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