Update for OOM integration
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / utils / DB.java
1 /*******************************************************************************\r
2  * ============LICENSE_START==================================================\r
3  * * org.onap.dmaap\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * *\r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * *\r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 \r
24 \r
25 package org.onap.dmaap.datarouter.provisioning.utils;\r
26 \r
27 import org.apache.log4j.Logger;\r
28 \r
29 import java.io.*;\r
30 import java.sql.*;\r
31 import java.util.*;\r
32 \r
33 /**\r
34  * Load the DB JDBC driver, and manage a simple pool of connections to the DB.\r
35  *\r
36  * @author Robert Eby\r
37  * @version $Id$\r
38  */\r
39 public class DB {\r
40 \r
41     /**\r
42      * The name of the properties file (in CLASSPATH)\r
43      */\r
44     private static String DB_URL;\r
45     private static String DB_LOGIN;\r
46     private static String DB_PASSWORD;\r
47     private static Properties props;\r
48     private static Logger intlogger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");\r
49     private static final Queue<Connection> queue = new LinkedList<>();\r
50 \r
51     public static String HTTPS_PORT;\r
52     public static String HTTP_PORT;\r
53 \r
54     /**\r
55      * Construct a DB object.  If this is the very first creation of this object, it will load a copy of the properties\r
56      * for the server, and attempt to load the JDBC driver for the database.  If a fatal error occurs (e.g. either the\r
57      * properties file or the DB driver is missing), the JVM will exit.\r
58      */\r
59     public DB() {\r
60         if (props == null) {\r
61             props = new Properties();\r
62             try {\r
63                 props.load(new FileInputStream(System.getProperty(\r
64                     "org.onap.dmaap.datarouter.provserver.properties",\r
65                     "/opt/app/datartr/etc/provserver.properties")));\r
66                 String DB_DRIVER = (String) props.get("org.onap.dmaap.datarouter.db.driver");\r
67                 DB_URL = (String) props.get("org.onap.dmaap.datarouter.db.url");\r
68                 DB_LOGIN = (String) props.get("org.onap.dmaap.datarouter.db.login");\r
69                 DB_PASSWORD = (String) props.get("org.onap.dmaap.datarouter.db.password");\r
70                 HTTPS_PORT = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");\r
71                 HTTP_PORT = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");\r
72                 Class.forName(DB_DRIVER);\r
73             } catch (IOException e) {\r
74                 intlogger.fatal("PROV9003 Opening properties: " + e.getMessage());\r
75                 e.printStackTrace();\r
76                 System.exit(1);\r
77             } catch (ClassNotFoundException e) {\r
78                 intlogger.fatal("PROV9004 cannot find the DB driver: " + e);\r
79                 e.printStackTrace();\r
80                 System.exit(1);\r
81             }\r
82         }\r
83     }\r
84 \r
85     /**\r
86      * Get the provisioning server properties (loaded from provserver.properties).\r
87      *\r
88      * @return the Properties object\r
89      */\r
90     public Properties getProperties() {\r
91         return props;\r
92     }\r
93 \r
94     /**\r
95      * Get a JDBC connection to the DB from the pool.  Creates a new one if none are available.\r
96      *\r
97      * @return the Connection\r
98      */\r
99     @SuppressWarnings("resource")\r
100     public Connection getConnection() throws SQLException {\r
101         Connection connection = null;\r
102         while (connection == null) {\r
103             synchronized (queue) {\r
104                 try {\r
105                     connection = queue.remove();\r
106                 } catch (NoSuchElementException nseEx) {\r
107                     int n = 0;\r
108                     do {\r
109                         // Try up to 3 times to get a connection\r
110                         try {\r
111                             connection = DriverManager.getConnection(DB_URL, DB_LOGIN, DB_PASSWORD);\r
112                         } catch (SQLException sqlEx) {\r
113                             if (++n >= 3) {\r
114                                 throw sqlEx;\r
115                             }\r
116                         }\r
117                     } while (connection == null);\r
118                 }\r
119             }\r
120             if (connection != null && !connection.isValid(1)) {\r
121                 connection.close();\r
122                 connection = null;\r
123             }\r
124         }\r
125         return connection;\r
126     }\r
127 \r
128     /**\r
129      * Returns a JDBC connection to the pool.\r
130      *\r
131      * @param connection the Connection to return\r
132      */\r
133     public void release(Connection connection) {\r
134         if (connection != null) {\r
135             synchronized (queue) {\r
136                 if (!queue.contains(connection)) {\r
137                     queue.add(connection);\r
138                 }\r
139             }\r
140         }\r
141     }\r
142 \r
143     /**\r
144      * Run all necessary retrofits required to bring the database up to the level required for this version of the\r
145      * provisioning server.  This should be run before the server itself is started.\r
146      *\r
147      * @return true if all retrofits worked, false otherwise\r
148      */\r
149     public boolean runRetroFits() {\r
150         return retroFit1();\r
151     }\r
152 \r
153     /**\r
154      * Retrofit 1 - Make sure the expected tables are in DB and are initialized. Uses sql_init_01.sql to setup the DB.\r
155      *\r
156      * @return true if the retrofit worked, false otherwise\r
157      */\r
158     private boolean retroFit1() {\r
159         final String[] expectedTables = {\r
160             "FEEDS", "FEED_ENDPOINT_ADDRS", "FEED_ENDPOINT_IDS", "PARAMETERS",\r
161             "SUBSCRIPTIONS", "LOG_RECORDS", "INGRESS_ROUTES", "EGRESS_ROUTES",\r
162             "NETWORK_ROUTES", "NODESETS", "NODES", "GROUPS"\r
163         };\r
164         Connection connection = null;\r
165         try {\r
166             connection = getConnection();\r
167             Set<String> actualTables = getTableSet(connection);\r
168             boolean initialize = false;\r
169             for (String table : expectedTables) {\r
170                 initialize |= !actualTables.contains(table.toLowerCase());\r
171             }\r
172             if (initialize) {\r
173                 intlogger.info("PROV9001: First time startup; The database is being initialized.");\r
174                 runInitScript(connection, 1);\r
175             }\r
176         } catch (SQLException e) {\r
177             intlogger.fatal("PROV9000: The database credentials are not working: " + e.getMessage());\r
178             return false;\r
179         } finally {\r
180             if (connection != null) {\r
181                 release(connection);\r
182             }\r
183         }\r
184         return true;\r
185     }\r
186 \r
187     /**\r
188      * Get a set of all table names in the DB.\r
189      *\r
190      * @param connection a DB connection\r
191      * @return the set of table names\r
192      */\r
193     private Set<String> getTableSet(Connection connection) {\r
194         Set<String> tables = new HashSet<String>();\r
195         try {\r
196             DatabaseMetaData md = connection.getMetaData();\r
197             ResultSet rs = md.getTables(null, null, "%", null);\r
198             if (rs != null) {\r
199                 while (rs.next()) {\r
200                     tables.add(rs.getString("TABLE_NAME"));\r
201                 }\r
202                 rs.close();\r
203             }\r
204         } catch (SQLException e) {\r
205             intlogger.fatal("PROV9010: Failed to get TABLE data from DB: " + e.getMessage());\r
206         }\r
207         return tables;\r
208     }\r
209 \r
210     /**\r
211      * Initialize the tables by running the initialization scripts located in the directory specified by the property\r
212      * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>.  Scripts have names of the form sql_init_NN.sql\r
213      *\r
214      * @param connection a DB connection\r
215      * @param scriptId the number of the sql_init_NN.sql script to run\r
216      */\r
217     private void runInitScript(Connection connection, int scriptId) {\r
218         String scriptDir = (String) props.get("org.onap.dmaap.datarouter.provserver.dbscripts");\r
219         StringBuilder strBuilder = new StringBuilder();\r
220         try {\r
221             String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);\r
222             if (!(new File(scriptFile)).exists()) {\r
223                 intlogger.fatal("PROV9005 Failed to load sql script from : " + scriptFile);\r
224                 System.exit(1);\r
225             }\r
226             LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));\r
227             String line;\r
228             while ((line = lineReader.readLine()) != null) {\r
229                 if (!line.startsWith("--")) {\r
230                     line = line.trim();\r
231                     strBuilder.append(line);\r
232                     if (line.endsWith(";")) {\r
233                         // Execute one DDL statement\r
234                         String sql = strBuilder.toString();\r
235                         strBuilder.setLength(0);\r
236                         Statement statement = connection.createStatement();\r
237                         statement.execute(sql);\r
238                         statement.close();\r
239                     }\r
240                 }\r
241             }\r
242             lineReader.close();\r
243             strBuilder.setLength(0);\r
244         } catch (Exception e) {\r
245             intlogger.fatal("PROV9002 Error when initializing table: " + e.getMessage());\r
246             System.exit(1);\r
247         }\r
248     }\r
249 }\r