From 0c28f36ff1b5e7b0ff2494b61c6dba4acb229337 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Fri, 13 Jun 2014 14:41:44 +0200 Subject: [PATCH] Fix a number of resource leaks reported by Coverity --- .../src/com/cloud/vm/dao/UserVmDaoImpl.java | 46 +++--- .../src/com/cloud/utils/db/Merovingian2.java | 8 +- .../com/cloud/utils/db/TransactionLegacy.java | 138 +++++++++--------- .../jobs/dao/AsyncJobJoinMapDaoImpl.java | 65 ++------- .../cloud/server/ConfigurationServerImpl.java | 42 +++--- 5 files changed, 129 insertions(+), 170 deletions(-) diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java index f35135f7f90..65a92aa3853 100755 --- a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java @@ -79,28 +79,28 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use ResourceTagDao _tagsDao; private static final String LIST_PODS_HAVING_VMS_FOR_ACCOUNT = - "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND (state = 'Running' OR state = 'Stopped') " - + "GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC"; + "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND (state = 'Running' OR state = 'Stopped') " + + "GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC"; private static final String VM_DETAILS = "select vm_instance.id, " - + "account.id, account.account_name, account.type, domain.name, instance_group.id, instance_group.name," - + "data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " - + "vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " - + "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " - + "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " - + "security_group.description, nics.id, nics.ip4_address, nics.default_nic, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, " + - "nics.isolation_uri, " - + "networks.traffic_type, networks.guest_type, user_ip_address.id, user_ip_address.public_ip_address from vm_instance " - + "left join account on vm_instance.account_id=account.id " + "left join domain on vm_instance.domain_id=domain.id " - + "left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " - + "left join instance_group on instance_group_vm_map.group_id=instance_group.id " + "left join data_center on vm_instance.data_center_id=data_center.id " - + "left join host on vm_instance.host_id=host.id " + "left join vm_template on vm_instance.vm_template_id=vm_template.id " - + "left join user_vm on vm_instance.id=user_vm.id " + "left join vm_template iso on iso.id=user_vm.iso_id " - + "left join service_offering on vm_instance.service_offering_id=service_offering.id " - + "left join disk_offering on vm_instance.service_offering_id=disk_offering.id " + "left join volumes on vm_instance.id=volumes.instance_id " - + "left join storage_pool on volumes.pool_id=storage_pool.id " + "left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id " - + "left join security_group on security_group_vm_map.security_group_id=security_group.id " + "left join nics on vm_instance.id=nics.instance_id " - + "left join networks on nics.network_id=networks.id " + "left join user_ip_address on user_ip_address.vm_id=vm_instance.id " + "where vm_instance.id in ("; + + "account.id, account.account_name, account.type, domain.name, instance_group.id, instance_group.name," + + "data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " + + "vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " + + "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " + + "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " + + "security_group.description, nics.id, nics.ip4_address, nics.default_nic, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, " + + "nics.isolation_uri, " + + "networks.traffic_type, networks.guest_type, user_ip_address.id, user_ip_address.public_ip_address from vm_instance " + + "left join account on vm_instance.account_id=account.id " + "left join domain on vm_instance.domain_id=domain.id " + + "left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " + + "left join instance_group on instance_group_vm_map.group_id=instance_group.id " + "left join data_center on vm_instance.data_center_id=data_center.id " + + "left join host on vm_instance.host_id=host.id " + "left join vm_template on vm_instance.vm_template_id=vm_template.id " + + "left join user_vm on vm_instance.id=user_vm.id " + "left join vm_template iso on iso.id=user_vm.iso_id " + + "left join service_offering on vm_instance.service_offering_id=service_offering.id " + + "left join disk_offering on vm_instance.service_offering_id=disk_offering.id " + "left join volumes on vm_instance.id=volumes.instance_id " + + "left join storage_pool on volumes.pool_id=storage_pool.id " + "left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id " + + "left join security_group on security_group_vm_map.security_group_id=security_group.id " + "left join nics on vm_instance.id=nics.instance_id " + + "left join networks on nics.network_id=networks.id " + "left join user_ip_address on user_ip_address.vm_id=vm_instance.id " + "where vm_instance.id in ("; private static final int VM_DETAILS_BATCH_SIZE = 100; @@ -186,7 +186,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use AccountDataCenterVirtualSearch.and("account", AccountDataCenterVirtualSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountDataCenterVirtualSearch.and("dc", AccountDataCenterVirtualSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); AccountDataCenterVirtualSearch.join("nicSearch", nicSearch, AccountDataCenterVirtualSearch.entity().getId(), nicSearch.entity().getInstanceId(), - JoinBuilder.JoinType.INNER); + JoinBuilder.JoinType.INNER); AccountDataCenterVirtualSearch.done(); UserVmByIsoSearch = createSearchBuilder(); @@ -217,7 +217,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use @Override public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData, boolean displayVm, - boolean isDynamicallyScalable, String customId, String hostName, String instanceName) { + boolean isDynamicallyScalable, String customId, String hostName, String instanceName) { UserVmVO vo = createForUpdate(); vo.setDisplayName(displayName); vo.setHaEnabled(enable); @@ -413,6 +413,8 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use rs.close(); curr_index += VM_DETAILS_BATCH_SIZE; } + if (pstmt != null) + pstmt.close(); } if (curr_index < userVmDataList.size()) { diff --git a/framework/db/src/com/cloud/utils/db/Merovingian2.java b/framework/db/src/com/cloud/utils/db/Merovingian2.java index 6eeea9f3850..89f9e61d877 100644 --- a/framework/db/src/com/cloud/utils/db/Merovingian2.java +++ b/framework/db/src/com/cloud/utils/db/Merovingian2.java @@ -40,7 +40,7 @@ public class Merovingian2 extends StandardMBean implements MerovingianMBean { private static final Logger s_logger = Logger.getLogger(Merovingian2.class); private static final String ACQUIRE_SQL = - "INSERT INTO op_lock (op_lock.key, op_lock.mac, op_lock.ip, op_lock.thread, op_lock.acquired_on, waiters) VALUES (?, ?, ?, ?, ?, 1)"; + "INSERT INTO op_lock (op_lock.key, op_lock.mac, op_lock.ip, op_lock.thread, op_lock.acquired_on, waiters) VALUES (?, ?, ?, ?, ?, 1)"; private static final String INCREMENT_SQL = "UPDATE op_lock SET waiters=waiters+1 where op_lock.key=? AND op_lock.mac=? AND op_lock.ip=? AND op_lock.thread=?"; private static final String SELECT_SQL = "SELECT op_lock.key, mac, ip, thread, acquired_on, waiters FROM op_lock"; private static final String INQUIRE_SQL = SELECT_SQL + " WHERE op_lock.key=?"; @@ -428,7 +428,7 @@ public class Merovingian2 extends StandardMBean implements MerovingianMBean { pstmt.setInt(3, threadId); int rows = pstmt.executeUpdate(); assert (false) : "Abandon hope, all ye who enter here....There were still " + rows + ":" + c + - " locks not released when the transaction ended, check for lock not released or @DB is not added to the code that using the locks!"; + " locks not released when the transaction ended, check for lock not released or @DB is not added to the code that using the locks!"; } catch (SQLException e) { throw new CloudRuntimeException("Can't clear locks " + pstmt, e); } finally { @@ -444,9 +444,7 @@ public class Merovingian2 extends StandardMBean implements MerovingianMBean { @Override public boolean releaseLockAsLastResortAndIReallyKnowWhatIAmDoing(String key) { s_logger.info("Releasing a lock from JMX lck-" + key); - PreparedStatement pstmt = null; - try { - pstmt = _concierge.conn().prepareStatement(RELEASE_LOCK_SQL); + try (PreparedStatement pstmt = _concierge.conn().prepareStatement(RELEASE_LOCK_SQL)) { pstmt.setString(1, key); int rows = pstmt.executeUpdate(); return rows > 0; diff --git a/framework/db/src/com/cloud/utils/db/TransactionLegacy.java b/framework/db/src/com/cloud/utils/db/TransactionLegacy.java index ac0ea21d1f1..f50cbe2044e 100755 --- a/framework/db/src/com/cloud/utils/db/TransactionLegacy.java +++ b/framework/db/src/com/cloud/utils/db/TransactionLegacy.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.utils.db; +import java.io.Closeable; import java.io.File; import java.io.IOException; import java.sql.Connection; @@ -60,7 +61,7 @@ import com.cloud.utils.mgmt.JmxUtil; * Note that this class is not synchronous but it doesn't need to be because * it is stored with TLS and is one per thread. Use appropriately. */ -public class TransactionLegacy { +public class TransactionLegacy implements Closeable { private static final Logger s_logger = Logger.getLogger(Transaction.class.getName() + "." + "Transaction"); private static final Logger s_stmtLogger = Logger.getLogger(Transaction.class.getName() + "." + "Statement"); private static final Logger s_lockLogger = Logger.getLogger(Transaction.class.getName() + "." + "Lock"); @@ -114,7 +115,7 @@ public class TransactionLegacy { assert txn != null : "No Transaction on stack. Did you mark the method with @DB?"; assert checkAnnotation(4, txn) : "Did you even read the guide to use Transaction...IOW...other people's code? Try method can't be private. What about @DB? hmmm... could that be it? " + - txn; + txn; } return txn; } @@ -326,11 +327,11 @@ public class TransactionLegacy { } str.append("-") - .append(stacks[i].getClassName().substring(stacks[i].getClassName().lastIndexOf(".") + 1)) - .append(".") - .append(stacks[i].getMethodName()) - .append(":") - .append(stacks[i].getLineNumber()); + .append(stacks[i].getClassName().substring(stacks[i].getClassName().lastIndexOf(".") + 1)) + .append(".") + .append(stacks[i].getMethodName()) + .append(":") + .append(stacks[i].getLineNumber()); j++; i++; } @@ -340,7 +341,7 @@ public class TransactionLegacy { return ""; } - public TransactionLegacy(final String name, final boolean forLocking, final short databaseId) { + private TransactionLegacy(final String name, final boolean forLocking, final short databaseId) { _name = name; _conn = null; _stack = new LinkedList(); @@ -557,42 +558,42 @@ public class TransactionLegacy { public Connection getConnection() throws SQLException { if (_conn == null) { switch (_dbId) { - case CLOUD_DB: - if (s_ds != null) { - _conn = s_ds.getConnection(); - } else { - s_logger.warn("A static-initialized variable becomes null, process is dying?"); - throw new CloudRuntimeException("Database is not initialized, process is dying?"); - } - break; - case USAGE_DB: - if (s_usageDS != null) { - _conn = s_usageDS.getConnection(); - } else { - s_logger.warn("A static-initialized variable becomes null, process is dying?"); - throw new CloudRuntimeException("Database is not initialized, process is dying?"); - } - break; - case AWSAPI_DB: - if (s_awsapiDS != null) { - _conn = s_awsapiDS.getConnection(); - } else { - s_logger.warn("A static-initialized variable becomes null, process is dying?"); - throw new CloudRuntimeException("Database is not initialized, process is dying?"); - } - break; + case CLOUD_DB: + if (s_ds != null) { + _conn = s_ds.getConnection(); + } else { + s_logger.warn("A static-initialized variable becomes null, process is dying?"); + throw new CloudRuntimeException("Database is not initialized, process is dying?"); + } + break; + case USAGE_DB: + if (s_usageDS != null) { + _conn = s_usageDS.getConnection(); + } else { + s_logger.warn("A static-initialized variable becomes null, process is dying?"); + throw new CloudRuntimeException("Database is not initialized, process is dying?"); + } + break; + case AWSAPI_DB: + if (s_awsapiDS != null) { + _conn = s_awsapiDS.getConnection(); + } else { + s_logger.warn("A static-initialized variable becomes null, process is dying?"); + throw new CloudRuntimeException("Database is not initialized, process is dying?"); + } + break; - case SIMULATOR_DB: - if (s_simulatorDS != null) { - _conn = s_simulatorDS.getConnection(); - } else { - s_logger.warn("A static-initialized variable becomes null, process is dying?"); - throw new CloudRuntimeException("Database is not initialized, process is dying?"); - } - break; - default: + case SIMULATOR_DB: + if (s_simulatorDS != null) { + _conn = s_simulatorDS.getConnection(); + } else { + s_logger.warn("A static-initialized variable becomes null, process is dying?"); + throw new CloudRuntimeException("Database is not initialized, process is dying?"); + } + break; + default: - throw new CloudRuntimeException("No database selected for the transaction"); + throw new CloudRuntimeException("No database selected for the transaction"); } _conn.setAutoCommit(!_txn); @@ -604,7 +605,7 @@ public class TransactionLegacy { _stack.push(new StackElement(CREATE_CONN, null)); if (s_connLogger.isTraceEnabled()) { s_connLogger.trace("Creating a DB connection with " + (_txn ? " txn: " : " no txn: ") + " for " + _dbId + ": dbconn" + System.identityHashCode(_conn) + - ". Stack: " + buildName()); + ". Stack: " + buildName()); } } else { s_logger.trace("conn: Using existing DB connection"); @@ -666,6 +667,7 @@ public class TransactionLegacy { } } + @Override public void close() { removeUpTo(CURRENT_TXN, null); @@ -981,7 +983,7 @@ public class TransactionLegacy { return _stack; } - protected TransactionLegacy() { + private TransactionLegacy() { _name = null; _conn = null; _stack = null; @@ -1094,18 +1096,18 @@ public class TransactionLegacy { } final GenericObjectPool cloudConnectionPool = - new GenericObjectPool(null, cloudMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, cloudMaxWait, cloudMaxIdle, cloudTestOnBorrow, false, - cloudTimeBtwEvictionRunsMillis, 1, cloudMinEvcitableIdleTimeMillis, cloudTestWhileIdle); + new GenericObjectPool(null, cloudMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, cloudMaxWait, cloudMaxIdle, cloudTestOnBorrow, false, + cloudTimeBtwEvictionRunsMillis, 1, cloudMinEvcitableIdleTimeMillis, cloudTestWhileIdle); final ConnectionFactory cloudConnectionFactory = - new DriverManagerConnectionFactory("jdbc:mysql://" + cloudHost + (s_dbHAEnabled ? "," + cloudSlaves : "") + ":" + cloudPort + "/" + cloudDbName + - "?autoReconnect=" + cloudAutoReconnect + (url != null ? "&" + url : "") + (useSSL ? "&useSSL=true" : "") + - (s_dbHAEnabled ? "&" + cloudDbHAParams : "") + (s_dbHAEnabled ? "&loadBalanceStrategy=" + loadBalanceStrategy : ""), cloudUsername, cloudPassword); + new DriverManagerConnectionFactory("jdbc:mysql://" + cloudHost + (s_dbHAEnabled ? "," + cloudSlaves : "") + ":" + cloudPort + "/" + cloudDbName + + "?autoReconnect=" + cloudAutoReconnect + (url != null ? "&" + url : "") + (useSSL ? "&useSSL=true" : "") + + (s_dbHAEnabled ? "&" + cloudDbHAParams : "") + (s_dbHAEnabled ? "&loadBalanceStrategy=" + loadBalanceStrategy : ""), cloudUsername, cloudPassword); final KeyedObjectPoolFactory poolableObjFactory = (cloudPoolPreparedStatements ? new StackKeyedObjectPoolFactory() : null); final PoolableConnectionFactory cloudPoolableConnectionFactory = - new PoolableConnectionFactory(cloudConnectionFactory, cloudConnectionPool, poolableObjFactory, cloudValidationQuery, false, false, isolationLevel); + new PoolableConnectionFactory(cloudConnectionFactory, cloudConnectionPool, poolableObjFactory, cloudValidationQuery, false, false, isolationLevel); // Default Data Source for CloudStack s_ds = new PoolingDataSource(cloudPoolableConnectionFactory.getPool()); @@ -1123,16 +1125,16 @@ public class TransactionLegacy { final String usageUrl = dbProps.getProperty("db.usage.url.params"); final GenericObjectPool usageConnectionPool = - new GenericObjectPool(null, usageMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, usageMaxWait, usageMaxIdle); + new GenericObjectPool(null, usageMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, usageMaxWait, usageMaxIdle); final ConnectionFactory usageConnectionFactory = - new DriverManagerConnectionFactory("jdbc:mysql://" + usageHost + (s_dbHAEnabled ? "," + dbProps.getProperty("db.cloud.slaves") : "") + ":" + usagePort + - "/" + usageDbName + "?autoReconnect=" + usageAutoReconnect + (usageUrl != null ? "&" + usageUrl : "") + - (s_dbHAEnabled ? "&" + getDBHAParams("usage", dbProps) : "") + (s_dbHAEnabled ? "&loadBalanceStrategy=" + loadBalanceStrategy : ""), usageUsername, - usagePassword); + new DriverManagerConnectionFactory("jdbc:mysql://" + usageHost + (s_dbHAEnabled ? "," + dbProps.getProperty("db.cloud.slaves") : "") + ":" + usagePort + + "/" + usageDbName + "?autoReconnect=" + usageAutoReconnect + (usageUrl != null ? "&" + usageUrl : "") + + (s_dbHAEnabled ? "&" + getDBHAParams("usage", dbProps) : "") + (s_dbHAEnabled ? "&loadBalanceStrategy=" + loadBalanceStrategy : ""), usageUsername, + usagePassword); final PoolableConnectionFactory usagePoolableConnectionFactory = - new PoolableConnectionFactory(usageConnectionFactory, usageConnectionPool, new StackKeyedObjectPoolFactory(), null, false, false); + new PoolableConnectionFactory(usageConnectionFactory, usageConnectionPool, new StackKeyedObjectPoolFactory(), null, false, false); // Data Source for usage server s_usageDS = new PoolingDataSource(usagePoolableConnectionFactory.getPool()); @@ -1140,13 +1142,13 @@ public class TransactionLegacy { // Configure awsapi db final String awsapiDbName = dbProps.getProperty("db.awsapi.name"); final GenericObjectPool awsapiConnectionPool = - new GenericObjectPool(null, usageMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, usageMaxWait, usageMaxIdle); + new GenericObjectPool(null, usageMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, usageMaxWait, usageMaxIdle); final ConnectionFactory awsapiConnectionFactory = - new DriverManagerConnectionFactory("jdbc:mysql://" + cloudHost + (s_dbHAEnabled ? "," + cloudSlaves : "") + ":" + cloudPort + "/" + awsapiDbName + - "?autoReconnect=" + cloudAutoReconnect + (s_dbHAEnabled ? "&" + cloudDbHAParams : "") + - (s_dbHAEnabled ? "&loadBalanceStrategy=" + loadBalanceStrategy : ""), cloudUsername, cloudPassword); + new DriverManagerConnectionFactory("jdbc:mysql://" + cloudHost + (s_dbHAEnabled ? "," + cloudSlaves : "") + ":" + cloudPort + "/" + awsapiDbName + + "?autoReconnect=" + cloudAutoReconnect + (s_dbHAEnabled ? "&" + cloudDbHAParams : "") + + (s_dbHAEnabled ? "&loadBalanceStrategy=" + loadBalanceStrategy : ""), cloudUsername, cloudPassword); final PoolableConnectionFactory awsapiPoolableConnectionFactory = - new PoolableConnectionFactory(awsapiConnectionFactory, awsapiConnectionPool, new StackKeyedObjectPoolFactory(), null, false, false); + new PoolableConnectionFactory(awsapiConnectionFactory, awsapiConnectionPool, new StackKeyedObjectPoolFactory(), null, false, false); // Data Source for awsapi s_awsapiDS = new PoolingDataSource(awsapiPoolableConnectionFactory.getPool()); @@ -1164,14 +1166,14 @@ public class TransactionLegacy { final boolean simulatorAutoReconnect = Boolean.parseBoolean(dbProps.getProperty("db.simulator.autoReconnect")); final GenericObjectPool simulatorConnectionPool = - new GenericObjectPool(null, simulatorMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, simulatorMaxWait, simulatorMaxIdle); + new GenericObjectPool(null, simulatorMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, simulatorMaxWait, simulatorMaxIdle); final ConnectionFactory simulatorConnectionFactory = - new DriverManagerConnectionFactory("jdbc:mysql://" + simulatorHost + ":" + simulatorPort + "/" + simulatorDbName + "?autoReconnect=" + - simulatorAutoReconnect, simulatorUsername, simulatorPassword); + new DriverManagerConnectionFactory("jdbc:mysql://" + simulatorHost + ":" + simulatorPort + "/" + simulatorDbName + "?autoReconnect=" + + simulatorAutoReconnect, simulatorUsername, simulatorPassword); final PoolableConnectionFactory simulatorPoolableConnectionFactory = - new PoolableConnectionFactory(simulatorConnectionFactory, simulatorConnectionPool, new StackKeyedObjectPoolFactory(), null, false, false); + new PoolableConnectionFactory(simulatorConnectionFactory, simulatorConnectionPool, new StackKeyedObjectPoolFactory(), null, false, false); s_simulatorDS = new PoolingDataSource(simulatorPoolableConnectionFactory.getPool()); } catch (Exception e) { s_logger.debug("Simulator DB properties are not available. Not initializing simulator DS"); @@ -1181,8 +1183,8 @@ public class TransactionLegacy { s_usageDS = getDefaultDataSource("cloud_usage"); s_simulatorDS = getDefaultDataSource("cloud_simulator"); s_logger.warn( - "Unable to load db configuration, using defaults with 5 connections. Falling back on assumed datasource on localhost:3306 using username:password=cloud:cloud. Please check your configuration", - e); + "Unable to load db configuration, using defaults with 5 connections. Falling back on assumed datasource on localhost:3306 using username:password=cloud:cloud. Please check your configuration", + e); } } @@ -1203,7 +1205,7 @@ public class TransactionLegacy { final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://localhost:3306/" + database, "cloud", "cloud"); final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); return new PoolingDataSource( - /* connectionPool */poolableConnectionFactory.getPool()); + /* connectionPool */poolableConnectionFactory.getPool()); } /** diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java index 7bc29db8cbe..d70864c755b 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java @@ -75,7 +75,7 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase standaloneList = new ArrayList(); TransactionLegacy txn = TransactionLegacy.currentTxn(); String sql = "SELECT job_id FROM async_job_join_map WHERE join_job_id = ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)"; - try { - PreparedStatement pstmt = txn.prepareStatement(sql); + try (PreparedStatement pstmt = txn.prepareStatement(sql)) { pstmt.setLong(1, joinedJobId); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { @@ -231,19 +230,22 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase findJobsToWakeBetween(Date cutDate) { List standaloneList = new ArrayList(); TransactionLegacy txn = TransactionLegacy.currentTxn(); - try { - String sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)"; - PreparedStatement pstmt = txn.prepareStatement(sql); + + String sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)"; + try (PreparedStatement pstmt = txn.prepareStatement(sql)) { pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { standaloneList.add(rs.getLong(1)); } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to handle SQL exception", e); + } - // update for next wake-up - sql = "UPDATE async_job_join_map SET next_wakeup=DATE_ADD(next_wakeup, INTERVAL wakeup_interval SECOND) WHERE next_wakeup < ? AND expiration > ?"; - pstmt = txn.prepareStatement(sql); + // update for next wake-up + sql = "UPDATE async_job_join_map SET next_wakeup=DATE_ADD(next_wakeup, INTERVAL wakeup_interval SECOND) WHERE next_wakeup < ? AND expiration > ?"; + try (PreparedStatement pstmt = txn.prepareStatement(sql)) { pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); pstmt.executeUpdate(); @@ -252,51 +254,6 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase wakeupByJoinedJobCompletion(long joinedJobId) { -// List standaloneList = new ArrayList(); -// -// TransactionLegacy txn = TransactionLegacy.currentTxn(); -// PreparedStatement pstmt = null; -// try { -// txn.start(); -// -// // -// // performance sensitive processing, do it in plain SQL -// // -// String sql = "UPDATE async_job SET job_pending_signals=? WHERE id IN " + -// "(SELECT job_id FROM async_job_join_map WHERE join_job_id = ?)"; -// pstmt = txn.prepareStatement(sql); -// pstmt.setInt(1, AsyncJob.Contants.SIGNAL_MASK_WAKEUP); -// pstmt.setLong(2, joinedJobId); -// pstmt.executeUpdate(); -// pstmt.close(); -// -// sql = "UPDATE sync_queue_item SET queue_proc_msid=NULL, queue_proc_number=NULL WHERE content_id IN " + -// "(SELECT job_id FROM async_job_join_map WHERE join_job_id = ?)"; -// pstmt = txn.prepareStatement(sql); -// pstmt.setLong(1, joinedJobId); -// pstmt.executeUpdate(); -// pstmt.close(); -// -// sql = "SELECT job_id FROM async_job_join_map WHERE join_job_id = ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)"; -// pstmt = txn.prepareStatement(sql); -// pstmt.setLong(1, joinedJobId); -// ResultSet rs = pstmt.executeQuery(); -// while(rs.next()) { -// standaloneList.add(rs.getLong(1)); -// } -// rs.close(); -// pstmt.close(); -// -// txn.commit(); -// } catch (SQLException e) { -// s_logger.error("Unexpected exception", e); -// } -// -// return standaloneList; -// } } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 95c961169a1..694f3cdd2ff 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -745,12 +745,12 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio // FIXME: take a global database lock here for safety. boolean onWindows = isOnWindows(); if(!onWindows) { - Script.runSimpleBashScript("if [ -f " + privkeyfile + " ]; then rm -f " + privkeyfile + "; fi; ssh-keygen -t rsa -N '' -f " + privkeyfile + " -q"); + Script.runSimpleBashScript("if [ -f " + privkeyfile + " ]; then rm -f " + privkeyfile + "; fi; ssh-keygen -t rsa -N '' -f " + privkeyfile + " -q"); } byte[] arr1 = new byte[4094]; // configuration table column value size - try { - new DataInputStream(new FileInputStream(privkeyfile)).readFully(arr1); + try (DataInputStream dis = new DataInputStream(new FileInputStream(privkeyfile))) { + dis.readFully(arr1); } catch (EOFException e) { } catch (Exception e) { s_logger.error("Cannot read the private key file", e); @@ -758,8 +758,8 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio } String privateKey = new String(arr1).trim(); byte[] arr2 = new byte[4094]; // configuration table column value size - try { - new DataInputStream(new FileInputStream(pubkeyfile)).readFully(arr2); + try (DataInputStream dis = new DataInputStream(new FileInputStream(pubkeyfile))) { + dis.readFully(arr2); } catch (EOFException e) { } catch (Exception e) { s_logger.warn("Cannot read the public key file", e); @@ -893,9 +893,9 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio } Script command = null; if(isOnWindows()) { - command = new Script("python", s_logger); + command = new Script("python", s_logger); } else { - command = new Script("/bin/bash", s_logger); + command = new Script("/bin/bash", s_logger); } command.add(scriptPath); command.add(publicKeyPath); @@ -911,20 +911,20 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio } protected String getInjectScript() { - String injectScript = null; - boolean onWindows = isOnWindows(); - if(onWindows) { - injectScript = "scripts/vm/systemvm/injectkeys.py"; - } else { - injectScript = "scripts/vm/systemvm/injectkeys.sh"; - } - return injectScript; + String injectScript = null; + boolean onWindows = isOnWindows(); + if(onWindows) { + injectScript = "scripts/vm/systemvm/injectkeys.py"; + } else { + injectScript = "scripts/vm/systemvm/injectkeys.sh"; + } + return injectScript; } protected boolean isOnWindows() { - String os = System.getProperty("os.name", "generic").toLowerCase(); - boolean onWindows = (os != null && os.startsWith("windows")); - return onWindows; + String os = System.getProperty("os.name", "generic").toLowerCase(); + boolean onWindows = (os != null && os.startsWith("windows")); + return onWindows; } @DB @@ -1186,9 +1186,9 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio // Offering #5 NetworkOfferingVO defaultNetscalerNetworkOffering = - new NetworkOfferingVO(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, - "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, false, true, null, null, true, - Availability.Optional, null, Network.GuestType.Shared, true, false, false, false, true, true, true, false, false, true, true, false, false, false); + new NetworkOfferingVO(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, + "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, false, true, null, null, true, + Availability.Optional, null, Network.GuestType.Shared, true, false, false, false, true, true, true, false, false, true, true, false, false, false); defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled); defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering);