update DR logging to log under one system
[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 java.io.File;\r
28 import java.io.FileInputStream;\r
29 import java.io.FileReader;\r
30 import java.io.IOException;\r
31 import java.io.LineNumberReader;\r
32 import java.sql.Connection;\r
33 import java.sql.DatabaseMetaData;\r
34 import java.sql.DriverManager;\r
35 import java.sql.ResultSet;\r
36 import java.sql.SQLException;\r
37 import java.sql.Statement;\r
38 import java.util.HashSet;\r
39 import java.util.LinkedList;\r
40 import java.util.NoSuchElementException;\r
41 import java.util.Properties;\r
42 import java.util.Queue;\r
43 import java.util.Set;\r
44 \r
45 import com.att.eelf.configuration.EELFLogger;\r
46 import com.att.eelf.configuration.EELFManager;\r
47 \r
48 /**\r
49  * Load the DB JDBC driver, and manage a simple pool of connections to the DB.\r
50  *\r
51  * @author Robert Eby\r
52  * @version $Id$\r
53  */\r
54 public class DB {\r
55 \r
56     private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
57 \r
58     private static String DB_URL;\r
59     private static String DB_LOGIN;\r
60     private static String DB_PASSWORD;\r
61     private static Properties props;\r
62     private static final Queue<Connection> queue = new LinkedList<>();\r
63 \r
64     private static String HTTPS_PORT;\r
65     private static String HTTP_PORT;\r
66 \r
67     /**\r
68      * Construct a DB object.  If this is the very first creation of this object, it will load a copy of the properties\r
69      * for the server, and attempt to load the JDBC driver for the database. If a fatal error occurs (e.g. either the\r
70      * properties file or the DB driver is missing), the JVM will exit.\r
71      */\r
72     public DB() {\r
73         if (props == null) {\r
74             props = new Properties();\r
75             try {\r
76                 props.load(new FileInputStream(System.getProperty(\r
77                     "org.onap.dmaap.datarouter.provserver.properties",\r
78                     "/opt/app/datartr/etc/provserver.properties")));\r
79                 String DB_DRIVER = (String) props.get("org.onap.dmaap.datarouter.db.driver");\r
80                 DB_URL = (String) props.get("org.onap.dmaap.datarouter.db.url");\r
81                 DB_LOGIN = (String) props.get("org.onap.dmaap.datarouter.db.login");\r
82                 DB_PASSWORD = (String) props.get("org.onap.dmaap.datarouter.db.password");\r
83                 HTTPS_PORT = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");\r
84                 HTTP_PORT = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");\r
85                 Class.forName(DB_DRIVER);\r
86             } catch (IOException e) {\r
87                 intlogger.error("PROV9003 Opening properties: " + e.getMessage());\r
88                 System.exit(1);\r
89             } catch (ClassNotFoundException e) {\r
90                 intlogger.error("PROV9004 cannot find the DB driver: " + e);\r
91                 System.exit(1);\r
92             }\r
93         }\r
94     }\r
95 \r
96     /**\r
97      * Get the provisioning server properties (loaded from provserver.properties).\r
98      *\r
99      * @return the Properties object\r
100      */\r
101     public Properties getProperties() {\r
102         return props;\r
103     }\r
104 \r
105     /**\r
106      * Get a JDBC connection to the DB from the pool.  Creates a new one if none are available.\r
107      *\r
108      * @return the Connection\r
109      */\r
110     @SuppressWarnings("resource")\r
111     public Connection getConnection() throws SQLException {\r
112         Connection connection = null;\r
113         while (connection == null) {\r
114             synchronized (queue) {\r
115                 try {\r
116                     connection = queue.remove();\r
117                 } catch (NoSuchElementException nseEx) {\r
118                     int n = 0;\r
119                     do {\r
120                         // Try up to 3 times to get a connection\r
121                         try {\r
122                             connection = DriverManager.getConnection(DB_URL, DB_LOGIN, DB_PASSWORD);\r
123                         } catch (SQLException sqlEx) {\r
124                             if (++n >= 3) {\r
125                                 throw sqlEx;\r
126                             }\r
127                         }\r
128                     } while (connection == null);\r
129                 }\r
130             }\r
131             if (connection != null && !connection.isValid(1)) {\r
132                 connection.close();\r
133                 connection = null;\r
134             }\r
135         }\r
136         return connection;\r
137     }\r
138 \r
139     /**\r
140      * Returns a JDBC connection to the pool.\r
141      *\r
142      * @param connection the Connection to return\r
143      */\r
144     public void release(Connection connection) {\r
145         if (connection != null) {\r
146             synchronized (queue) {\r
147                 if (!queue.contains(connection)) {\r
148                     queue.add(connection);\r
149                 }\r
150             }\r
151         }\r
152     }\r
153 \r
154     /**\r
155      * Run all necessary retrofits required to bring the database up to the level required for this version of the\r
156      * provisioning server.  This should be run before the server itself is started.\r
157      *\r
158      * @return true if all retrofits worked, false otherwise\r
159      */\r
160     public boolean runRetroFits() {\r
161         return retroFit1();\r
162     }\r
163 \r
164 \r
165     public static String getHttpsPort() {\r
166         return HTTPS_PORT;\r
167     }\r
168 \r
169     public static String getHttpPort() {\r
170         return HTTP_PORT;\r
171     }\r
172 \r
173     /**\r
174      * Retrofit 1 - Make sure the expected tables are in DB and are initialized. Uses sql_init_01.sql to setup the DB.\r
175      *\r
176      * @return true if the retrofit worked, false otherwise\r
177      */\r
178     private boolean retroFit1() {\r
179         final String[] expectedTables = {\r
180             "FEEDS", "FEED_ENDPOINT_ADDRS", "FEED_ENDPOINT_IDS", "PARAMETERS",\r
181             "SUBSCRIPTIONS", "LOG_RECORDS", "INGRESS_ROUTES", "EGRESS_ROUTES",\r
182             "NETWORK_ROUTES", "NODESETS", "NODES", "GROUPS"\r
183         };\r
184         Connection connection = null;\r
185         try {\r
186             connection = getConnection();\r
187             Set<String> actualTables = getTableSet(connection);\r
188             boolean initialize = false;\r
189             for (String tableName : expectedTables) {\r
190                 initialize |= !actualTables.contains(tableName);\r
191             }\r
192             if (initialize) {\r
193                 intlogger.info("PROV9001: First time startup; The database is being initialized.");\r
194                 runInitScript(connection, 1);\r
195             }\r
196         } catch (SQLException e) {\r
197             intlogger\r
198                 .error("PROV9000: The database credentials are not working: " + e.getMessage());\r
199             return false;\r
200         } finally {\r
201             if (connection != null) {\r
202                 release(connection);\r
203             }\r
204         }\r
205         return true;\r
206     }\r
207 \r
208     /**\r
209      * Get a set of all table names in the DB.\r
210      *\r
211      * @param connection a DB connection\r
212      * @return the set of table names\r
213      */\r
214     private Set<String> getTableSet(Connection connection) {\r
215         Set<String> tables = new HashSet<>();\r
216         try {\r
217             DatabaseMetaData md = connection.getMetaData();\r
218             ResultSet rs = md.getTables(null, null, "%", null);\r
219             if (rs != null) {\r
220                 while (rs.next()) {\r
221                     tables.add(rs.getString("TABLE_NAME").toUpperCase());\r
222                 }\r
223                 rs.close();\r
224             }\r
225         } catch (SQLException e) {\r
226             intlogger.error("PROV9010: Failed to get TABLE data from DB: " + e.getMessage());\r
227         }\r
228         return tables;\r
229     }\r
230 \r
231     /**\r
232      * Initialize the tables by running the initialization scripts located in the directory specified by the property\r
233      * <i>org.onap.dmaap.datarouter.provserver.dbscripts</i>.  Scripts have names of the form\r
234      * sql_init_NN.sql\r
235      *\r
236      * @param connection a DB connection\r
237      * @param scriptId the number of the sql_init_NN.sql script to run\r
238      */\r
239     private void runInitScript(Connection connection, int scriptId) {\r
240         String scriptDir = (String) props.get("org.onap.dmaap.datarouter.provserver.dbscripts");\r
241         StringBuilder strBuilder = new StringBuilder();\r
242         try {\r
243             String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);\r
244             if (!(new File(scriptFile)).exists()) {\r
245                 intlogger.error("PROV9005 Failed to load sql script from : " + scriptFile);\r
246                 System.exit(1);\r
247             }\r
248             LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));\r
249             String line;\r
250             while ((line = lineReader.readLine()) != null) {\r
251                 if (!line.startsWith("--")) {\r
252                     line = line.trim();\r
253                     strBuilder.append(line);\r
254                     if (line.endsWith(";")) {\r
255                         // Execute one DDL statement\r
256                         String sql = strBuilder.toString();\r
257                         strBuilder.setLength(0);\r
258                         Statement statement = connection.createStatement();\r
259                         statement.execute(sql);\r
260                         statement.close();\r
261                     }\r
262                 }\r
263             }\r
264             lineReader.close();\r
265             strBuilder.setLength(0);\r
266         } catch (Exception e) {\r
267             intlogger.error("PROV9002 Error when initializing table: " + e.getMessage());\r
268             System.exit(1);\r
269         }\r
270     }\r
271 }\r