Release DR images via self release
[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 package org.onap.dmaap.datarouter.provisioning.utils;\r
25 \r
26 import static java.lang.System.exit;\r
27 import static java.lang.System.getProperty;\r
28 \r
29 import com.att.eelf.configuration.EELFLogger;\r
30 import com.att.eelf.configuration.EELFManager;\r
31 import java.io.File;\r
32 import java.io.FileInputStream;\r
33 import java.io.FileReader;\r
34 import java.io.IOException;\r
35 import java.io.LineNumberReader;\r
36 import java.sql.Connection;\r
37 import java.sql.DatabaseMetaData;\r
38 import java.sql.DriverManager;\r
39 import java.sql.ResultSet;\r
40 import java.sql.SQLException;\r
41 import java.sql.Statement;\r
42 import java.util.HashSet;\r
43 import java.util.LinkedList;\r
44 import java.util.NoSuchElementException;\r
45 import java.util.Properties;\r
46 import java.util.Queue;\r
47 import java.util.Set;\r
48 \r
49 /**\r
50  * Load the DB JDBC driver, and manage a simple pool of connections to the DB.\r
51  *\r
52  * @author Robert Eby\r
53  * @version $Id$\r
54  */\r
55 public class DB {\r
56 \r
57     private static EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");\r
58 \r
59     private static String dbUrl;\r
60     private static String dbLogin;\r
61     private static String dbPassword;\r
62     private static Properties props;\r
63     private static final Queue<Connection> queue = new LinkedList<>();\r
64 \r
65     private static String httpsPort;\r
66     private static String httpPort;\r
67 \r
68     /**\r
69      * Construct a DB object.  If this is the very first creation of this object, it will load a copy of the properties\r
70      * for the server, and attempt to load the JDBC driver for the database. If a fatal error occurs (e.g. either the\r
71      * properties file or the DB driver is missing), the JVM will exit.\r
72      */\r
73     public DB() {\r
74         if (props == null) {\r
75             props = new Properties();\r
76             try {\r
77                 props.load(new FileInputStream(getProperty(\r
78                     "org.onap.dmaap.datarouter.provserver.properties",\r
79                     "/opt/app/datartr/etc/provserver.properties")));\r
80                 dbUrl = (String) props.get("org.onap.dmaap.datarouter.db.url");\r
81                 dbLogin = (String) props.get("org.onap.dmaap.datarouter.db.login");\r
82                 dbPassword = (String) props.get("org.onap.dmaap.datarouter.db.password");\r
83                 httpsPort = (String) props.get("org.onap.dmaap.datarouter.provserver.https.port");\r
84                 httpPort = (String) props.get("org.onap.dmaap.datarouter.provserver.http.port");\r
85                 String dbDriver = (String) props.get("org.onap.dmaap.datarouter.db.driver");\r
86                 Class.forName(dbDriver);\r
87             } catch (IOException e) {\r
88                 intlogger.error("PROV9003 Opening properties: " + e.getMessage(), e);\r
89                 exit(1);\r
90             } catch (ClassNotFoundException e) {\r
91                 intlogger.error("PROV9004 cannot find the DB driver: " + e);\r
92                 exit(1);\r
93             }\r
94         }\r
95     }\r
96 \r
97     /**\r
98      * Get the provisioning server properties (loaded from provserver.properties).\r
99      *\r
100      * @return the Properties object\r
101      */\r
102     public Properties getProperties() {\r
103         return props;\r
104     }\r
105 \r
106     /**\r
107      * Get a JDBC connection to the DB from the pool.  Creates a new one if none are available.\r
108      *\r
109      * @return the Connection\r
110      */\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 ignore) {\r
118                     int num = 0;\r
119                     do {\r
120                         // Try up to 3 times to get a connection\r
121                         try {\r
122                             connection = DriverManager.getConnection(dbUrl, dbLogin, dbPassword);\r
123                         } catch (SQLException sqlEx) {\r
124                             if (++num >= 3) {\r
125                                 throw sqlEx;\r
126                             }\r
127                         }\r
128                     }\r
129                     while (connection == null);\r
130                 }\r
131             }\r
132             if (connection != null && !connection.isValid(1)) {\r
133                 connection.close();\r
134                 connection = null;\r
135             }\r
136         }\r
137         return connection;\r
138     }\r
139 \r
140     /**\r
141      * Returns a JDBC connection to the pool.\r
142      *\r
143      * @param connection the Connection to return\r
144      */\r
145     public void release(Connection connection) {\r
146         if (connection != null) {\r
147             synchronized (queue) {\r
148                 if (!queue.contains(connection)) {\r
149                     queue.add(connection);\r
150                 }\r
151             }\r
152         }\r
153     }\r
154 \r
155     /**\r
156      * Run all necessary retrofits required to bring the database up to the level required for this version of the\r
157      * provisioning server.  This should be run before the server itself is started.\r
158      *\r
159      * @return true if all retrofits worked, false otherwise\r
160      */\r
161     public boolean runRetroFits() {\r
162         return retroFit1();\r
163     }\r
164 \r
165 \r
166     public static String getHttpsPort() {\r
167         return httpsPort;\r
168     }\r
169 \r
170     public static String getHttpPort() {\r
171         return httpPort;\r
172     }\r
173 \r
174     /**\r
175      * Retrofit 1 - Make sure the expected tables are in DB and are initialized. Uses sql_init_01.sql to setup the DB.\r
176      *\r
177      * @return true if the retrofit worked, false otherwise\r
178      */\r
179     private boolean retroFit1() {\r
180         final String[] expectedTables = {\r
181             "FEEDS", "FEED_ENDPOINT_ADDRS", "FEED_ENDPOINT_IDS", "PARAMETERS",\r
182             "SUBSCRIPTIONS", "LOG_RECORDS", "INGRESS_ROUTES", "EGRESS_ROUTES",\r
183             "NETWORK_ROUTES", "NODESETS", "NODES", "GROUPS"\r
184         };\r
185         Connection connection = null;\r
186         try {\r
187             connection = getConnection();\r
188             Set<String> actualTables = getTableSet(connection);\r
189             boolean initialize = false;\r
190             for (String tableName : expectedTables) {\r
191                 initialize |= !actualTables.contains(tableName);\r
192             }\r
193             if (initialize) {\r
194                 intlogger.info("PROV9001: First time startup; The database is being initialized.");\r
195                 runInitScript(connection, 1);\r
196             }\r
197         } catch (SQLException e) {\r
198             intlogger.error("PROV9000: The database credentials are not working: " + e.getMessage(), e);\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(), e);\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         String scriptFile = String.format("%s/sql_init_%02d.sql", scriptDir, scriptId);\r
242         if (!(new File(scriptFile)).exists()) {\r
243             intlogger.error("PROV9005 Failed to load sql script from : " + scriptFile);\r
244             exit(1);\r
245         }\r
246         try (LineNumberReader lineReader = new LineNumberReader(new FileReader(scriptFile));\r
247                 Statement statement = connection.createStatement()) {\r
248             StringBuilder strBuilder = new StringBuilder();\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                     executeDdlStatement(statement, strBuilder, line);\r
255                 }\r
256             }\r
257             strBuilder.setLength(0);\r
258         } catch (Exception e) {\r
259             intlogger.error("PROV9002 Error when initializing table: " + e.getMessage(), e);\r
260             exit(1);\r
261         }\r
262     }\r
263 \r
264     private void executeDdlStatement(Statement statement, StringBuilder strBuilder, String line) throws SQLException {\r
265         if (line.endsWith(";")) {\r
266             // Execute one DDL statement\r
267             String sql = strBuilder.toString();\r
268             strBuilder.setLength(0);\r
269             statement.execute(sql);\r
270         }\r
271     }\r
272 }\r