handle a bunch of warnings

This commit is contained in:
Daan Hoogland 2025-11-14 15:17:15 +01:00
parent e90e436ef8
commit 16e24dbecb
3 changed files with 107 additions and 404 deletions

View File

@ -24,12 +24,7 @@ import java.sql.Date;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
@ -37,6 +32,7 @@ import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParserFactory;
import com.cloud.utils.StringUtils;
import org.apache.cloudstack.utils.security.DigestHelper; import org.apache.cloudstack.utils.security.DigestHelper;
import org.apache.cloudstack.utils.security.ParserUtils; import org.apache.cloudstack.utils.security.ParserUtils;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -73,25 +69,20 @@ public class DatabaseConfig {
private String _currentFieldName = null; private String _currentFieldName = null;
private Map<String, String> _currentObjectParams = null; private Map<String, String> _currentObjectParams = null;
private static Map<String, String> s_configurationDescriptions = new HashMap<String, String>(); private static final Map<String, String> s_configurationDescriptions = new HashMap<>();
private static Map<String, String> s_configurationComponents = new HashMap<String, String>(); private static final Map<String, String> s_configurationComponents = new HashMap<>();
private static Map<String, String> s_defaultConfigurationValues = new HashMap<String, String>(); private static final Map<String, String> s_defaultConfigurationValues = new HashMap<>();
// Change to HashSet // Change to HashSet
private static HashSet<String> objectNames = new HashSet<String>(); private static final HashSet<String> objectNames = new HashSet<>();
private static HashSet<String> fieldNames = new HashSet<String>(); private static final HashSet<String> fieldNames = new HashSet<>();
// Maintain an IPRangeConfig object to handle IP related logic // Maintain an IPRangeConfig object to handle IP related logic
private final IPRangeConfig iprc = ComponentContext.inject(IPRangeConfig.class); private final IPRangeConfig ipRangeConfig = ComponentContext.inject(IPRangeConfig.class);
// Maintain a PodZoneConfig object to handle Pod/Zone related logic // Maintain a PodZoneConfig object to handle Pod/Zone related logic
private final PodZoneConfig pzc = ComponentContext.inject(PodZoneConfig.class); private final PodZoneConfig pzc = ComponentContext.inject(PodZoneConfig.class);
// Global variables to store network.throttling.rate and multicast.throttling.rate from the configuration table
// Will be changed from null to a non-null value if the value existed in the configuration table
private String _networkThrottlingRate = null;
private String _multicastThrottlingRate = null;
static { static {
// initialize the objectNames ArrayList // initialize the objectNames ArrayList
objectNames.add("zone"); objectNames.add("zone");
@ -356,6 +347,9 @@ public class DatabaseConfig {
s_defaultConfigurationValues.put("publish.async.job.events", "true"); s_defaultConfigurationValues.put("publish.async.job.events", "true");
} }
/**
* to make sure it is never used
*/
protected DatabaseConfig() { protected DatabaseConfig() {
} }
@ -368,10 +362,10 @@ public class DatabaseConfig {
File file = PropertiesUtil.findConfigFile("log4j-cloud.xml"); File file = PropertiesUtil.findConfigFile("log4j-cloud.xml");
if (file != null) { if (file != null) {
System.out.println("Log4j configuration from : " + file.getAbsolutePath()); LOGGER.info("Log4j configuration from : {}", file.getAbsolutePath());
Configurator.initialize(null, file.getAbsolutePath()); Configurator.initialize(null, file.getAbsolutePath());
} else { } else {
System.out.println("Configure log4j with default properties"); LOGGER.info("Configure log4j with default properties");
} }
if (args.length < 1) { if (args.length < 1) {
@ -383,8 +377,6 @@ public class DatabaseConfig {
config.doConfig(); config.doConfig();
System.exit(0); System.exit(0);
} catch (Exception ex) { } catch (Exception ex) {
System.out.print("Error Caught");
ex.printStackTrace();
LOGGER.error("error", ex); LOGGER.error("error", ex);
} }
} }
@ -412,15 +404,11 @@ public class DatabaseConfig {
String version = firstNode.getTextContent(); String version = firstNode.getTextContent();
if (!version.equals("2.0")) { if (!version.equals("2.0")) {
System.out.println(warningMsg); LOGGER.warn(warningMsg);
} }
} catch (ParserConfigurationException parserException) { } catch (ParserConfigurationException | IOException | SAXException exception) {
parserException.printStackTrace(); LOGGER.error("exception during version check.",exception);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (SAXException saxException) {
saxException.printStackTrace();
} }
} }
@ -443,7 +431,7 @@ public class DatabaseConfig {
// Save default values for configuration fields // Save default values for configuration fields
saveVMTemplate(); saveVMTemplate();
saveRootDomain(); saveRootDomain();
saveDefaultConfiguations(); saveDefaultConfigurations();
} }
}); });
@ -522,10 +510,7 @@ public class DatabaseConfig {
stmt.setLong(13, 0); stmt.setLong(13, 0);
stmt.setLong(14, 1238425896); stmt.setLong(14, 1238425896);
boolean nfs = false; boolean nfs = url.startsWith("nfs") || url.startsWith("cifs");
if (url.startsWith("nfs") || url.startsWith("cifs")) {
nfs = true;
}
if (nfs) { if (nfs) {
stmt.setString(15, "com.cloud.storage.resource.NfsSecondaryStorageResource"); stmt.setString(15, "com.cloud.storage.resource.NfsSecondaryStorageResource");
} else { } else {
@ -568,7 +553,6 @@ public class DatabaseConfig {
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
System.out.println("Error creating secondary storage: " + ex.getMessage()); System.out.println("Error creating secondary storage: " + ex.getMessage());
return;
} }
} }
@ -597,7 +581,6 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
System.out.println("Error creating cluster: " + ex.getMessage()); System.out.println("Error creating cluster: " + ex.getMessage());
LOGGER.error("error creating cluster", ex); LOGGER.error("error creating cluster", ex);
return;
} }
} }
@ -612,7 +595,7 @@ public class DatabaseConfig {
String hostAddress = _currentObjectParams.get("hostAddress"); String hostAddress = _currentObjectParams.get("hostAddress");
String hostPath = _currentObjectParams.get("hostPath"); String hostPath = _currentObjectParams.get("hostPath");
String storageType = _currentObjectParams.get("storageType"); String storageType = _currentObjectParams.get("storageType");
String uuid = UUID.nameUUIDFromBytes(new String(hostAddress + hostPath).getBytes()).toString(); String uuid = UUID.nameUUIDFromBytes((hostAddress + hostPath).getBytes()).toString();
String insertSql1 = String insertSql1 =
"INSERT INTO `storage_pool` (`id`, `name`, `uuid` , `pool_type` , `port`, `data_center_id` ,`available_bytes` , `capacity_bytes` ,`host_address`, `path`, `created`, `pod_id`,`status` , `cluster_id`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; "INSERT INTO `storage_pool` (`id`, `name`, `uuid` , `pool_type` , `port`, `data_center_id` ,`available_bytes` , `capacity_bytes` ,`host_address`, `path`, `created`, `pod_id`,`status` , `cluster_id`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
@ -624,11 +607,7 @@ public class DatabaseConfig {
stmt.setLong(1, id); stmt.setLong(1, id);
stmt.setString(2, name); stmt.setString(2, name);
stmt.setString(3, uuid); stmt.setString(3, uuid);
if (storageType == null) { stmt.setString(4, Objects.requireNonNullElse(storageType, "NetworkFileSystem"));
stmt.setString(4, "NetworkFileSystem");
} else {
stmt.setString(4, storageType);
}
stmt.setLong(5, 111); stmt.setLong(5, 111);
stmt.setLong(6, dataCenterId); stmt.setLong(6, dataCenterId);
stmt.setLong(7, 0); stmt.setLong(7, 0);
@ -644,7 +623,6 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
System.out.println("Error creating storage pool: " + ex.getMessage()); System.out.println("Error creating storage pool: " + ex.getMessage());
LOGGER.error("error creating storage pool ", ex); LOGGER.error("error creating storage pool ", ex);
return;
} }
} }
@ -748,7 +726,6 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
System.out.println("Error creating physical network service provider: " + ex.getMessage()); System.out.println("Error creating physical network service provider: " + ex.getMessage());
LOGGER.error("error creating physical network service provider", ex); LOGGER.error("error creating physical network service provider", ex);
return;
} }
} }
@ -773,7 +750,6 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
System.out.println("Error creating virtual router provider: " + ex.getMessage()); System.out.println("Error creating virtual router provider: " + ex.getMessage());
LOGGER.error("error creating virtual router provider ", ex); LOGGER.error("error creating virtual router provider ", ex);
return;
} }
} }
@ -797,12 +773,12 @@ public class DatabaseConfig {
} }
// Check that the given IP address range was valid // Check that the given IP address range was valid
if (!checkIpAddressRange(publicIpRange)) { if (checkInvalidIpAddressRange(publicIpRange)) {
printError("Please enter a valid public IP range."); printError("Please enter a valid public IP range.");
} }
// Split the IP address range // Split the IP address range
String[] ipAddressRangeArray = publicIpRange.split("\\-"); String[] ipAddressRangeArray = publicIpRange.split("-");
String startIP = ipAddressRangeArray[0]; String startIP = ipAddressRangeArray[0];
String endIP = null; String endIP = null;
if (ipAddressRangeArray.length > 1) { if (ipAddressRangeArray.length > 1) {
@ -810,14 +786,14 @@ public class DatabaseConfig {
} }
// If a netmask was provided, check that the startIP, endIP, and gateway all belong to the same subnet // If a netmask was provided, check that the startIP, endIP, and gateway all belong to the same subnet
if (netmask != null && !netmask.equals("")) { if (StringUtils.isNotEmpty(netmask)) {
if (endIP != null) { if (endIP != null) {
if (!IPRangeConfig.sameSubnet(startIP, endIP, netmask)) { if (!IPRangeConfig.sameSubnet(startIP, endIP, netmask)) {
printError("Start and end IPs for the public IP range must be in the same subnet, as per the provided netmask."); printError("Start and end IPs for the public IP range must be in the same subnet, as per the provided netmask.");
} }
} }
if (gateway != null && !gateway.equals("")) { if (StringUtils.isNotEmpty(gateway)) {
if (!IPRangeConfig.sameSubnet(startIP, gateway, netmask)) { if (!IPRangeConfig.sameSubnet(startIP, gateway, netmask)) {
printError("The start IP for the public IP range must be in the same subnet as the gateway, as per the provided netmask."); printError("The start IP for the public IP range must be in the same subnet as the gateway, as per the provided netmask.");
} }
@ -838,7 +814,7 @@ public class DatabaseConfig {
pzc.modifyVlan(zoneName, true, vlanId, gateway, netmask, vlanPodName, vlanType, publicIpRange, 0, physicalNetworkId); pzc.modifyVlan(zoneName, true, vlanId, gateway, netmask, vlanPodName, vlanType, publicIpRange, 0, physicalNetworkId);
long vlanDbId = pzc.getVlanDbId(zoneName, vlanId); long vlanDbId = pzc.getVlanDbId(zoneName, vlanId);
iprc.saveIPRange("public", -1, zoneDbId, vlanDbId, startIP, endIP, null, physicalNetworkId); ipRangeConfig.saveIPRange("public", -1, zoneDbId, vlanDbId, startIP, endIP, null, physicalNetworkId);
} }
@ -863,7 +839,7 @@ public class DatabaseConfig {
} }
// Get the individual cidrAddress and cidrSize values // Get the individual cidrAddress and cidrSize values
String[] cidrPair = cidr.split("\\/"); String[] cidrPair = cidr.split("/");
String cidrAddress = cidrPair[0]; String cidrAddress = cidrPair[0];
String cidrSize = cidrPair[1]; String cidrSize = cidrPair[1];
long cidrSizeNum = Long.parseLong(cidrSize); long cidrSizeNum = Long.parseLong(cidrSize);
@ -877,13 +853,12 @@ public class DatabaseConfig {
if (privateIpRange != null) { if (privateIpRange != null) {
// Check that the given IP address range was valid // Check that the given IP address range was valid
if (!checkIpAddressRange(privateIpRange)) { if (checkInvalidIpAddressRange(privateIpRange)) {
printError("Please enter a valid private IP range."); printError("Please enter a valid private IP range.");
} }
String[] ipAddressRangeArray = privateIpRange.split("\\-"); String[] ipAddressRangeArray = privateIpRange.split("-");
startIP = ipAddressRangeArray[0]; startIP = ipAddressRangeArray[0];
endIP = null;
if (ipAddressRangeArray.length > 1) { if (ipAddressRangeArray.length > 1) {
endIP = ipAddressRangeArray[1]; endIP = ipAddressRangeArray[1];
} }
@ -904,54 +879,39 @@ public class DatabaseConfig {
if (privateIpRange != null) { if (privateIpRange != null) {
// Save the IP address range // Save the IP address range
iprc.saveIPRange("private", id, dataCenterId, -1, startIP, endIP, null, -1); ipRangeConfig.saveIPRange("private", id, dataCenterId, -1, startIP, endIP, null, -1);
} }
} }
@DB @DB
protected void saveServiceOffering() { protected void saveServiceOffering() {
long id = Long.parseLong(_currentObjectParams.get("id"));
String name = _currentObjectParams.get("name"); String name = _currentObjectParams.get("name");
String displayText = _currentObjectParams.get("displayText"); String displayText = _currentObjectParams.get("displayText");
ProvisioningType provisioningType = ProvisioningType.valueOf(_currentObjectParams.get("provisioningType")); ProvisioningType provisioningType = ProvisioningType.valueOf(_currentObjectParams.get("provisioningType"));
int cpu = Integer.parseInt(_currentObjectParams.get("cpu")); int cpu = Integer.parseInt(_currentObjectParams.get("cpu"));
int ramSize = Integer.parseInt(_currentObjectParams.get("ramSize")); int ramSize = Integer.parseInt(_currentObjectParams.get("ramSize"));
int speed = Integer.parseInt(_currentObjectParams.get("speed")); int speed = Integer.parseInt(_currentObjectParams.get("speed"));
String useLocalStorageValue = _currentObjectParams.get("useLocalStorage");
// int nwRate = Integer.parseInt(_currentObjectParams.get("nwRate"));
// int mcRate = Integer.parseInt(_currentObjectParams.get("mcRate"));
boolean ha = Boolean.parseBoolean(_currentObjectParams.get("enableHA")); boolean ha = Boolean.parseBoolean(_currentObjectParams.get("enableHA"));
boolean mirroring = Boolean.parseBoolean(_currentObjectParams.get("mirrored"));
boolean useLocalStorage;
if (useLocalStorageValue != null) {
if (Boolean.parseBoolean(useLocalStorageValue)) {
useLocalStorage = true;
} else {
useLocalStorage = false;
}
} else {
useLocalStorage = false;
}
DiskOfferingVO diskOfferingVO = new DiskOfferingVO(name, displayText, provisioningType, false, null, false, false, true); DiskOfferingVO diskOfferingVO = new DiskOfferingVO(name, displayText, provisioningType, false, null, false, false, true);
ServiceOfferingVO serviceOffering = ServiceOfferingVO serviceOffering =
new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, ha, displayText, new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, ha, displayText,
false, null, false); false, null, false);
Long bytesReadRate = Long.parseLong(_currentObjectParams.get("bytesReadRate")); long bytesReadRate = Long.parseLong(_currentObjectParams.get("bytesReadRate"));
if ((bytesReadRate != null) && (bytesReadRate > 0)) if (bytesReadRate > 0)
diskOfferingVO.setBytesReadRate(bytesReadRate); diskOfferingVO.setBytesReadRate(bytesReadRate);
Long bytesWriteRate = Long.parseLong(_currentObjectParams.get("bytesWriteRate")); long bytesWriteRate = Long.parseLong(_currentObjectParams.get("bytesWriteRate"));
if ((bytesWriteRate != null) && (bytesWriteRate > 0)) if (bytesWriteRate > 0)
diskOfferingVO.setBytesWriteRate(bytesWriteRate); diskOfferingVO.setBytesWriteRate(bytesWriteRate);
Long iopsReadRate = Long.parseLong(_currentObjectParams.get("iopsReadRate")); long iopsReadRate = Long.parseLong(_currentObjectParams.get("iopsReadRate"));
if ((iopsReadRate != null) && (iopsReadRate > 0)) if (iopsReadRate > 0)
diskOfferingVO.setIopsReadRate(iopsReadRate); diskOfferingVO.setIopsReadRate(iopsReadRate);
Long iopsWriteRate = Long.parseLong(_currentObjectParams.get("iopsWriteRate")); long iopsWriteRate = Long.parseLong(_currentObjectParams.get("iopsWriteRate"));
if ((iopsWriteRate != null) && (iopsWriteRate > 0)) if (iopsWriteRate > 0)
diskOfferingVO.setIopsWriteRate(iopsWriteRate); diskOfferingVO.setIopsWriteRate(iopsWriteRate);
DiskOfferingDaoImpl DiskOfferinDao = ComponentContext.inject(DiskOfferingDaoImpl.class); DiskOfferingDaoImpl DiskOfferinDao = ComponentContext.inject(DiskOfferingDaoImpl.class);
@ -968,30 +928,15 @@ public class DatabaseConfig {
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("error creating service offering", e); LOGGER.error("error creating service offering", e);
} }
/*
String insertSql = "INSERT INTO `cloud`.`service_offering` (id, name, cpu, ram_size, speed, nw_rate, mc_rate, created, ha_enabled, mirrored, display_text, guest_ip_type, use_local_storage) " +
"VALUES (" + id + ",'" + name + "'," + cpu + "," + ramSize + "," + speed + "," + nwRate + "," + mcRate + ",now()," + ha + "," + mirroring + ",'" + displayText + "','" + guestIpType + "','" + useLocalStorage + "')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
LOGGER.error("error creating service offering", ex);
return;
}
*/
} }
@DB @DB
protected void saveDiskOffering() { protected void saveDiskOffering() {
long id = Long.parseLong(_currentObjectParams.get("id"));
String name = _currentObjectParams.get("name"); String name = _currentObjectParams.get("name");
String displayText = _currentObjectParams.get("displayText"); String displayText = _currentObjectParams.get("displayText");
ProvisioningType provisioningType = ProvisioningType.valueOf(_currentObjectParams.get("provisioningtype")); ProvisioningType provisioningType = ProvisioningType.valueOf(_currentObjectParams.get("provisioningtype"));
long diskSpace = Long.parseLong(_currentObjectParams.get("diskSpace")); long diskSpace = Long.parseLong(_currentObjectParams.get("diskSpace"));
diskSpace = diskSpace * 1024 * 1024; diskSpace = diskSpace * 1024 * 1024;
// boolean mirroring = Boolean.parseBoolean(_currentObjectParams.get("mirrored"));
String tags = _currentObjectParams.get("tags"); String tags = _currentObjectParams.get("tags");
String useLocal = _currentObjectParams.get("useLocal"); String useLocal = _currentObjectParams.get("useLocal");
boolean local = false; boolean local = false;
@ -999,7 +944,7 @@ public class DatabaseConfig {
local = Boolean.parseBoolean(useLocal); local = Boolean.parseBoolean(useLocal);
} }
if (tags != null && tags.length() > 0) { if (StringUtils.isNotEmpty(tags)) {
String[] tokens = tags.split(","); String[] tokens = tags.split(",");
StringBuilder newTags = new StringBuilder(); StringBuilder newTags = new StringBuilder();
for (String token : tokens) { for (String token : tokens) {
@ -1011,17 +956,17 @@ public class DatabaseConfig {
DiskOfferingVO diskOffering = new DiskOfferingVO(name, displayText, provisioningType, diskSpace, tags, false, null, null, null); DiskOfferingVO diskOffering = new DiskOfferingVO(name, displayText, provisioningType, diskSpace, tags, false, null, null, null);
diskOffering.setUseLocalStorage(local); diskOffering.setUseLocalStorage(local);
Long bytesReadRate = Long.parseLong(_currentObjectParams.get("bytesReadRate")); long bytesReadRate = Long.parseLong(_currentObjectParams.get("bytesReadRate"));
if (bytesReadRate != null && (bytesReadRate > 0)) if (bytesReadRate > 0)
diskOffering.setBytesReadRate(bytesReadRate); diskOffering.setBytesReadRate(bytesReadRate);
Long bytesWriteRate = Long.parseLong(_currentObjectParams.get("bytesWriteRate")); long bytesWriteRate = Long.parseLong(_currentObjectParams.get("bytesWriteRate"));
if (bytesWriteRate != null && (bytesWriteRate > 0)) if (bytesWriteRate > 0)
diskOffering.setBytesWriteRate(bytesWriteRate); diskOffering.setBytesWriteRate(bytesWriteRate);
Long iopsReadRate = Long.parseLong(_currentObjectParams.get("iopsReadRate")); long iopsReadRate = Long.parseLong(_currentObjectParams.get("iopsReadRate"));
if (iopsReadRate != null && (iopsReadRate > 0)) if (iopsReadRate > 0)
diskOffering.setIopsReadRate(iopsReadRate); diskOffering.setIopsReadRate(iopsReadRate);
Long iopsWriteRate = Long.parseLong(_currentObjectParams.get("iopsWriteRate")); long iopsWriteRate = Long.parseLong(_currentObjectParams.get("iopsWriteRate"));
if (iopsWriteRate != null && (iopsWriteRate > 0)) if (iopsWriteRate > 0)
diskOffering.setIopsWriteRate(iopsWriteRate); diskOffering.setIopsWriteRate(iopsWriteRate);
DiskOfferingDaoImpl offering = ComponentContext.inject(DiskOfferingDaoImpl.class); DiskOfferingDaoImpl offering = ComponentContext.inject(DiskOfferingDaoImpl.class);
@ -1031,107 +976,10 @@ public class DatabaseConfig {
LOGGER.error("error creating disk offering", e); LOGGER.error("error creating disk offering", e);
} }
/*
String insertSql = "INSERT INTO `cloud`.`disk_offering` (id, domain_id, name, display_text, disk_size, mirrored, tags) " +
"VALUES (" + id + "," + domainId + ",'" + name + "','" + displayText + "'," + diskSpace + "," + mirroring + ", ? )";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.setString(1, tags);
stmt.executeUpdate();
} catch (SQLException ex) {
LOGGER.error("error creating disk offering", ex);
return;
}
*/
}
@DB
protected void saveThrottlingRates() {
boolean saveNetworkThrottlingRate = (_networkThrottlingRate != null);
boolean saveMulticastThrottlingRate = (_multicastThrottlingRate != null);
if (!saveNetworkThrottlingRate && !saveMulticastThrottlingRate) {
return;
}
String insertNWRateSql = "UPDATE `cloud`.`service_offering` SET `nw_rate` = ?";
String insertMCRateSql = "UPDATE `cloud`.`service_offering` SET `mc_rate` = ?";
TransactionLegacy txn = TransactionLegacy.currentTxn();
try {
PreparedStatement stmt;
if (saveNetworkThrottlingRate) {
stmt = txn.prepareAutoCloseStatement(insertNWRateSql);
stmt.setString(1, _networkThrottlingRate);
stmt.executeUpdate();
}
if (saveMulticastThrottlingRate) {
stmt = txn.prepareAutoCloseStatement(insertMCRateSql);
stmt.setString(1, _multicastThrottlingRate);
stmt.executeUpdate();
}
} catch (SQLException ex) {
LOGGER.error("error saving network and multicast throttling rates to all service offerings", ex);
return;
}
} }
// no configurable values for VM Template, hard-code the defaults for now // no configurable values for VM Template, hard-code the defaults for now
private void saveVMTemplate() { private void saveVMTemplate() {
/*
long id = 1;
String uniqueName = "routing";
String name = "DomR Template";
int isPublic = 0;
String path = "template/private/u000000/os/routing";
String type = "ext3";
int requiresHvm = 0;
int bits = 64;
long createdByUserId = 1;
int isReady = 1;
String insertSql = "INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, path, created, type, hvm, bits, created_by, ready) " +
"VALUES (" + id + ",'" + uniqueName + "','" + name + "'," + isPublic + ",'" + path + "',now(),'" + type + "'," +
requiresHvm + "," + bits + "," + createdByUserId + "," + isReady + ")";
Transaction txn = Transaction.open();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
LOGGER.error("error creating vm template: " + ex);
} finally {
txn.close();
}
*/
/*
// do it again for console proxy template
id = 2;
uniqueName = "consoleproxy";
name = "Console Proxy Template";
isPublic = 0;
path = "template/private/u000000/os/consoleproxy";
type = "ext3";
insertSql = "INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, path, created, type, hvm, bits, created_by, ready) " +
"VALUES (" + id + ",'" + uniqueName + "','" + name + "'," + isPublic + ",'" + path + "',now(),'" + type + "'," +
requiresHvm + "," + bits + "," + createdByUserId + "," + isReady + ")";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
LOGGER.error("error creating vm template: " + ex);
} finally {
txn.close();
}
*/
} }
@DB @DB
@ -1166,7 +1014,7 @@ public class DatabaseConfig {
String password = _currentObjectParams.get("password"); String password = _currentObjectParams.get("password");
String email = _currentObjectParams.get("email"); String email = _currentObjectParams.get("email");
if (email == null || email.equals("")) { if (StringUtils.isNotEmpty(email)) {
printError("An email address for each user is required."); printError("An email address for each user is required.");
} }
@ -1209,7 +1057,7 @@ public class DatabaseConfig {
} }
} }
private void saveDefaultConfiguations() { private void saveDefaultConfigurations() {
for (String name : s_defaultConfigurationValues.keySet()) { for (String name : s_defaultConfigurationValues.keySet()) {
String value = s_defaultConfigurationValues.get(name); String value = s_defaultConfigurationValues.get(name);
saveConfiguration(name, value, null); saveConfiguration(name, value, null);
@ -1239,18 +1087,6 @@ public class DatabaseConfig {
} }
} }
if (name.equals("network.throttling.rate")) {
if (value != null && !value.isEmpty()) {
_networkThrottlingRate = value;
}
}
if (name.equals("multicast.throttling.rate")) {
if (value != null && !value.isEmpty()) {
_multicastThrottlingRate = value;
}
}
String insertSql = String insertSql =
"INSERT INTO `cloud`.`configuration` (instance, component, name, value, description, category) " + "INSERT INTO `cloud`.`configuration` (instance, component, name, value, description, category) " +
"VALUES (?,?,?,?,?,?)"; "VALUES (?,?,?,?,?,?)";
@ -1261,7 +1097,7 @@ public class DatabaseConfig {
PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql); PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
stmt.setString(1, name); stmt.setString(1, name);
ResultSet result = stmt.executeQuery(); ResultSet result = stmt.executeQuery();
Boolean hasRow = result.next(); boolean hasRow = result.next();
if (!hasRow) { if (!hasRow) {
stmt = txn.prepareAutoCloseStatement(insertSql); stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.setString(1, instance); stmt.setString(1, instance);
@ -1277,8 +1113,8 @@ public class DatabaseConfig {
} }
} }
private boolean checkIpAddressRange(String ipAddressRange) { private boolean checkInvalidIpAddressRange(String ipAddressRange) {
String[] ipAddressRangeArray = ipAddressRange.split("\\-"); String[] ipAddressRangeArray = ipAddressRange.split("-");
String startIP = ipAddressRangeArray[0]; String startIP = ipAddressRangeArray[0];
String endIP = null; String endIP = null;
if (ipAddressRangeArray.length > 1) { if (ipAddressRangeArray.length > 1) {
@ -1286,21 +1122,21 @@ public class DatabaseConfig {
} }
if (!IPRangeConfig.validIP(startIP)) { if (!IPRangeConfig.validIP(startIP)) {
LOGGER.error("The private IP address: " + startIP + " is invalid."); LOGGER.error("The private IP address: {} is invalid", startIP);
return false; return true;
} }
if (!IPRangeConfig.validOrBlankIP(endIP)) { if (!IPRangeConfig.validOrBlankIP(endIP)) {
LOGGER.error("The private IP address: " + endIP + " is invalid."); LOGGER.error("The private IP address: {} is invalid.", endIP);
return false; return true;
} }
if (!IPRangeConfig.validIPRange(startIP, endIP)) { if (!IPRangeConfig.validIPRange(startIP, endIP)) {
LOGGER.error("The IP range " + startIP + " -> " + endIP + " is invalid."); LOGGER.error("The IP range {} -> {} is invalid.", startIP, endIP);
return false; return true;
} }
return true; return false;
} }
@DB @DB
@ -1313,30 +1149,6 @@ public class DatabaseConfig {
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.error("error creating ROOT domain", ex); LOGGER.error("error creating ROOT domain", ex);
} }
/*
String updateSql = "update account set domain_id = 1 where id = 2";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareStatement(updateSql);
stmt.executeUpdate();
} catch (SQLException ex) {
LOGGER.error("error updating admin user", ex);
} finally {
txn.close();
}
updateSql = "update account set domain_id = 1 where id = 1";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareStatement(updateSql);
stmt.executeUpdate();
} catch (SQLException ex) {
LOGGER.error("error updating system user", ex);
} finally {
txn.close();
}
*/
} }
class DbConfigXMLHandler extends DefaultHandler { class DbConfigXMLHandler extends DefaultHandler {
@ -1347,7 +1159,7 @@ public class DatabaseConfig {
} }
@Override @Override
public void endElement(String s, String s1, String s2) throws SAXException { public void endElement(String s, String s1, String s2) {
if (DatabaseConfig.objectNames.contains(s2) || "object".equals(s2)) { if (DatabaseConfig.objectNames.contains(s2) || "object".equals(s2)) {
_parent.saveCurrentObject(); _parent.saveCurrentObject();
} else if (DatabaseConfig.fieldNames.contains(s2) || "field".equals(s2)) { } else if (DatabaseConfig.fieldNames.contains(s2) || "field".equals(s2)) {
@ -1356,19 +1168,19 @@ public class DatabaseConfig {
} }
@Override @Override
public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException { public void startElement(String s, String s1, String s2, Attributes attributes) {
if ("object".equals(s2)) { if ("object".equals(s2)) {
_parent.setCurrentObjectName(convertName(attributes.getValue("name"))); _parent.setCurrentObjectName(convertName(attributes.getValue("name")));
} else if ("field".equals(s2)) { } else if ("field".equals(s2)) {
if (_currentObjectParams == null) { if (_currentObjectParams == null) {
_currentObjectParams = new HashMap<String, String>(); _currentObjectParams = new HashMap<>();
} }
_currentFieldName = convertName(attributes.getValue("name")); _currentFieldName = convertName(attributes.getValue("name"));
} else if (DatabaseConfig.objectNames.contains(s2)) { } else if (DatabaseConfig.objectNames.contains(s2)) {
_parent.setCurrentObjectName(s2); _parent.setCurrentObjectName(s2);
} else if (DatabaseConfig.fieldNames.contains(s2)) { } else if (DatabaseConfig.fieldNames.contains(s2)) {
if (_currentObjectParams == null) { if (_currentObjectParams == null) {
_currentObjectParams = new HashMap<String, String>(); _currentObjectParams = new HashMap<>();
} }
_currentFieldName = s2; _currentFieldName = s2;
} }
@ -1390,53 +1202,41 @@ public class DatabaseConfig {
nameArray[i] = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase(); nameArray[i] = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
} }
name = ""; name = "";
for (int i = 0; i < nameArray.length; i++) { for (String s : nameArray) {
name = name.concat(nameArray[i]); name = name.concat(s);
} }
} }
return name; return name;
} }
} }
public static List<String> genReturnList(String success, String message) {
List<String> returnList = new ArrayList<String>(2);
returnList.add(0, success);
returnList.add(1, message);
return returnList;
}
public static void printError(String message) { public static void printError(String message) {
System.out.println(message); LOGGER.error(message);
System.exit(1); System.exit(1);
} }
public static String getDatabaseValueString(String selectSql, String name, String errorMsg) { public static String getDatabaseValueString(String selectSql, String name, String errorMsg) {
TransactionLegacy txn = TransactionLegacy.open("getDatabaseValueString");
PreparedStatement stmt = null;
try { try (TransactionLegacy txn = TransactionLegacy.open("getDatabaseValueString")) {
PreparedStatement stmt;
stmt = txn.prepareAutoCloseStatement(selectSql); stmt = txn.prepareAutoCloseStatement(selectSql);
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();
if (rs.next()) { if (rs.next()) {
String value = rs.getString(name); return rs.getString(name);
return value;
} else { } else {
return null; return null;
} }
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage());
printError(errorMsg); printError(errorMsg);
} finally {
txn.close();
} }
return null; return null;
} }
public static long getDatabaseValueLong(String selectSql, String name, String errorMsg) { public static long getDatabaseValueLong(String selectSql, String name, String errorMsg) {
TransactionLegacy txn = TransactionLegacy.open("getDatabaseValueLong");
PreparedStatement stmt = null;
try { try (TransactionLegacy txn = TransactionLegacy.open("getDatabaseValueLong")) {
PreparedStatement stmt;
stmt = txn.prepareAutoCloseStatement(selectSql); stmt = txn.prepareAutoCloseStatement(selectSql);
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();
if (rs.next()) { if (rs.next()) {
@ -1447,22 +1247,17 @@ public class DatabaseConfig {
} catch (SQLException e) { } catch (SQLException e) {
System.out.println("Exception: " + e.getMessage()); System.out.println("Exception: " + e.getMessage());
printError(errorMsg); printError(errorMsg);
} finally {
txn.close();
} }
return -1; return -1;
} }
public static void saveSQL(String sql, String errorMsg) { public static void saveSQL(String sql, String errorMsg) {
TransactionLegacy txn = TransactionLegacy.open("saveSQL"); try (TransactionLegacy txn = TransactionLegacy.open("saveSQL")) {
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(sql); PreparedStatement stmt = txn.prepareAutoCloseStatement(sql);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
System.out.println("SQL Exception: " + ex.getMessage()); LOGGER.error("SQL Exception: {}", ex, ex.getMessage());
printError(errorMsg); printError(errorMsg);
} finally {
txn.close();
} }
} }

View File

@ -30,8 +30,11 @@ import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class IPRangeConfig { public class IPRangeConfig {
protected static Logger LOGGER = LogManager.getLogger(IPRangeConfig.class);
public static void main(String[] args) { public static void main(String[] args) {
IPRangeConfig config = ComponentContext.inject(IPRangeConfig.class); IPRangeConfig config = ComponentContext.inject(IPRangeConfig.class);
@ -69,15 +72,14 @@ public class IPRangeConfig {
long zoneId = PodZoneConfig.getZoneId(zone); long zoneId = PodZoneConfig.getZoneId(zone);
result = changeRange(op, "public", -1, zoneId, startIP, endIP, null, -1); result = changeRange(op, "public", -1, zoneId, startIP, endIP, null, -1);
result = result.replaceAll("<br>", "/n"); result = result == null ? "<no renge>" : result.replaceAll("<br>", "/n");
System.out.println(result); LOGGER.info(result);
} else if (type.equals("private")) { } else if (type.equals("private")) {
if (args.length != 5 && args.length != 6) { if (args.length != 5 && args.length != 6) {
printError(usage()); printError(usage());
} }
String pod = args[2]; String pod = args[2];
String zone = args[3]; String zone = args[3];
;
String startIP = args[4]; String startIP = args[4];
String endIP = null; String endIP = null;
if (args.length == 6) { if (args.length == 6) {
@ -92,38 +94,13 @@ public class IPRangeConfig {
long podId = PodZoneConfig.getPodId(pod, zone); long podId = PodZoneConfig.getPodId(pod, zone);
long zoneId = PodZoneConfig.getZoneId(zone); long zoneId = PodZoneConfig.getZoneId(zone);
result = changeRange(op, "private", podId, zoneId, startIP, endIP, null, -1); result = changeRange(op, "private", podId, zoneId, startIP, endIP, null, -1);
result = result.replaceAll("<br>", "/n"); result = result == null ? "<no renge>" : result.replaceAll("<br>", "/n");
System.out.println(result); LOGGER.info(result);
} else { } else {
printError(usage()); LOGGER.error(usage());
} }
} }
public List<String> changePublicIPRangeGUI(String op, String zone, String startIP, String endIP, long physicalNetworkId) {
String result = checkErrors("public", op, null, zone, startIP, endIP);
if (!result.equals("success")) {
return DatabaseConfig.genReturnList("false", result);
}
long zoneId = PodZoneConfig.getZoneId(zone);
result = changeRange(op, "public", -1, zoneId, startIP, endIP, null, physicalNetworkId);
return DatabaseConfig.genReturnList("true", result);
}
public List<String> changePrivateIPRangeGUI(String op, String pod, String zone, String startIP, String endIP) {
String result = checkErrors("private", op, pod, zone, startIP, endIP);
if (!result.equals("success")) {
return DatabaseConfig.genReturnList("false", result);
}
long podId = PodZoneConfig.getPodId(pod, zone);
long zoneId = PodZoneConfig.getZoneId(zone);
result = changeRange(op, "private", podId, zoneId, startIP, endIP, null, -1);
return DatabaseConfig.genReturnList("true", result);
}
private String checkErrors(String type, String op, String pod, String zone, String startIP, String endIP) { private String checkErrors(String type, String op, String pod, String zone, String startIP, String endIP) {
if (!op.equals("add") && !op.equals("delete")) { if (!op.equals("add") && !op.equals("delete")) {
return usage(); return usage();
@ -153,15 +130,7 @@ public class IPRangeConfig {
} }
// Check that the IPs that are being added are compatible with either the zone's public netmask, or the pod's CIDR // Check that the IPs that are being added are compatible with either the zone's public netmask, or the pod's CIDR
if (type.equals("public")) { if (type.equals("private")) {
// String publicNetmask = getPublicNetmask(zone);
// String publicGateway = getPublicGateway(zone);
// if (publicNetmask == null) return "Please ensure that your zone's public net mask is specified";
// if (!sameSubnet(startIP, endIP, publicNetmask)) return "Please ensure that your start IP and end IP are in the same subnet, as per the zone's netmask.";
// if (!sameSubnet(startIP, publicGateway, publicNetmask)) return "Please ensure that your start IP is in the same subnet as your zone's gateway, as per the zone's netmask.";
// if (!sameSubnet(endIP, publicGateway, publicNetmask)) return "Please ensure that your end IP is in the same subnet as your zone's gateway, as per the zone's netmask.";
} else if (type.equals("private")) {
String cidrAddress = getCidrAddress(pod, zone); String cidrAddress = getCidrAddress(pod, zone);
long cidrSize = getCidrSize(pod, zone); long cidrSize = getCidrSize(pod, zone);
@ -188,7 +157,7 @@ public class IPRangeConfig {
return ""; return "";
} }
if (problemIPs.size() == 0) { if (problemIPs.isEmpty()) {
if (op.equals("add")) { if (op.equals("add")) {
return "Successfully added all IPs in the specified range."; return "Successfully added all IPs in the specified range.";
} else if (op.equals("delete")) { } else if (op.equals("delete")) {
@ -197,29 +166,29 @@ public class IPRangeConfig {
return ""; return "";
} }
} else { } else {
String successString = ""; StringBuilder successString = new StringBuilder();
if (op.equals("add")) { if (op.equals("add")) {
successString += "Failed to add the following IPs, because they are already in the database: <br><br>"; successString.append("Failed to add the following IPs, because they are already in the database: <br><br>");
} else if (op.equals("delete")) { } else if (op.equals("delete")) {
successString += "Failed to delete the following IPs, because they are in use: <br><br>"; successString.append("Failed to delete the following IPs, because they are in use: <br><br>");
} }
for (int i = 0; i < problemIPs.size(); i++) { for (int i = 0; i < problemIPs.size(); i++) {
successString += problemIPs.get(i); successString.append(problemIPs.get(i));
if (i != (problemIPs.size() - 1)) { if (i != (problemIPs.size() - 1)) {
successString += ", "; successString.append(", ");
} }
} }
successString += "<br><br>"; successString.append("<br><br>");
if (op.equals("add")) { if (op.equals("add")) {
successString += "Successfully added all other IPs in the specified range."; successString.append("Successfully added all other IPs in the specified range.");
} else if (op.equals("delete")) { } else if (op.equals("delete")) {
successString += "Successfully deleted all other IPs in the specified range."; successString.append("Successfully deleted all other IPs in the specified range.");
} }
return successString; return successString.toString();
} }
} }
@ -240,46 +209,6 @@ public class IPRangeConfig {
} }
} }
private String genSuccessString(Vector<String> problemIPs, String op) {
if (problemIPs == null) {
return "";
}
if (problemIPs.size() == 0) {
if (op.equals("add")) {
return "Successfully added all IPs in the specified range.";
} else if (op.equals("delete")) {
return "Successfully deleted all IPs in the specified range.";
} else {
return "";
}
} else {
String successString = "";
if (op.equals("add")) {
successString += "Failed to add the following IPs, because they are already in the database: <br><br>";
} else if (op.equals("delete")) {
successString += "Failed to delete the following IPs, because they are in use: <br><br>";
}
for (int i = 0; i < problemIPs.size(); i++) {
successString += problemIPs.elementAt(i);
if (i != (problemIPs.size() - 1)) {
successString += ", ";
}
}
successString += "<br><br>";
if (op.equals("add")) {
successString += "Successfully added all other IPs in the specified range.";
} else if (op.equals("delete")) {
successString += "Successfully deleted all other IPs in the specified range.";
}
return successString;
}
}
public static String getCidrAddress(String pod, String zone) { public static String getCidrAddress(String pod, String zone) {
long dcId = PodZoneConfig.getZoneId(zone); long dcId = PodZoneConfig.getZoneId(zone);
String selectSql = "SELECT * FROM `cloud`.`host_pod_ref` WHERE name = \"" + pod + "\" AND data_center_id = \"" + dcId + "\""; String selectSql = "SELECT * FROM `cloud`.`host_pod_ref` WHERE name = \"" + pod + "\" AND data_center_id = \"" + dcId + "\"";
@ -316,8 +245,8 @@ public class IPRangeConfig {
public Vector<String> updatePublicIPRange(TransactionLegacy txn, long startIP, long endIP, long vlanDbId, boolean forSystemvms) { public Vector<String> updatePublicIPRange(TransactionLegacy txn, long startIP, long endIP, long vlanDbId, boolean forSystemvms) {
String updateSql = "UPDATE `cloud`.`user_ip_address` SET forsystemvms = ? WHERE public_ip_address = ? AND vlan_db_id = ?"; String updateSql = "UPDATE `cloud`.`user_ip_address` SET forsystemvms = ? WHERE public_ip_address = ? AND vlan_db_id = ?";
Vector<String> problemIPs = new Vector<String>(); Vector<String> problemIPs = new Vector<>();
Connection conn = null; Connection conn;
try { try {
conn = txn.getConnection(); conn = txn.getConnection();
} }
@ -325,7 +254,7 @@ public class IPRangeConfig {
System.out.println("updatePublicIPRange. Exception: " + e.getMessage()); System.out.println("updatePublicIPRange. Exception: " + e.getMessage());
return null; return null;
} }
try (PreparedStatement stmt = conn.prepareStatement(updateSql);) { try (PreparedStatement stmt = conn.prepareStatement(updateSql)) {
while (startIP <= endIP) { while (startIP <= endIP) {
stmt.clearParameters(); stmt.clearParameters();
stmt.setBoolean(1, forSystemvms); stmt.setBoolean(1, forSystemvms);
@ -346,8 +275,8 @@ public class IPRangeConfig {
String deleteSql = "DELETE FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_db_id = ?"; String deleteSql = "DELETE FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_db_id = ?";
String isPublicIPAllocatedSelectSql = "SELECT * FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_db_id = ?"; String isPublicIPAllocatedSelectSql = "SELECT * FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_db_id = ?";
Vector<String> problemIPs = new Vector<String>(); Vector<String> problemIPs = new Vector<>();
Connection conn = null; Connection conn;
try { try {
conn = txn.getConnection(); conn = txn.getConnection();
} }
@ -356,7 +285,7 @@ public class IPRangeConfig {
return null; return null;
} }
try (PreparedStatement stmt = conn.prepareStatement(deleteSql); try (PreparedStatement stmt = conn.prepareStatement(deleteSql);
PreparedStatement isAllocatedStmt = conn.prepareStatement(isPublicIPAllocatedSelectSql);) { PreparedStatement isAllocatedStmt = conn.prepareStatement(isPublicIPAllocatedSelectSql)) {
while (startIP <= endIP) { while (startIP <= endIP) {
if (!isPublicIPAllocated(NetUtils.long2Ip(startIP), vlanDbId, isAllocatedStmt)) { if (!isPublicIPAllocated(NetUtils.long2Ip(startIP), vlanDbId, isAllocatedStmt)) {
stmt.clearParameters(); stmt.clearParameters();
@ -380,11 +309,11 @@ public class IPRangeConfig {
private Vector<String> deletePrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) { private Vector<String> deletePrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
String deleteSql = "DELETE FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND pod_id = ? AND data_center_id = ?"; String deleteSql = "DELETE FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND pod_id = ? AND data_center_id = ?";
String isPrivateIPAllocatedSelectSql = "SELECT * FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND data_center_id = ? AND pod_id = ?"; String isPrivateIPAllocatedSelectSql = "SELECT * FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND data_center_id = ? AND pod_id = ?";
Vector<String> problemIPs = new Vector<String>(); Vector<String> problemIPs = new Vector<>();
try { try {
Connection conn = txn.getConnection(); Connection conn = txn.getConnection();
try (PreparedStatement stmt = conn.prepareStatement(deleteSql); try (PreparedStatement stmt = conn.prepareStatement(deleteSql);
PreparedStatement isAllocatedStmt = conn.prepareStatement(isPrivateIPAllocatedSelectSql);) { PreparedStatement isAllocatedStmt = conn.prepareStatement(isPrivateIPAllocatedSelectSql)) {
while (startIP <= endIP) { while (startIP <= endIP) {
if (!isPrivateIPAllocated(NetUtils.long2Ip(startIP), podId, zoneId, isAllocatedStmt)) { if (!isPrivateIPAllocated(NetUtils.long2Ip(startIP), podId, zoneId, isAllocatedStmt)) {
stmt.clearParameters(); stmt.clearParameters();
@ -436,7 +365,7 @@ public class IPRangeConfig {
stmt.setString(1, ip); stmt.setString(1, ip);
stmt.setLong(2, zoneId); stmt.setLong(2, zoneId);
stmt.setLong(3, podId); stmt.setLong(3, podId);
try(ResultSet rs = stmt.executeQuery();) { try(ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { if (rs.next()) {
return (rs.getString("taken") != null); return (rs.getString("taken") != null);
} else { } else {
@ -483,9 +412,9 @@ public class IPRangeConfig {
String insertSql = String insertSql =
"INSERT INTO `cloud`.`user_ip_address` (public_ip_address, data_center_id, vlan_db_id, mac_address, source_network_id, physical_network_id, uuid, forsystemvms) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?, ?, ?, ?)"; "INSERT INTO `cloud`.`user_ip_address` (public_ip_address, data_center_id, vlan_db_id, mac_address, source_network_id, physical_network_id, uuid, forsystemvms) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?, ?, ?, ?)";
String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
Vector<String> problemIPs = new Vector<String>(); Vector<String> problemIPs = new Vector<>();
Connection conn = null; Connection conn;
try { try {
conn = txn.getConnection(); conn = txn.getConnection();
} catch (SQLException e) { } catch (SQLException e) {
@ -493,7 +422,7 @@ public class IPRangeConfig {
} }
while (startIP <= endIP) { while (startIP <= endIP) {
try (PreparedStatement insert_stmt = conn.prepareStatement(insertSql); try (PreparedStatement insert_stmt = conn.prepareStatement(insertSql);
PreparedStatement update_stmt = conn.prepareStatement(updateSql); PreparedStatement update_stmt = conn.prepareStatement(updateSql)
){ ){
insert_stmt.setString(1, NetUtils.long2Ip(startIP)); insert_stmt.setString(1, NetUtils.long2Ip(startIP));
insert_stmt.setLong(2, zoneId); insert_stmt.setLong(2, zoneId);
@ -519,13 +448,13 @@ public class IPRangeConfig {
String insertSql = String insertSql =
"INSERT INTO `cloud`.`op_dc_ip_address_alloc` (ip_address, data_center_id, pod_id, mac_address) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?))"; "INSERT INTO `cloud`.`op_dc_ip_address_alloc` (ip_address, data_center_id, pod_id, mac_address) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?))";
String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
Vector<String> problemIPs = new Vector<String>(); Vector<String> problemIPs = new Vector<>();
try { try {
Connection conn = txn.getConnection(); Connection conn = txn.getConnection();
while (startIP <= endIP) { while (startIP <= endIP) {
try (PreparedStatement insert_stmt = conn.prepareStatement(insertSql); try (PreparedStatement insert_stmt = conn.prepareStatement(insertSql);
PreparedStatement update_stmt = conn.prepareStatement(updateSql); PreparedStatement update_stmt = conn.prepareStatement(updateSql)
) )
{ {
insert_stmt.setString(1, NetUtils.long2Ip(startIP)); insert_stmt.setString(1, NetUtils.long2Ip(startIP));
@ -541,8 +470,7 @@ public class IPRangeConfig {
startIP++; startIP++;
} }
} catch (Exception ex) { } catch (Exception ex) {
System.out.print(ex.getMessage()); LOGGER.error(ex.getMessage(), ex);
ex.printStackTrace();
} }
return problemIPs; return problemIPs;
@ -550,7 +478,7 @@ public class IPRangeConfig {
private Vector<String> saveLinkLocalPrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) { private Vector<String> saveLinkLocalPrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
String insertSql = "INSERT INTO `cloud`.`op_dc_link_local_ip_address_alloc` (ip_address, data_center_id, pod_id) VALUES (?, ?, ?)"; String insertSql = "INSERT INTO `cloud`.`op_dc_link_local_ip_address_alloc` (ip_address, data_center_id, pod_id) VALUES (?, ?, ?)";
Vector<String> problemIPs = new Vector<String>(); Vector<String> problemIPs = new Vector<>();
Connection conn = null; Connection conn = null;
try { try {
@ -581,16 +509,6 @@ public class IPRangeConfig {
return problemIPs; return problemIPs;
} }
public static String getPublicNetmask(String zone) {
return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`data_center` WHERE name = \"" + zone + "\"", "netmask",
"Unable to start DB connection to read public netmask. Please contact Cloud Support.");
}
public static String getPublicGateway(String zone) {
return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`data_center` WHERE name = \"" + zone + "\"", "gateway",
"Unable to start DB connection to read public gateway. Please contact Cloud Support.");
}
public static String getGuestNetworkCidr(Long zoneId) { public static String getGuestNetworkCidr(Long zoneId) {
return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`data_center` WHERE id = \"" + zoneId + "\"", "guest_network_cidr", return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`data_center` WHERE id = \"" + zoneId + "\"", "guest_network_cidr",
"Unable to start DB connection to read guest cidr network. Please contact Cloud Support."); "Unable to start DB connection to read guest cidr network. Please contact Cloud Support.");

View File

@ -190,11 +190,6 @@ public class PodZoneConfig {
return currentPodCidrSubnets; return currentPodCidrSubnets;
} }
public void deletePod(String name, long dcId) {
String sql = "DELETE FROM `cloud`.`host_pod_ref` WHERE name=\"" + name + "\" AND data_center_id=\"" + dcId + "\"";
DatabaseConfig.saveSQL(sql, "Failed to delete pod due to exception. Please contact Cloud Support.");
}
public long getVlanDbId(String zone, String vlanId) { public long getVlanDbId(String zone, String vlanId) {
long zoneId = getZoneId(zone); long zoneId = getZoneId(zone);
@ -477,11 +472,6 @@ public class PodZoneConfig {
"Unable to start DB connection to read configuration. Please contact Cloud Support."); "Unable to start DB connection to read configuration. Please contact Cloud Support.");
} }
public void deleteZone(String name) {
String sql = "DELETE FROM `cloud`.`data_center` WHERE name=\"" + name + "\"";
DatabaseConfig.saveSQL(sql, "Failed to delete zone due to exception. Please contact Cloud Support.");
}
public void saveVlan(long zoneId, Long podId, String vlanId, String vlanGateway, String vlanNetmask, String vlanType, String ipRange, long networkId, public void saveVlan(long zoneId, Long podId, String vlanId, String vlanGateway, String vlanNetmask, String vlanType, String ipRange, long networkId,
long physicalNetworkId) { long physicalNetworkId) {
String sql = String sql =