19 package org.sleuthkit.autopsy.centralrepository.datamodel;
21 import java.sql.Connection;
22 import java.sql.ResultSet;
23 import java.sql.SQLException;
24 import java.sql.Statement;
25 import java.util.concurrent.TimeUnit;
26 import java.util.logging.Level;
27 import org.apache.commons.dbcp2.BasicDataSource;
28 import org.openide.util.NbBundle.Messages;
36 final class PostgresEamDb
extends AbstractSqlEamDb {
38 private final static Logger LOGGER = Logger.
getLogger(PostgresEamDb.class.getName());
40 private final static String CONFLICT_CLAUSE =
"ON CONFLICT DO NOTHING";
42 private static PostgresEamDb instance;
44 private static final int CONN_POOL_SIZE = 10;
45 private BasicDataSource connectionPool = null;
47 private final PostgresEamDbSettings dbSettings;
57 public synchronized static PostgresEamDb getInstance() throws EamDbException {
58 if (instance == null) {
59 instance =
new PostgresEamDb();
71 private PostgresEamDb() throws EamDbException {
72 dbSettings =
new PostgresEamDbSettings();
73 bulkArtifactsThreshold = dbSettings.getBulkThreshold();
77 public void shutdownConnections() throws EamDbException {
80 if (connectionPool != null) {
81 connectionPool.close();
82 connectionPool = null;
86 }
catch (SQLException ex) {
87 throw new EamDbException(
"Failed to close existing database connections.", ex);
92 public void updateSettings() {
94 dbSettings.loadSettings();
95 bulkArtifactsThreshold = dbSettings.getBulkThreshold();
100 public void saveSettings() {
101 synchronized (
this) {
102 dbSettings.saveSettings();
107 public void reset() throws EamDbException {
108 Connection conn = connect();
111 Statement dropContent = conn.createStatement();
112 dropContent.executeUpdate(
"TRUNCATE TABLE organizations RESTART IDENTITY CASCADE");
113 dropContent.executeUpdate(
"TRUNCATE TABLE cases RESTART IDENTITY CASCADE");
114 dropContent.executeUpdate(
"TRUNCATE TABLE data_sources RESTART IDENTITY CASCADE");
115 dropContent.executeUpdate(
"TRUNCATE TABLE reference_sets RESTART IDENTITY CASCADE");
116 dropContent.executeUpdate(
"TRUNCATE TABLE correlation_types RESTART IDENTITY CASCADE");
117 dropContent.executeUpdate(
"TRUNCATE TABLE db_info RESTART IDENTITY CASCADE");
119 String instancesTemplate =
"TRUNCATE TABLE %s_instances RESTART IDENTITY CASCADE";
120 String referencesTemplate =
"TRUNCATE TABLE reference_%s RESTART IDENTITY CASCADE";
121 for (CorrelationAttributeInstance.Type type : defaultCorrelationTypes) {
122 dropContent.executeUpdate(String.format(instancesTemplate, type.getDbTableName()));
124 if (type.getId() == CorrelationAttributeInstance.FILES_TYPE_ID) {
125 dropContent.executeUpdate(String.format(referencesTemplate, type.getDbTableName()));
128 }
catch (SQLException ex) {
129 LOGGER.log(Level.WARNING,
"Failed to reset database.", ex);
131 EamDbUtil.closeConnection(conn);
134 dbSettings.insertDefaultDatabaseContent();
141 private void setupConnectionPool() throws EamDbException {
142 connectionPool =
new BasicDataSource();
143 connectionPool.setUsername(dbSettings.getUserName());
144 connectionPool.setPassword(dbSettings.getPassword());
145 connectionPool.setDriverClassName(dbSettings.getDriver());
147 StringBuilder connectionURL =
new StringBuilder();
148 connectionURL.append(dbSettings.getJDBCBaseURI());
149 connectionURL.append(dbSettings.getHost());
150 connectionURL.append(
":");
151 connectionURL.append(dbSettings.getPort());
152 connectionURL.append(
"/");
153 connectionURL.append(dbSettings.getDbName());
155 connectionPool.setUrl(connectionURL.toString());
156 connectionPool.setUsername(dbSettings.getUserName());
157 connectionPool.setPassword(dbSettings.getPassword());
160 connectionPool.setInitialSize(5);
161 connectionPool.setMaxIdle(CONN_POOL_SIZE);
162 connectionPool.setValidationQuery(dbSettings.getValidationQuery());
175 protected Connection connect(
boolean foreignKeys)
throws EamDbException {
187 @Messages({
"PostgresEamDb.centralRepoDisabled.message=Central Repository module is not enabled.",
188 "PostgresEamDb.connectionFailed.message=Error getting connection to database."})
190 protected Connection connect() throws EamDbException {
191 synchronized (
this) {
192 if (!EamDb.isEnabled()) {
193 throw new EamDbException(
"Central Repository module is not enabled", Bundle.PostgresEamDb_centralRepoDisabled_message());
196 if (connectionPool == null) {
197 setupConnectionPool();
201 return connectionPool.getConnection();
202 }
catch (SQLException ex) {
203 throw new EamDbException(
"Error getting connection from connection pool.", Bundle.PostgresEamDb_connectionFailed_message(), ex);
208 protected String getConflictClause() {
209 return CONFLICT_CLAUSE;
224 @Messages({
"PostgresEamDb.multiUserLockError.message=Error acquiring database lock"})
225 public CoordinationService.Lock getExclusiveMultiUserDbLock()
throws EamDbException {
228 if (!UserPreferences.getIsMultiUserModeEnabled()) {
232 String databaseNodeName = dbSettings.getHost() +
"_" + dbSettings.getDbName();
233 CoordinationService.Lock lock = CoordinationService.getInstance().tryGetExclusiveLock(CoordinationService.CategoryNode.CENTRAL_REPO, databaseNodeName, 5, TimeUnit.MINUTES);
238 throw new EamDbException(
"Error acquiring database lock", Bundle.PostgresEamDb_multiUserLockError_message());
239 }
catch (InterruptedException ex) {
240 throw new EamDbException(
"Error acquiring database lock", Bundle.PostgresEamDb_multiUserLockError_message(), ex);
241 }
catch (CoordinationService.CoordinationServiceException ex) {
248 boolean doesColumnExist(Connection conn, String tableName, String columnName)
throws SQLException {
249 final String objectIdColumnExistsTemplate =
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='%s' AND column_name='%s')";
250 ResultSet resultSet = null;
251 Statement statement = null;
252 boolean columnExists =
false;
254 statement = conn.createStatement();
255 resultSet = statement.executeQuery(String.format(objectIdColumnExistsTemplate, tableName, columnName));
256 if (resultSet.next()) {
257 columnExists = resultSet.getBoolean(1);
260 EamDbUtil.closeResultSet(resultSet);
261 EamDbUtil.closeStatement(statement);
synchronized static Logger getLogger(String name)