http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efe1e0a5/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java ---------------------------------------------------------------------- diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java index dab2b46..b32947a 100755 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java @@ -117,75 +117,47 @@ public class Upgrade410to420 implements DbUpgrade { } private void createFullCloneFlag(Connection conn) { - ResultSet rs = null; - PreparedStatement delete = null; - PreparedStatement query = null; - PreparedStatement update = null; + String update_sql; int numRows = 0; - try { - delete = conn.prepareStatement("delete from `cloud`.`configuration` where name='vmware.create.full.clone';"); + try (PreparedStatement delete = conn.prepareStatement("delete from `cloud`.`configuration` where name='vmware.create.full.clone';");) + { delete.executeUpdate(); - query = conn.prepareStatement("select count(*) from `cloud`.`data_center`"); - rs = query.executeQuery(); - if (rs.next()) { - numRows = rs.getInt(1); - } - if (numRows > 0) { - update = - conn.prepareStatement("insert into `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'UserVmManager', 'vmware.create.full.clone' , 'false', 'If set to true, creates VMs as full clones on ESX hypervisor');"); - } else { - update = - conn.prepareStatement("insert into `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'UserVmManager', 'vmware.create.full.clone' , 'true', 'If set to true, creates VMs as full clones on ESX hypervisor');"); + try(PreparedStatement query = conn.prepareStatement("select count(*) from `cloud`.`data_center`");) + { + try(ResultSet rs = query.executeQuery();) { + if (rs.next()) { + numRows = rs.getInt(1); + } + if (numRows > 0) { + update_sql = "insert into `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'UserVmManager', 'vmware.create.full.clone' , 'false', 'If set to true, creates VMs as full clones on ESX hypervisor');"; + } else { + update_sql = "insert into `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'UserVmManager', 'vmware.create.full.clone' , 'true', 'If set to true, creates VMs as full clones on ESX hypervisor');"; + } + try(PreparedStatement update_pstmt = conn.prepareStatement(update_sql);) { + update_pstmt.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Failed to set global flag vmware.create.full.clone: ", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Failed to set global flag vmware.create.full.clone: ", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Failed to set global flag vmware.create.full.clone: ", e); } - update.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Failed to set global flag vmware.create.full.clone: ", e); - } finally { - if (update != null) { - try { - update.close(); - } catch (SQLException e) { - - } - } - if (query != null) { - try { - query.close(); - } catch (SQLException e) { - - } - } - if (delete != null) { - try { - delete.close(); - } catch (SQLException e) { - - } - } } } private void migrateVolumeOnSecondaryStorage(Connection conn) { - PreparedStatement sql = null; - try { - sql = conn.prepareStatement("update `cloud`.`volumes` set state='Uploaded' where state='UploadOp'"); + try (PreparedStatement sql = conn.prepareStatement("update `cloud`.`volumes` set state='Uploaded' where state='UploadOp'");){ sql.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Failed to upgrade volume state: ", e); - } finally { - if (sql != null) { - try { - sql.close(); - } catch (SQLException e) { - - } - } } } private void persistVswitchConfiguration(Connection conn) { - PreparedStatement clustersQuery = null; - ResultSet clusters = null; Long clusterId; String clusterHypervisorType; final String NEXUS_GLOBAL_CONFIG_PARAM_NAME = "vmware.use.nexus.vswitch"; @@ -200,36 +172,39 @@ public class Upgrade410to420 implements DbUpgrade { String guestVswitchType = VMWARE_STANDARD_VSWITCH; Map<Long, List<Pair<String, String>>> detailsMap = new HashMap<Long, List<Pair<String, String>>>(); List<Pair<String, String>> detailsList; - - try { - clustersQuery = conn.prepareStatement("select id, hypervisor_type from `cloud`.`cluster` where removed is NULL"); - clusters = clustersQuery.executeQuery(); - while (clusters.next()) { - clusterHypervisorType = clusters.getString("hypervisor_type"); - clusterId = clusters.getLong("id"); - if (clusterHypervisorType.equalsIgnoreCase("VMware")) { - if (!readGlobalConfigParam) { - paramValStr = getConfigurationParameter(conn, VSWITCH_GLOBAL_CONFIG_PARAM_CATEGORY, NEXUS_GLOBAL_CONFIG_PARAM_NAME); - if (paramValStr.equalsIgnoreCase("true")) { - nexusEnabled = true; + try (PreparedStatement clustersQuery = conn.prepareStatement("select id, hypervisor_type from `cloud`.`cluster` where removed is NULL");){ + try(ResultSet clusters = clustersQuery.executeQuery();) { + while (clusters.next()) { + clusterHypervisorType = clusters.getString("hypervisor_type"); + clusterId = clusters.getLong("id"); + if (clusterHypervisorType.equalsIgnoreCase("VMware")) { + if (!readGlobalConfigParam) { + paramValStr = getConfigurationParameter(conn, VSWITCH_GLOBAL_CONFIG_PARAM_CATEGORY, NEXUS_GLOBAL_CONFIG_PARAM_NAME); + if (paramValStr.equalsIgnoreCase("true")) { + nexusEnabled = true; + } } - } - if (nexusEnabled) { - publicVswitchType = NEXUS_1000V_DVSWITCH; - guestVswitchType = NEXUS_1000V_DVSWITCH; - } - detailsList = new ArrayList<Pair<String, String>>(); - detailsList.add(new Pair<String, String>(ApiConstants.VSWITCH_TYPE_GUEST_TRAFFIC, guestVswitchType)); - detailsList.add(new Pair<String, String>(ApiConstants.VSWITCH_TYPE_PUBLIC_TRAFFIC, publicVswitchType)); - detailsMap.put(clusterId, detailsList); + if (nexusEnabled) { + publicVswitchType = NEXUS_1000V_DVSWITCH; + guestVswitchType = NEXUS_1000V_DVSWITCH; + } + detailsList = new ArrayList<Pair<String, String>>(); + detailsList.add(new Pair<String, String>(ApiConstants.VSWITCH_TYPE_GUEST_TRAFFIC, guestVswitchType)); + detailsList.add(new Pair<String, String>(ApiConstants.VSWITCH_TYPE_PUBLIC_TRAFFIC, publicVswitchType)); + detailsMap.put(clusterId, detailsList); - updateClusterDetails(conn, detailsMap); - s_logger.debug("Persist vSwitch Configuration: Successfully persisted vswitch configuration for cluster " + clusterId); - } else { - s_logger.debug("Persist vSwitch Configuration: Ignoring cluster " + clusterId + " with hypervisor type " + clusterHypervisorType); - continue; - } - } // End cluster iteration + updateClusterDetails(conn, detailsMap); + s_logger.debug("Persist vSwitch Configuration: Successfully persisted vswitch configuration for cluster " + clusterId); + } else { + s_logger.debug("Persist vSwitch Configuration: Ignoring cluster " + clusterId + " with hypervisor type " + clusterHypervisorType); + continue; + } + } // End cluster iteration + }catch (SQLException e) { + String msg = "Unable to persist vswitch configuration of VMware clusters." + e.getMessage(); + s_logger.error(msg); + throw new CloudRuntimeException(msg, e); + } if (nexusEnabled) { // If Nexus global parameter is true, then set DVS configuration parameter to true. TODOS: Document that this mandates that MS need to be restarted. @@ -239,21 +214,10 @@ public class Upgrade410to420 implements DbUpgrade { String msg = "Unable to persist vswitch configuration of VMware clusters." + e.getMessage(); s_logger.error(msg); throw new CloudRuntimeException(msg, e); - } finally { - try { - if (clusters != null) { - clusters.close(); - } - if (clustersQuery != null) { - clustersQuery.close(); - } - } catch (SQLException e) { - } } } private void updateClusterDetails(Connection conn, Map<Long, List<Pair<String, String>>> detailsMap) { - PreparedStatement clusterDetailsInsert = null; // Insert cluster details into cloud.cluster_details table for existing VMware clusters // Input parameter detailMap is a map of clusterId and list of key value pairs for that cluster Long clusterId; @@ -265,204 +229,148 @@ public class Upgrade410to420 implements DbUpgrade { while (clusterIt.hasNext()) { clusterId = clusterIt.next(); keyValues = detailsMap.get(clusterId); - clusterDetailsInsert = conn.prepareStatement("INSERT INTO `cloud`.`cluster_details` (cluster_id, name, value) VALUES (?, ?, ?)"); - for (Pair<String, String> keyValuePair : keyValues) { - key = keyValuePair.first(); - val = keyValuePair.second(); - clusterDetailsInsert.setLong(1, clusterId); - clusterDetailsInsert.setString(2, key); - clusterDetailsInsert.setString(3, val); - clusterDetailsInsert.executeUpdate(); + try( PreparedStatement clusterDetailsInsert = conn.prepareStatement("INSERT INTO `cloud`.`cluster_details` (cluster_id, name, value) VALUES (?, ?, ?)");) { + for (Pair<String, String> keyValuePair : keyValues) { + key = keyValuePair.first(); + val = keyValuePair.second(); + clusterDetailsInsert.setLong(1, clusterId); + clusterDetailsInsert.setString(2, key); + clusterDetailsInsert.setString(3, val); + clusterDetailsInsert.executeUpdate(); + } + s_logger.debug("Inserted vswitch configuration details into cloud.cluster_details for cluster with id " + clusterId + "."); + }catch (SQLException e) { + throw new CloudRuntimeException("Unable insert cluster details into cloud.cluster_details table.", e); } - s_logger.debug("Inserted vswitch configuration details into cloud.cluster_details for cluster with id " + clusterId + "."); } - } catch (SQLException e) { + } catch (RuntimeException e) { throw new CloudRuntimeException("Unable insert cluster details into cloud.cluster_details table.", e); - } finally { - try { - if (clusterDetailsInsert != null) { - clusterDetailsInsert.close(); - } - } catch (SQLException e) { - } } } private String getConfigurationParameter(Connection conn, String category, String paramName) { - ResultSet rs = null; - PreparedStatement pstmt = null; - try { - pstmt = - conn.prepareStatement("select value from `cloud`.`configuration` where category='" + category + "' and value is not NULL and name = '" + paramName + "';"); - rs = pstmt.executeQuery(); - while (rs.next()) { - return rs.getString("value"); + try (PreparedStatement pstmt = + conn.prepareStatement("select value from `cloud`.`configuration` where category='" + category + "' and value is not NULL and name = '" + paramName + "';");) + { + try(ResultSet rs = pstmt.executeQuery();) { + while (rs.next()) { + return rs.getString("value"); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable read global configuration parameter " + paramName + ". ", e); } } catch (SQLException e) { throw new CloudRuntimeException("Unable read global configuration parameter " + paramName + ". ", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } } return "false"; } private void setConfigurationParameter(Connection conn, String category, String paramName, String paramVal) { - PreparedStatement pstmt = null; - try { - pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = '" + paramVal + "' WHERE name = '" + paramName + "';"); + try (PreparedStatement pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = '" + paramVal + "' WHERE name = '" + paramName + "';");) + { s_logger.debug("Updating global configuration parameter " + paramName + " with value " + paramVal + ". Update SQL statement is " + pstmt); pstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Unable to set global configuration parameter " + paramName + " to " + paramVal + ". ", e); - } finally { - try { - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } } } private void movePrivateZoneToDedicatedResource(Connection conn) { - - PreparedStatement pstmt = null; - ResultSet rs = null; - PreparedStatement pstmtUpdate = null; - PreparedStatement pstmt3 = null; - ResultSet rs3 = null; - - try { - - pstmt3 = conn.prepareStatement("SELECT distinct(`domain_id`) FROM `cloud`.`data_center` WHERE `domain_id` IS NOT NULL AND removed IS NULL"); - rs3 = pstmt3.executeQuery(); - - while (rs3.next()) { - long domainId = rs3.getLong(1); - long affinityGroupId = 0; - - // create or find an affinity group for this domain of type - // 'ExplicitDedication' - PreparedStatement pstmt2 = null; - ResultSet rs2 = null; - pstmt2 = - conn.prepareStatement("SELECT affinity_group.id FROM `cloud`.`affinity_group` INNER JOIN `cloud`.`affinity_group_domain_map` ON affinity_group.id=affinity_group_domain_map.affinity_group_id WHERE affinity_group.type = 'ExplicitDedication' AND affinity_group.acl_type = 'Domain' AND (affinity_group_domain_map.domain_id = ?)"); - pstmt2.setLong(1, domainId); - rs2 = pstmt2.executeQuery(); - if (rs2.next()) { - // group exists, use it - affinityGroupId = rs2.getLong(1); - } else { - // create new group - rs2.close(); - pstmt2.close(); - - pstmt2 = conn.prepareStatement("SELECT name FROM `cloud`.`domain` where id = ?"); - pstmt2.setLong(1, domainId); - rs2 = pstmt2.executeQuery(); - String domainName = ""; - if (rs2.next()) { - domainName = rs2.getString(1); + String domainName = ""; + try (PreparedStatement sel_dc_dom_id = conn.prepareStatement("SELECT distinct(`domain_id`) FROM `cloud`.`data_center` WHERE `domain_id` IS NOT NULL AND removed IS NULL");) { + try (ResultSet rs3 = sel_dc_dom_id.executeQuery();) { + while (rs3.next()) { + long domainId = rs3.getLong(1); + long affinityGroupId = 0; + // create or find an affinity group for this domain of type + // 'ExplicitDedication' + try (PreparedStatement sel_aff_grp_pstmt = + conn.prepareStatement("SELECT affinity_group.id FROM `cloud`.`affinity_group` INNER JOIN `cloud`.`affinity_group_domain_map` ON affinity_group.id=affinity_group_domain_map.affinity_group_id WHERE affinity_group.type = 'ExplicitDedication' AND affinity_group.acl_type = 'Domain' AND (affinity_group_domain_map.domain_id = ?)");) { + sel_aff_grp_pstmt.setLong(1, domainId); + try (ResultSet rs2 = sel_aff_grp_pstmt.executeQuery();) { + if (rs2.next()) { + // group exists, use it + affinityGroupId = rs2.getLong(1); + } else { + // create new group + try (PreparedStatement sel_dom_id_pstmt = conn.prepareStatement("SELECT name FROM `cloud`.`domain` where id = ?");) { + sel_dom_id_pstmt.setLong(1, domainId); + try (ResultSet sel_dom_id_res = sel_dom_id_pstmt.executeQuery();) { + if (sel_dom_id_res.next()) { + domainName = sel_dom_id_res.getString(1); + } + } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); + } + // create new domain level group for this domain + String type = "ExplicitDedication"; + String uuid = UUID.randomUUID().toString(); + String groupName = "DedicatedGrp-domain-" + domainName; + s_logger.debug("Adding AffinityGroup of type " + type + " for domain id " + domainId); + String sql = + "INSERT INTO `cloud`.`affinity_group` (`name`, `type`, `uuid`, `description`, `domain_id`, `account_id`, `acl_type`) VALUES (?, ?, ?, ?, 1, 1, 'Domain')"; + try (PreparedStatement insert_pstmt = conn.prepareStatement(sql);) { + insert_pstmt.setString(1, groupName); + insert_pstmt.setString(2, type); + insert_pstmt.setString(3, uuid); + insert_pstmt.setString(4, "dedicated resources group"); + insert_pstmt.executeUpdate(); + try (PreparedStatement sel_aff_pstmt = conn.prepareStatement("SELECT affinity_group.id FROM `cloud`.`affinity_group` where uuid = ?");) { + sel_aff_pstmt.setString(1, uuid); + try (ResultSet sel_aff_res = sel_aff_pstmt.executeQuery();) { + if (sel_aff_res.next()) { + affinityGroupId = sel_aff_res.getLong(1); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); + } + // add the domain map + String sqlMap = "INSERT INTO `cloud`.`affinity_group_domain_map` (`domain_id`, `affinity_group_id`) VALUES (?, ?)"; + try (PreparedStatement pstmtUpdate = conn.prepareStatement(sqlMap);) { + pstmtUpdate.setLong(1, domainId); + pstmtUpdate.setLong(2, affinityGroupId); + pstmtUpdate.executeUpdate(); + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); + } + } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); } - rs2.close(); - pstmt2.close(); - // create new domain level group for this domain - String type = "ExplicitDedication"; - String uuid = UUID.randomUUID().toString(); - String groupName = "DedicatedGrp-domain-" + domainName; - s_logger.debug("Adding AffinityGroup of type " + type + " for domain id " + domainId); - - String sql = - "INSERT INTO `cloud`.`affinity_group` (`name`, `type`, `uuid`, `description`, `domain_id`, `account_id`, `acl_type`) VALUES (?, ?, ?, ?, 1, 1, 'Domain')"; - pstmtUpdate = conn.prepareStatement(sql); - pstmtUpdate.setString(1, groupName); - pstmtUpdate.setString(2, type); - pstmtUpdate.setString(3, uuid); - pstmtUpdate.setString(4, "dedicated resources group"); - pstmtUpdate.executeUpdate(); - pstmtUpdate.close(); - - pstmt2 = conn.prepareStatement("SELECT affinity_group.id FROM `cloud`.`affinity_group` where uuid = ?"); - pstmt2.setString(1, uuid); - rs2 = pstmt2.executeQuery(); - if (rs2.next()) { - affinityGroupId = rs2.getLong(1); + try (PreparedStatement sel_pstmt = conn.prepareStatement("SELECT `id` FROM `cloud`.`data_center` WHERE `domain_id` = ? AND removed IS NULL");) { + sel_pstmt.setLong(1, domainId); + try (ResultSet sel_pstmt_rs = sel_pstmt.executeQuery();) { + while (sel_pstmt_rs.next()) { + long zoneId = sel_pstmt_rs.getLong(1); + dedicateZone(conn, zoneId, domainId, affinityGroupId); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); } - - // add the domain map - String sqlMap = "INSERT INTO `cloud`.`affinity_group_domain_map` (`domain_id`, `affinity_group_id`) VALUES (?, ?)"; - pstmtUpdate = conn.prepareStatement(sqlMap); - pstmtUpdate.setLong(1, domainId); - pstmtUpdate.setLong(2, affinityGroupId); - pstmtUpdate.executeUpdate(); - pstmtUpdate.close(); - - } - - rs2.close(); - pstmt2.close(); - - pstmt = conn.prepareStatement("SELECT `id` FROM `cloud`.`data_center` WHERE `domain_id` = ? AND removed IS NULL"); - pstmt.setLong(1, domainId); - rs = pstmt.executeQuery(); - - while (rs.next()) { - long zoneId = rs.getLong(1); - dedicateZone(conn, zoneId, domainId, affinityGroupId); } + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); } - - } catch (SQLException e) { + }catch (SQLException e) { throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); - } finally { - if (pstmtUpdate != null) { - try { - pstmtUpdate.close(); - } catch (SQLException e) { - } - } - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - } - } - if (pstmt != null) { - try { - pstmt.close(); - } catch (SQLException e) { - } - } - if (rs3 != null) { - try { - rs3.close(); - } catch (SQLException e) { - } - } - if (pstmt3 != null) { - try { - pstmt3.close(); - } catch (SQLException e) { - } - } - } } - private void dedicateZone(Connection conn, long zoneId, long domainId, long affinityGroupId) { - PreparedStatement pstmtUpdate2 = null; - try { + try( PreparedStatement pstmtUpdate2 = conn.prepareStatement("INSERT INTO `cloud`.`dedicated_resources` (`uuid`,`data_center_id`, `domain_id`, `affinity_group_id`) VALUES (?, ?, ?, ?)");) { // create the dedicated resources entry - String sql = "INSERT INTO `cloud`.`dedicated_resources` (`uuid`,`data_center_id`, `domain_id`, `affinity_group_id`) VALUES (?, ?, ?, ?)"; - pstmtUpdate2 = conn.prepareStatement(sql); pstmtUpdate2.setString(1, UUID.randomUUID().toString()); pstmtUpdate2.setLong(2, zoneId); pstmtUpdate2.setLong(3, domainId); @@ -471,13 +379,6 @@ public class Upgrade410to420 implements DbUpgrade { pstmtUpdate2.close(); } catch (SQLException e) { throw new CloudRuntimeException("Exception while saving zone to dedicated resources", e); - } finally { - if (pstmtUpdate2 != null) { - try { - pstmtUpdate2.close(); - } catch (SQLException e) { - } - } } } @@ -494,39 +395,43 @@ public class Upgrade410to420 implements DbUpgrade { keys.add("fk_external_pxe_devices_physical_network_id"); DbUpgradeUtils.dropKeysIfExist(conn, "baremetal_pxe_devices", keys, true); - PreparedStatement pstmt = null; - try { - pstmt = - conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_nsp_id` FOREIGN KEY (`nsp_id`) REFERENCES `physical_network_service_providers` (`id`) ON DELETE CASCADE"); - pstmt.executeUpdate(); - pstmt.close(); - pstmt = - conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE"); - pstmt.executeUpdate(); - pstmt.close(); - pstmt.close(); - pstmt = - conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE"); - pstmt.executeUpdate(); - pstmt.close(); + try (PreparedStatement alter_pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_nsp_id` FOREIGN KEY (`nsp_id`) REFERENCES `physical_network_service_providers` (`id`) ON DELETE CASCADE");) + { + alter_pstmt.executeUpdate(); + try(PreparedStatement alter_pstmt_id = + conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE"); + ) { + alter_pstmt_id.executeUpdate(); + try(PreparedStatement alter_pstmt_phy_net = + conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE");) + { + alter_pstmt_phy_net.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to add foreign keys to baremetal_dhcp_devices table", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to add foreign keys to baremetal_dhcp_devices table", e); + } s_logger.debug("Added foreign keys for table baremetal_dhcp_devices"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add foreign keys to baremetal_dhcp_devices table", e); } - - try { - pstmt = - conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_nsp_id` FOREIGN KEY (`nsp_id`) REFERENCES `physical_network_service_providers` (`id`) ON DELETE CASCADE"); - pstmt.executeUpdate(); - pstmt.close(); - pstmt = - conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE"); - pstmt.executeUpdate(); - pstmt.close(); - pstmt = - conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE"); - pstmt.executeUpdate(); - pstmt.close(); + try (PreparedStatement alter_pxe_pstmt = + conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_nsp_id` FOREIGN KEY (`nsp_id`) REFERENCES `physical_network_service_providers` (`id`) ON DELETE CASCADE");) + { + alter_pxe_pstmt.executeUpdate(); + try(PreparedStatement alter_pxe_id_pstmt = + conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE");) { + alter_pxe_id_pstmt.executeUpdate(); + try(PreparedStatement alter_pxe_phy_net_pstmt = + conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE");) { + alter_pxe_phy_net_pstmt.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to add foreign keys to baremetal_pxe_devices table", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to add foreign keys to baremetal_pxe_devices table", e); + } s_logger.debug("Added foreign keys for table baremetal_pxe_devices"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add foreign keys to baremetal_pxe_devices table", e); @@ -534,169 +439,121 @@ public class Upgrade410to420 implements DbUpgrade { } private void addIndexForAlert(Connection conn) { - //First drop if it exists. (Due to patches shipped to customers some will have the index and some wont.) List<String> indexList = new ArrayList<String>(); s_logger.debug("Dropping index i_alert__last_sent if it exists"); indexList.add("last_sent"); // in 4.1, we created this index that is not in convention. indexList.add("i_alert__last_sent"); DbUpgradeUtils.dropKeysIfExist(conn, "alert", indexList, false); - //Now add index. - PreparedStatement pstmt = null; - try { - pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`alert` ADD INDEX `i_alert__last_sent`(`last_sent`)"); + try(PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`alert` ADD INDEX `i_alert__last_sent`(`last_sent`)");) + { pstmt.executeUpdate(); s_logger.debug("Added index i_alert__last_sent for table alert"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add index i_alert__last_sent to alert table for the column last_sent", e); - } finally { - try { - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } } - } private void dropUploadTable(Connection conn) { - - PreparedStatement pstmt0 = null; - PreparedStatement pstmt1 = null; - PreparedStatement pstmt2 = null; - PreparedStatement pstmt3 = null; - - ResultSet rs0 = null; - ResultSet rs2 = null; - - try { + try(PreparedStatement pstmt0 = conn.prepareStatement("SELECT url, created, type_id, host_id from upload where type=?");) { // Read upload table - Templates s_logger.debug("Populating template_store_ref table"); - pstmt0 = conn.prepareStatement("SELECT url, created, type_id, host_id from upload where type=?"); pstmt0.setString(1, "TEMPLATE"); - rs0 = pstmt0.executeQuery(); - pstmt1 = conn.prepareStatement("UPDATE template_store_ref SET download_url=?, download_url_created=? where template_id=? and store_id=?"); - - //Update template_store_ref - while (rs0.next()) { - pstmt1.setString(1, rs0.getString("url")); - pstmt1.setDate(2, rs0.getDate("created")); - pstmt1.setLong(3, rs0.getLong("type_id")); - pstmt1.setLong(4, rs0.getLong("host_id")); - pstmt1.executeUpdate(); - } - - // Read upload table - Volumes - s_logger.debug("Populating volume store ref table"); - pstmt2 = conn.prepareStatement("SELECT url, created, type_id, host_id, install_path from upload where type=?"); - pstmt2.setString(1, "VOLUME"); - rs2 = pstmt2.executeQuery(); - - pstmt3 = - conn.prepareStatement("INSERT IGNORE INTO volume_store_ref (volume_id, store_id, zone_id, created, state, download_url, download_url_created, install_path) VALUES (?,?,?,?,?,?,?,?)"); - //insert into template_store_ref - while (rs2.next()) { - pstmt3.setLong(1, rs2.getLong("type_id")); - pstmt3.setLong(2, rs2.getLong("host_id")); - pstmt3.setLong(3, 1l);// ??? - pstmt3.setDate(4, rs2.getDate("created")); - pstmt3.setString(5, "Ready"); - pstmt3.setString(6, rs2.getString("url")); - pstmt3.setDate(7, rs2.getDate("created")); - pstmt3.setString(8, rs2.getString("install_path")); - pstmt3.executeUpdate(); + try(ResultSet rs0 = pstmt0.executeQuery();) + { + try(PreparedStatement pstmt1 = conn.prepareStatement("UPDATE template_store_ref SET download_url=?, download_url_created=? where template_id=? and store_id=?");) { + //Update template_store_ref + while (rs0.next()) { + pstmt1.setString(1, rs0.getString("url")); + pstmt1.setDate(2, rs0.getDate("created")); + pstmt1.setLong(3, rs0.getLong("type_id")); + pstmt1.setLong(4, rs0.getLong("host_id")); + pstmt1.executeUpdate(); + } + // Read upload table - Volumes + s_logger.debug("Populating volume store ref table"); + try(PreparedStatement pstmt2 = conn.prepareStatement("SELECT url, created, type_id, host_id, install_path from upload where type=?");) { + pstmt2.setString(1, "VOLUME"); + try(ResultSet rs2 = pstmt2.executeQuery();) { + + try(PreparedStatement pstmt3 = + conn.prepareStatement("INSERT IGNORE INTO volume_store_ref (volume_id, store_id, zone_id, created, state, download_url, download_url_created, install_path) VALUES (?,?,?,?,?,?,?,?)");) { + //insert into template_store_ref + while (rs2.next()) { + pstmt3.setLong(1, rs2.getLong("type_id")); + pstmt3.setLong(2, rs2.getLong("host_id")); + pstmt3.setLong(3, 1l);// ??? + pstmt3.setDate(4, rs2.getDate("created")); + pstmt3.setString(5, "Ready"); + pstmt3.setString(6, rs2.getString("url")); + pstmt3.setDate(7, rs2.getDate("created")); + pstmt3.setString(8, rs2.getString("install_path")); + pstmt3.executeUpdate(); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e); } } catch (SQLException e) { throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e); - } finally { - try { - if (pstmt0 != null) { - pstmt0.close(); - } - if (pstmt1 != null) { - pstmt1.close(); - } - if (pstmt2 != null) { - pstmt2.close(); - } - if (pstmt3 != null) { - pstmt3.close(); - } - } catch (SQLException e) { - } } - } //KVM snapshot flag: only turn on if Customers is using snapshot; private void setKVMSnapshotFlag(Connection conn) { s_logger.debug("Verify and set the KVM snapshot flag if snapshot was used. "); - PreparedStatement pstmt = null; - ResultSet rs = null; - try { + try(PreparedStatement pstmt = conn.prepareStatement("select count(*) from `cloud`.`snapshots` where hypervisor_type = 'KVM'");) + { int numRows = 0; - pstmt = conn.prepareStatement("select count(*) from `cloud`.`snapshots` where hypervisor_type = 'KVM'"); - rs = pstmt.executeQuery(); - if (rs.next()) { - numRows = rs.getInt(1); - } - rs.close(); - pstmt.close(); - if (numRows > 0) { - //Add the configuration flag - pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = 'kvm.snapshot.enabled'"); - pstmt.setString(1, "true"); - pstmt.executeUpdate(); - } - } catch (SQLException e) { - throw new CloudRuntimeException("Failed to read the snapshot table for KVM upgrade. ", e); - } finally { - try { - if (rs != null) { - rs.close(); + try(ResultSet rs = pstmt.executeQuery();) { + if (rs.next()) { + numRows = rs.getInt(1); } - - if (pstmt != null) { - pstmt.close(); + if (numRows > 0) { + //Add the configuration flag + try(PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = 'kvm.snapshot.enabled'");) { + update_pstmt.setString(1, "true"); + update_pstmt.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Failed to read the snapshot table for KVM upgrade. ", e); + } } - } catch (SQLException e) { + }catch (SQLException e) { + throw new CloudRuntimeException("Failed to read the snapshot table for KVM upgrade. ", e); } + } catch (SQLException e) { + throw new CloudRuntimeException("Failed to read the snapshot table for KVM upgrade. ", e); } s_logger.debug("Done set KVM snapshot flag. "); } private void updatePrimaryStore(Connection conn) { - PreparedStatement sql = null; - PreparedStatement sql2 = null; - try { - sql = conn.prepareStatement("update storage_pool set storage_provider_name = ? , scope = ? where pool_type = 'Filesystem' or pool_type = 'LVM'"); + try(PreparedStatement sql = conn.prepareStatement("update storage_pool set storage_provider_name = ? , scope = ? where pool_type = 'Filesystem' or pool_type = 'LVM'");) { sql.setString(1, DataStoreProvider.DEFAULT_PRIMARY); sql.setString(2, "HOST"); sql.executeUpdate(); - - sql2 = conn.prepareStatement("update storage_pool set storage_provider_name = ? , scope = ? where pool_type != 'Filesystem' and pool_type != 'LVM'"); - sql2.setString(1, DataStoreProvider.DEFAULT_PRIMARY); - sql2.setString(2, "CLUSTER"); - sql2.executeUpdate(); + try(PreparedStatement sql2 = conn.prepareStatement("update storage_pool set storage_provider_name = ? , scope = ? where pool_type != 'Filesystem' and pool_type != 'LVM'");) { + sql2.setString(1, DataStoreProvider.DEFAULT_PRIMARY); + sql2.setString(2, "CLUSTER"); + sql2.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Failed to upgrade vm template data store uuid: " + e.toString()); + } } catch (SQLException e) { throw new CloudRuntimeException("Failed to upgrade vm template data store uuid: " + e.toString()); - } finally { - if (sql != null) { - try { - sql.close(); - } catch (SQLException e) { - } - } - - if (sql2 != null) { - try { - sql2.close(); - } catch (SQLException e) { - } - } } } @@ -789,7 +646,7 @@ public class Upgrade410to420 implements DbUpgrade { String newGuestLabel = oldParamValue; try { // No need to iterate because the global param setting applies to all physical networks irrespective of traffic type - if (rs.next()) { + if ((rs != null) && (rs.next())) { oldGuestLabel = rs.getString("vmware_network_label"); // guestLabel is in format [[<VSWITCHNAME>],VLANID] separatorIndex = oldGuestLabel.indexOf(","); @@ -799,65 +656,57 @@ public class Upgrade410to420 implements DbUpgrade { } } catch (SQLException e) { s_logger.error(new CloudRuntimeException("Failed to read vmware_network_label : " + e)); - } finally { - try { - if (rs != null) { - rs.close(); - } - } catch (SQLException e) { - } } return newGuestLabel; } private void upgradeVmwareLabels(Connection conn) { - PreparedStatement pstmt = null; - ResultSet rsParams = null; - ResultSet rsLabel = null; String newLabel; String trafficType = null; String trafficTypeVswitchParam; String trafficTypeVswitchParamValue; - try { + try (PreparedStatement pstmt = + conn.prepareStatement("select name,value from `cloud`.`configuration` where category='Hidden' and value is not NULL and name REGEXP 'vmware*.vswitch';");) + { // update the existing vmware traffic labels - pstmt = - conn.prepareStatement("select name,value from `cloud`.`configuration` where category='Hidden' and value is not NULL and name REGEXP 'vmware*.vswitch';"); - rsParams = pstmt.executeQuery(); - while (rsParams.next()) { - trafficTypeVswitchParam = rsParams.getString("name"); - trafficTypeVswitchParamValue = rsParams.getString("value"); - // When upgraded from 4.0 to 4.1 update physical network traffic label with trafficTypeVswitchParam - if (trafficTypeVswitchParam.equals("vmware.private.vswitch")) { - trafficType = "Management"; //TODO(sateesh): Ignore storage traffic, as required physical network already implemented, anything else tobe done? - } else if (trafficTypeVswitchParam.equals("vmware.public.vswitch")) { - trafficType = "Public"; - } else if (trafficTypeVswitchParam.equals("vmware.guest.vswitch")) { - trafficType = "Guest"; + try(ResultSet rsParams = pstmt.executeQuery();) { + while (rsParams.next()) { + trafficTypeVswitchParam = rsParams.getString("name"); + trafficTypeVswitchParamValue = rsParams.getString("value"); + // When upgraded from 4.0 to 4.1 update physical network traffic label with trafficTypeVswitchParam + if (trafficTypeVswitchParam.equals("vmware.private.vswitch")) { + trafficType = "Management"; //TODO(sateesh): Ignore storage traffic, as required physical network already implemented, anything else tobe done? + } else if (trafficTypeVswitchParam.equals("vmware.public.vswitch")) { + trafficType = "Public"; + } else if (trafficTypeVswitchParam.equals("vmware.guest.vswitch")) { + trafficType = "Guest"; + } + try(PreparedStatement sel_pstmt = + conn.prepareStatement("select physical_network_id, traffic_type, vmware_network_label from physical_network_traffic_types where vmware_network_label is not NULL and traffic_type='" + + trafficType + "';");) { + try(ResultSet rsLabel = sel_pstmt.executeQuery();) { + newLabel = getNewLabel(rsLabel, trafficTypeVswitchParamValue); + try(PreparedStatement update_pstmt = + conn.prepareStatement("update physical_network_traffic_types set vmware_network_label = " + newLabel + " where traffic_type = '" + trafficType + + "' and vmware_network_label is not NULL;");) { + s_logger.debug("Updating vmware label for " + trafficType + " traffic. Update SQL statement is " + pstmt); + update_pstmt.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to set vmware traffic labels ", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to set vmware traffic labels ", e); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to set vmware traffic labels ", e); + } } - pstmt = - conn.prepareStatement("select physical_network_id, traffic_type, vmware_network_label from physical_network_traffic_types where vmware_network_label is not NULL and traffic_type='" + - trafficType + "';"); - rsLabel = pstmt.executeQuery(); - newLabel = getNewLabel(rsLabel, trafficTypeVswitchParamValue); - pstmt = - conn.prepareStatement("update physical_network_traffic_types set vmware_network_label = " + newLabel + " where traffic_type = '" + trafficType + - "' and vmware_network_label is not NULL;"); - s_logger.debug("Updating vmware label for " + trafficType + " traffic. Update SQL statement is " + pstmt); - pstmt.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to set vmware traffic labels ", e); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to set vmware traffic labels ", e); - } finally { - try { - if (rsParams != null) { - rsParams.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } } } @@ -865,14 +714,10 @@ public class Upgrade410to420 implements DbUpgrade { List<Long> listOfLegacyZones = new ArrayList<Long>(); List<Long> listOfNonLegacyZones = new ArrayList<Long>(); Map<String, ArrayList<Long>> dcToZoneMap = new HashMap<String, ArrayList<Long>>(); - PreparedStatement pstmt = null; - PreparedStatement clustersQuery = null; - PreparedStatement clusterDetailsQuery = null; - ResultSet rs = null; ResultSet clusters = null; - ResultSet clusterDetails = null; Long zoneId; Long clusterId; + ArrayList<String> dcList = null; String clusterHypervisorType; boolean legacyZone; boolean ignoreZone; @@ -884,121 +729,107 @@ public class Upgrade410to420 implements DbUpgrade { String vc = ""; String dcName = ""; - try { - pstmt = conn.prepareStatement("select id from `cloud`.`data_center` where removed is NULL"); - rs = pstmt.executeQuery(); - - while (rs.next()) { - zoneId = rs.getLong("id"); - clustersQuery = conn.prepareStatement("select id, hypervisor_type from `cloud`.`cluster` where removed is NULL AND data_center_id=?"); - clustersQuery.setLong(1, zoneId); - legacyZone = false; - ignoreZone = true; - ArrayList<String> dcList = new ArrayList<String>(); - count = 0L; - // Legacy zone term is meant only for VMware - // Legacy zone is a zone with atleast 2 clusters & with multiple DCs or VCs - clusters = clustersQuery.executeQuery(); - if (!clusters.next()) { - continue; // Ignore the zone without any clusters - } else { - dcOfPreviousCluster = null; - dcOfCurrentCluster = null; - do { - clusterHypervisorType = clusters.getString("hypervisor_type"); - clusterId = clusters.getLong("id"); - if (clusterHypervisorType.equalsIgnoreCase("VMware")) { - ignoreZone = false; - clusterDetailsQuery = conn.prepareStatement("select value from `cloud`.`cluster_details` where name='url' and cluster_id=?"); - clusterDetailsQuery.setLong(1, clusterId); - clusterDetails = clusterDetailsQuery.executeQuery(); - clusterDetails.next(); - url = clusterDetails.getString("value"); - tokens = url.split("/"); // url format - http://vcenter/dc/cluster - vc = tokens[2]; - dcName = tokens[3]; - dcOfPreviousCluster = dcOfCurrentCluster; - dcOfCurrentCluster = dcName + "@" + vc; - if (!dcList.contains(dcOfCurrentCluster)) { - dcList.add(dcOfCurrentCluster); - } - if (count > 0) { - if (!dcOfPreviousCluster.equalsIgnoreCase(dcOfCurrentCluster)) { - legacyZone = true; - s_logger.debug("Marking the zone " + zoneId + " as legacy zone."); + try(PreparedStatement pstmt = conn.prepareStatement("select id from `cloud`.`data_center` where removed is NULL");) { + try (ResultSet rs = pstmt.executeQuery();) { + while (rs.next()) { + zoneId = rs.getLong("id"); + try(PreparedStatement clustersQuery = conn.prepareStatement("select id, hypervisor_type from `cloud`.`cluster` where removed is NULL AND data_center_id=?");) { + clustersQuery.setLong(1, zoneId); + legacyZone = false; + ignoreZone = true; + dcList = new ArrayList<String>(); + count = 0L; + // Legacy zone term is meant only for VMware + // Legacy zone is a zone with atleast 2 clusters & with multiple DCs or VCs + clusters = clustersQuery.executeQuery(); + }catch (SQLException e) { + throw new CloudRuntimeException("persistLegacyZones:Exception:"+e.getMessage(), e); + } + if (!clusters.next()) { + continue; // Ignore the zone without any clusters + } else { + dcOfPreviousCluster = null; + dcOfCurrentCluster = null; + do { + clusterHypervisorType = clusters.getString("hypervisor_type"); + clusterId = clusters.getLong("id"); + if (clusterHypervisorType.equalsIgnoreCase("VMware")) { + ignoreZone = false; + try (PreparedStatement clusterDetailsQuery = conn.prepareStatement("select value from `cloud`.`cluster_details` where name='url' and cluster_id=?");) { + clusterDetailsQuery.setLong(1, clusterId); + try (ResultSet clusterDetails = clusterDetailsQuery.executeQuery();) { + clusterDetails.next(); + url = clusterDetails.getString("value"); + tokens = url.split("/"); // url format - http://vcenter/dc/cluster + vc = tokens[2]; + dcName = tokens[3]; + dcOfPreviousCluster = dcOfCurrentCluster; + dcOfCurrentCluster = dcName + "@" + vc; + if (!dcList.contains(dcOfCurrentCluster)) { + dcList.add(dcOfCurrentCluster); + } + if (count > 0) { + if (!dcOfPreviousCluster.equalsIgnoreCase(dcOfCurrentCluster)) { + legacyZone = true; + s_logger.debug("Marking the zone " + zoneId + " as legacy zone."); + } + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable add zones to cloud.legacyzones table.", e); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable add zones to cloud.legacyzones table.", e); } + } else { + s_logger.debug("Ignoring zone " + zoneId + " with hypervisor type " + clusterHypervisorType); + break; } - } else { - s_logger.debug("Ignoring zone " + zoneId + " with hypervisor type " + clusterHypervisorType); - break; + count++; + } while (clusters.next()); + if (ignoreZone) { + continue; // Ignore the zone with hypervisors other than VMware } - count++; - } while (clusters.next()); - if (ignoreZone) { - continue; // Ignore the zone with hypervisors other than VMware } - } - if (legacyZone) { - listOfLegacyZones.add(zoneId); - } else { - listOfNonLegacyZones.add(zoneId); - } - for (String dc : dcList) { - ArrayList<Long> dcZones = new ArrayList<Long>(); - if (dcToZoneMap.get(dc) != null) { - dcZones = dcToZoneMap.get(dc); + if (legacyZone) { + listOfLegacyZones.add(zoneId); + } else { + listOfNonLegacyZones.add(zoneId); } - dcZones.add(zoneId); - dcToZoneMap.put(dc, dcZones); - } - } - // If a VMware datacenter in a vCenter maps to more than 1 CloudStack zone, mark all the zones it is mapped to as legacy - for (Map.Entry<String, ArrayList<Long>> entry : dcToZoneMap.entrySet()) { - if (entry.getValue().size() > 1) { - for (Long newLegacyZone : entry.getValue()) { - if (listOfNonLegacyZones.contains(newLegacyZone)) { - listOfNonLegacyZones.remove(newLegacyZone); - listOfLegacyZones.add(newLegacyZone); + for (String dc : dcList) { + ArrayList<Long> dcZones = new ArrayList<Long>(); + if (dcToZoneMap.get(dc) != null) { + dcZones = dcToZoneMap.get(dc); } + dcZones.add(zoneId); + dcToZoneMap.put(dc, dcZones); } } - } - updateLegacyZones(conn, listOfLegacyZones); - updateNonLegacyZones(conn, listOfNonLegacyZones); - } catch (SQLException e) { - String msg = "Unable to discover legacy zones." + e.getMessage(); - s_logger.error(msg); - throw new CloudRuntimeException(msg, e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - if (clusters != null) { - clusters.close(); - } - if (clusterDetails != null) { - clusterDetails.close(); - } - if (clustersQuery != null) { - clustersQuery.close(); - } - if (clusterDetailsQuery != null) { - clusterDetailsQuery.close(); + // If a VMware datacenter in a vCenter maps to more than 1 CloudStack zone, mark all the zones it is mapped to as legacy + for (Map.Entry<String, ArrayList<Long>> entry : dcToZoneMap.entrySet()) { + if (entry.getValue().size() > 1) { + for (Long newLegacyZone : entry.getValue()) { + if (listOfNonLegacyZones.contains(newLegacyZone)) { + listOfNonLegacyZones.remove(newLegacyZone); + listOfLegacyZones.add(newLegacyZone); + } + } + } } + updateLegacyZones(conn, listOfLegacyZones); + updateNonLegacyZones(conn, listOfNonLegacyZones); } catch (SQLException e) { + s_logger.error("Unable to discover legacy zones." + e.getMessage(),e); + throw new CloudRuntimeException("Unable to discover legacy zones." + e.getMessage(), e); } + }catch (SQLException e) { + s_logger.error("Unable to discover legacy zones." + e.getMessage(),e); + throw new CloudRuntimeException("Unable to discover legacy zones." + e.getMessage(), e); } } private void updateLegacyZones(Connection conn, List<Long> zones) { - PreparedStatement legacyZonesQuery = null; //Insert legacy zones into table for legacy zones. - try { - legacyZonesQuery = conn.prepareStatement("INSERT INTO `cloud`.`legacy_zones` (zone_id) VALUES (?)"); + try (PreparedStatement legacyZonesQuery = conn.prepareStatement("INSERT INTO `cloud`.`legacy_zones` (zone_id) VALUES (?)");){ for (Long zoneId : zones) { legacyZonesQuery.setLong(1, zoneId); legacyZonesQuery.executeUpdate(); @@ -1006,13 +837,6 @@ public class Upgrade410to420 implements DbUpgrade { } } catch (SQLException e) { throw new CloudRuntimeException("Unable add zones to cloud.legacyzones table.", e); - } finally { - try { - if (legacyZonesQuery != null) { - legacyZonesQuery.close(); - } - } catch (SQLException e) { - } } } @@ -1109,157 +933,141 @@ public class Upgrade410to420 implements DbUpgrade { } private void createPlaceHolderNics(Connection conn) { - PreparedStatement pstmt = null; - ResultSet rs = null; - - try { - pstmt = - conn.prepareStatement("SELECT network_id, gateway, ip4_address FROM `cloud`.`nics` WHERE reserver_name IN ('DirectNetworkGuru','DirectPodBasedNetworkGuru') and vm_type='DomainRouter' AND removed IS null"); - rs = pstmt.executeQuery(); - while (rs.next()) { - Long networkId = rs.getLong(1); - String gateway = rs.getString(2); - String ip = rs.getString(3); - String uuid = UUID.randomUUID().toString(); - //Insert placeholder nic for each Domain router nic in Shared network - pstmt = - conn.prepareStatement("INSERT INTO `cloud`.`nics` (uuid, ip4_address, gateway, network_id, state, strategy, vm_type, default_nic, created) VALUES (?, ?, ?, ?, 'Reserved', 'PlaceHolder', 'DomainRouter', 0, now())"); - pstmt.setString(1, uuid); - pstmt.setString(2, ip); - pstmt.setString(3, gateway); - pstmt.setLong(4, networkId); - pstmt.executeUpdate(); - s_logger.debug("Created placeholder nic for the ipAddress " + ip + " and network " + networkId); - + try (PreparedStatement pstmt = + conn.prepareStatement("SELECT network_id, gateway, ip4_address FROM `cloud`.`nics` WHERE reserver_name IN ('DirectNetworkGuru','DirectPodBasedNetworkGuru') and vm_type='DomainRouter' AND removed IS null");) + { + try(ResultSet rs = pstmt.executeQuery();) { + while (rs.next()) { + Long networkId = rs.getLong(1); + String gateway = rs.getString(2); + String ip = rs.getString(3); + String uuid = UUID.randomUUID().toString(); + //Insert placeholder nic for each Domain router nic in Shared network + try(PreparedStatement insert_pstmt = + conn.prepareStatement("INSERT INTO `cloud`.`nics` (uuid, ip4_address, gateway, network_id, state, strategy, vm_type, default_nic, created) VALUES (?, ?, ?, ?, 'Reserved', 'PlaceHolder', 'DomainRouter', 0, now())");) { + insert_pstmt.setString(1, uuid); + insert_pstmt.setString(2, ip); + insert_pstmt.setString(3, gateway); + insert_pstmt.setLong(4, networkId); + insert_pstmt.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to create placeholder nics", e); + } + s_logger.debug("Created placeholder nic for the ipAddress " + ip + " and network " + networkId); + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to create placeholder nics", e); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to create placeholder nics", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } } } private void updateRemoteAccessVpn(Connection conn) { - PreparedStatement pstmt = null; - ResultSet rs = null; - - try { - pstmt = conn.prepareStatement("SELECT vpn_server_addr_id FROM `cloud`.`remote_access_vpn`"); - rs = pstmt.executeQuery(); - long id = 1; - while (rs.next()) { - String uuid = UUID.randomUUID().toString(); - Long ipId = rs.getLong(1); - pstmt = conn.prepareStatement("UPDATE `cloud`.`remote_access_vpn` set uuid=?, id=? where vpn_server_addr_id=?"); - pstmt.setString(1, uuid); - pstmt.setLong(2, id); - pstmt.setLong(3, ipId); - pstmt.executeUpdate(); - id++; + try(PreparedStatement pstmt = conn.prepareStatement("SELECT vpn_server_addr_id FROM `cloud`.`remote_access_vpn`");) { + try(ResultSet rs = pstmt.executeQuery();) { + long id = 1; + while (rs.next()) { + String uuid = UUID.randomUUID().toString(); + Long ipId = rs.getLong(1); + try(PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`remote_access_vpn` set uuid=?, id=? where vpn_server_addr_id=?");) { + update_pstmt.setString(1, uuid); + update_pstmt.setLong(2, id); + update_pstmt.setLong(3, ipId); + update_pstmt.executeUpdate(); + id++; + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to update id/uuid of remote_access_vpn table", e); + } + } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to update id/uuid of remote_access_vpn table", e); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to update id/uuid of remote_access_vpn table", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } } } private void addEgressFwRulesForSRXGuestNw(Connection conn) { - PreparedStatement pstmt = null; ResultSet rs = null; - ResultSet rsId = null; - ResultSet rsNw = null; - try { - pstmt = conn.prepareStatement("select network_id FROM `cloud`.`ntwk_service_map` where service='Firewall' and provider='JuniperSRX' "); + try(PreparedStatement pstmt = conn.prepareStatement("select network_id FROM `cloud`.`ntwk_service_map` where service='Firewall' and provider='JuniperSRX' ");) { rs = pstmt.executeQuery(); while (rs.next()) { long netId = rs.getLong(1); //checking for Isolated OR Virtual - pstmt = - conn.prepareStatement("select account_id, domain_id FROM `cloud`.`networks` where (guest_type='Isolated' OR guest_type='Virtual') and traffic_type='Guest' and vpc_id is NULL and (state='implemented' OR state='Shutdown') and id=? "); - pstmt.setLong(1, netId); - s_logger.debug("Getting account_id, domain_id from networks table: " + pstmt); - rsNw = pstmt.executeQuery(); - - if (rsNw.next()) { - long accountId = rsNw.getLong(1); - long domainId = rsNw.getLong(2); - - //Add new rule for the existing networks - s_logger.debug("Adding default egress firewall rule for network " + netId); - pstmt = - conn.prepareStatement("INSERT INTO firewall_rules (uuid, state, protocol, purpose, account_id, domain_id, network_id, xid, created, traffic_type) VALUES (?, 'Active', 'all', 'Firewall', ?, ?, ?, ?, now(), 'Egress')"); - pstmt.setString(1, UUID.randomUUID().toString()); - pstmt.setLong(2, accountId); - pstmt.setLong(3, domainId); - pstmt.setLong(4, netId); - pstmt.setString(5, UUID.randomUUID().toString()); - s_logger.debug("Inserting default egress firewall rule " + pstmt); - pstmt.executeUpdate(); - - pstmt = conn.prepareStatement("select id from firewall_rules where protocol='all' and network_id=?"); - pstmt.setLong(1, netId); - rsId = pstmt.executeQuery(); - - long firewallRuleId; - if (rsId.next()) { - firewallRuleId = rsId.getLong(1); - pstmt = conn.prepareStatement("insert into firewall_rules_cidrs (firewall_rule_id,source_cidr) values (?, '0.0.0.0/0')"); - pstmt.setLong(1, firewallRuleId); - s_logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + pstmt); - pstmt.executeUpdate(); + try(PreparedStatement sel_net_pstmt = + conn.prepareStatement("select account_id, domain_id FROM `cloud`.`networks` where (guest_type='Isolated' OR guest_type='Virtual') and traffic_type='Guest' and vpc_id is NULL and (state='implemented' OR state='Shutdown') and id=? ");) { + sel_net_pstmt.setLong(1, netId); + s_logger.debug("Getting account_id, domain_id from networks table: "); + try(ResultSet rsNw = pstmt.executeQuery();) + { + if (rsNw.next()) { + long accountId = rsNw.getLong(1); + long domainId = rsNw.getLong(2); + + //Add new rule for the existing networks + s_logger.debug("Adding default egress firewall rule for network " + netId); + try (PreparedStatement insert_pstmt = + conn.prepareStatement("INSERT INTO firewall_rules (uuid, state, protocol, purpose, account_id, domain_id, network_id, xid, created, traffic_type) VALUES (?, 'Active', 'all', 'Firewall', ?, ?, ?, ?, now(), 'Egress')");) { + insert_pstmt.setString(1, UUID.randomUUID().toString()); + insert_pstmt.setLong(2, accountId); + insert_pstmt.setLong(3, domainId); + insert_pstmt.setLong(4, netId); + insert_pstmt.setString(5, UUID.randomUUID().toString()); + s_logger.debug("Inserting default egress firewall rule " + insert_pstmt); + insert_pstmt.executeUpdate(); + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to set egress firewall rules ", e); + } + try (PreparedStatement sel_firewall_pstmt = conn.prepareStatement("select id from firewall_rules where protocol='all' and network_id=?");) { + sel_firewall_pstmt.setLong(1, netId); + try (ResultSet rsId = sel_firewall_pstmt.executeQuery();) { + long firewallRuleId; + if (rsId.next()) { + firewallRuleId = rsId.getLong(1); + try (PreparedStatement insert_pstmt = conn.prepareStatement("insert into firewall_rules_cidrs (firewall_rule_id,source_cidr) values (?, '0.0.0.0/0')");) { + insert_pstmt.setLong(1, firewallRuleId); + s_logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + insert_pstmt); + insert_pstmt.executeUpdate(); + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to set egress firewall rules ", e); + } + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to set egress firewall rules ", e); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to set egress firewall rules ", e); + } + } } } } } catch (SQLException e) { throw new CloudRuntimeException("Unable to set egress firewall rules ", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } } } private void upgradeEIPNetworkOfferings(Connection conn) { - - PreparedStatement pstmt = null; - ResultSet rs = null; - - try { - pstmt = conn.prepareStatement("select id, elastic_ip_service from `cloud`.`network_offerings` where traffic_type='Guest'"); - rs = pstmt.executeQuery(); - while (rs.next()) { - long id = rs.getLong(1); - // check if elastic IP service is enabled for network offering - if (rs.getLong(2) != 0) { - //update network offering with eip_associate_public_ip set to true - pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings` set eip_associate_public_ip=? where id=?"); - pstmt.setBoolean(1, true); - pstmt.setLong(2, id); - pstmt.executeUpdate(); + try (PreparedStatement pstmt = conn.prepareStatement("select id, elastic_ip_service from `cloud`.`network_offerings` where traffic_type='Guest'");) + { + try(ResultSet rs = pstmt.executeQuery();) { + while (rs.next()) { + long id = rs.getLong(1); + // check if elastic IP service is enabled for network offering + if (rs.getLong(2) != 0) { + //update network offering with eip_associate_public_ip set to true + try(PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings` set eip_associate_public_ip=? where id=?");) { + update_pstmt.setBoolean(1, true); + update_pstmt.setLong(2, id); + update_pstmt.executeUpdate(); + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to set elastic_ip_service for network offerings with EIP service enabled.", e); + } + } } + }catch (SQLException e) { + throw new CloudRuntimeException("Unable to set elastic_ip_service for network offerings with EIP service enabled.", e); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to set elastic_ip_service for network offerings with EIP service enabled.", e); @@ -1399,106 +1207,29 @@ public class Upgrade410to420 implements DbUpgrade { } if (!hasAcls) { //no network ACls for this network. - // Assign default Deny ACL - aclId = NetworkACL.DEFAULT_DENY; - } - //Assign acl to network - pstmt = conn.prepareStatement("UPDATE `cloud`.`networks` set network_acl_id=? where id=?"); - pstmt.setLong(1, aclId); - pstmt.setLong(2, networkId); - pstmt.executeUpdate(); - } - s_logger.debug("Done updating network ACLs "); - } catch (SQLException e) { - throw new CloudRuntimeException("Unable to move network acls from firewall rules table to network_acl_item table", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (rsAcls != null) { - rsAcls.close(); - } - if (rsCidr != null) { - rsCidr.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } - } - } - - private void updateGlobalDeploymentPlanner(Connection conn) { - PreparedStatement pstmt = null; - ResultSet rs = null; - - try { - pstmt = conn.prepareStatement("select value from `cloud`.`configuration` where name = 'vm.allocation.algorithm'"); - rs = pstmt.executeQuery(); - while (rs.next()) { - String globalValue = rs.getString(1); - String plannerName = "FirstFitPlanner"; - - if (globalValue != null) { - if (globalValue.equals(DeploymentPlanner.AllocationAlgorithm.random.toString())) { - plannerName = "FirstFitPlanner"; - } else if (globalValue.equals(DeploymentPlanner.AllocationAlgorithm.firstfit.toString())) { - plannerName = "FirstFitPlanner"; - } else if (globalValue.equals(DeploymentPlanner.AllocationAlgorithm.userconcentratedpod_firstfit.toString())) { - plannerName = "UserConcentratedPodPlanner"; - } else if (globalValue.equals(DeploymentPlanner.AllocationAlgorithm.userconcentratedpod_random.toString())) { - plannerName = "UserConcentratedPodPlanner"; - } else if (globalValue.equals(DeploymentPlanner.AllocationAlgorithm.userdispersing.toString())) { - plannerName = "UserDispersingPlanner"; - } - } - // update vm.deployment.planner global config - pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` set value=? where name = 'vm.deployment.planner'"); - pstmt.setString(1, plannerName); - pstmt.executeUpdate(); - } - } catch (SQLException e) { - throw new CloudRuntimeException("Unable to set vm.deployment.planner global config", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } - } - } - - private void upgradeDefaultVpcOffering(Connection conn) { - PreparedStatement pstmt = null; - ResultSet rs = null; - - try { - pstmt = - conn.prepareStatement("select distinct map.vpc_offering_id from `cloud`.`vpc_offering_service_map` map, `cloud`.`vpc_offerings` off where off.id=map.vpc_offering_id AND service='Lb'"); - rs = pstmt.executeQuery(); - while (rs.next()) { - long id = rs.getLong(1); - //Add internal LB vm as a supported provider for the load balancer service - pstmt = conn.prepareStatement("INSERT INTO `cloud`.`vpc_offering_service_map` (vpc_offering_id, service, provider) VALUES (?,?,?)"); - pstmt.setLong(1, id); - pstmt.setString(2, "Lb"); - pstmt.setString(3, "InternalLbVm"); + // Assign default Deny ACL + aclId = NetworkACL.DEFAULT_DENY; + } + //Assign acl to network + pstmt = conn.prepareStatement("UPDATE `cloud`.`networks` set network_acl_id=? where id=?"); + pstmt.setLong(1, aclId); + pstmt.setLong(2, networkId); pstmt.executeUpdate(); } - + s_logger.debug("Done updating network ACLs "); } catch (SQLException e) { - throw new CloudRuntimeException("Unable update the default VPC offering with the internal lb service", e); + throw new CloudRuntimeException("Unable to move network acls from firewall rules table to network_acl_item table", e); } finally { try { if (rs != null) { rs.close(); } + if (rsAcls != null) { + rsAcls.close(); + } + if (rsCidr != null) { + rsCidr.close(); + } if (pstmt != null) { pstmt.close(); } @@ -1507,106 +1238,156 @@ public class Upgrade410to420 implements DbUpgrade { } } - private void upgradePhysicalNtwksWithInternalLbProvider(Connection conn) { - - PreparedStatement pstmt = null; - ResultSet rs = null; - - try { - pstmt = conn.prepareStatement("SELECT id FROM `cloud`.`physical_network` where removed is null"); - rs = pstmt.executeQuery(); - while (rs.next()) { - long pNtwkId = rs.getLong(1); - String uuid = UUID.randomUUID().toString(); - //Add internal LB VM to the list of physical network service providers - pstmt = - conn.prepareStatement("INSERT INTO `cloud`.`physical_network_service_providers` " - + "(uuid, physical_network_id, provider_name, state, load_balance_service_provided, destination_physical_network_id)" - + " VALUES (?, ?, 'InternalLbVm', 'Enabled', 1, 0)"); - pstmt.setString(1, uuid); - pstmt.setLong(2, pNtwkId); -
<TRUNCATED>
