use of com.cloud.legacymodel.exceptions.InvalidParameterValueException in project cosmic by MissionCriticalCloud.
the class ConfigurationManagerImpl method validateConfigurationValue.
private String validateConfigurationValue(final String name, String value, final String scope) {
final ConfigurationVO cfg = _configDao.findByName(name);
if (cfg == null) {
s_logger.error("Missing configuration variable " + name + " in configuration table");
return "Invalid configuration variable.";
}
final String configScope = cfg.getScope();
if (scope != null) {
if (!configScope.contains(scope)) {
s_logger.error("Invalid scope id provided for the parameter " + name);
return "Invalid scope id provided for the parameter " + name;
}
}
final Class<?> type;
final Config c = Config.getConfig(name);
if (c == null) {
s_logger.warn("Did not find configuration " + name + " in Config.java. Perhaps moved to ConfigDepot");
final ConfigKey<?> configKey = _configDepot.get(name);
if (configKey == null) {
s_logger.warn("Did not find configuration " + name + " in ConfigDepot too.");
return null;
}
type = configKey.type();
} else {
type = c.getType();
}
String errMsg = null;
try {
if (type.equals(Integer.class)) {
errMsg = "There was error in trying to parse value: " + value + ". Please enter a valid integer value for parameter " + name;
Integer.parseInt(value);
} else if (type.equals(Float.class)) {
errMsg = "There was error in trying to parse value: " + value + ". Please enter a valid float value for parameter " + name;
Float.parseFloat(value);
}
} catch (final Exception e) {
// catching generic exception as some throws NullPointerException and some throws NumberFormatExcpeion
s_logger.error(errMsg);
return errMsg;
}
if (value == null) {
if (type.equals(Boolean.class)) {
return "Please enter either 'true' or 'false'.";
}
if (overprovisioningFactorsForValidation.contains(name)) {
final String msg = "value cannot be null for the parameter " + name;
s_logger.error(msg);
return msg;
}
return null;
}
value = value.trim();
try {
if (overprovisioningFactorsForValidation.contains(name) && Float.parseFloat(value) < 1f) {
final String msg = name + " should be greater than or equal to 1";
s_logger.error(msg);
throw new InvalidParameterValueException(msg);
}
} catch (final NumberFormatException e) {
final String msg = "There was an error trying to parse the float value for: " + name;
s_logger.error(msg);
throw new InvalidParameterValueException(msg);
}
if (type.equals(Boolean.class)) {
if (!(value.equals("true") || value.equals("false"))) {
s_logger.error("Configuration variable " + name + " is expecting true or false instead of " + value);
return "Please enter either 'true' or 'false'.";
}
return null;
}
if (type.equals(Integer.class) && configValuesForValidation.contains(name)) {
try {
final int val = Integer.parseInt(value);
if (val <= 0) {
throw new InvalidParameterValueException("Please enter a positive value for the configuration parameter:" + name);
}
// TODO - better validation for all password pamameters
if ("vm.password.length".equalsIgnoreCase(name) && val < 10) {
throw new InvalidParameterValueException("Please enter a value greater than 6 for the configuration parameter:" + name);
}
if ("remote.access.vpn.psk.length".equalsIgnoreCase(name)) {
if (val < 8) {
throw new InvalidParameterValueException("Please enter a value greater than 8 for the configuration parameter:" + name);
}
if (val > 256) {
throw new InvalidParameterValueException("Please enter a value less than 256 for the configuration parameter:" + name);
}
}
} catch (final NumberFormatException e) {
s_logger.error("There was an error trying to parse the integer value for:" + name);
throw new InvalidParameterValueException("There was an error trying to parse the integer value for:" + name);
}
}
if (type.equals(Float.class)) {
try {
final Float val = Float.parseFloat(value);
if (weightBasedParametersForValidation.contains(name) && (val < 0f || val > 1f)) {
throw new InvalidParameterValueException("Please enter a value between 0 and 1 for the configuration parameter: " + name);
}
} catch (final NumberFormatException e) {
s_logger.error("There was an error trying to parse the float value for:" + name);
throw new InvalidParameterValueException("There was an error trying to parse the float value for:" + name);
}
}
if (c == null) {
// return in case of Configkey parameters
return null;
}
final String range = c.getRange();
if (range == null) {
return null;
}
if (type.equals(String.class)) {
if (range.equals("privateip")) {
try {
if (!NetUtils.isSiteLocalAddress(value)) {
s_logger.error("privateip range " + value + " is not a site local address for configuration variable " + name);
return "Please enter a site local IP address.";
}
} catch (final NullPointerException e) {
s_logger.error("Error parsing ip address for " + name);
throw new InvalidParameterValueException("Error parsing ip address");
}
} else if (range.equals("netmask")) {
if (!NetUtils.isValidIp4Netmask(value)) {
s_logger.error("netmask " + value + " is not a valid net mask for configuration variable " + name);
return "Please enter a valid netmask.";
}
} else if (range.equals("hypervisorList")) {
final String[] hypervisors = value.split(",");
if (hypervisors == null) {
return "Please enter hypervisor list, separated by comma";
}
for (final String hypervisor : hypervisors) {
if (HypervisorType.getType(hypervisor) == HypervisorType.Any || HypervisorType.getType(hypervisor) == HypervisorType.None) {
return "Please enter a valid hypervisor type";
}
}
} else if (range.equalsIgnoreCase("instanceName")) {
if (!NetUtils.verifyInstanceName(value)) {
return "Instance name can not contain hyphen, space or plus sign";
}
} else if (range.equalsIgnoreCase("domainName")) {
String domainName = value;
if (value.startsWith("*")) {
// skip the "*."
domainName = value.substring(2);
}
// max length for FQDN is 253 + 2, code adds xxx-xxx-xxx-xxx to domain name when creating URL
if (domainName.length() >= 238 || !domainName.matches(DOMAIN_NAME_PATTERN)) {
return "Please enter a valid string for domain name, prefixed with '*.' if applicable";
}
} else if (range.equals("routes")) {
final String[] routes = value.split(",");
for (final String route : routes) {
if (route != null) {
final String routeToVerify = route.trim();
if (!NetUtils.isValidIp4Cidr(routeToVerify)) {
throw new InvalidParameterValueException("Invalid value for blacklisted route: " + route + ". Valid format is list" + " of cidrs separated by coma. Example: 10.1.1.0/24,192.168.0.0/24");
}
}
}
} else {
final String[] options = range.split(",");
for (final String option : options) {
if (option.trim().equalsIgnoreCase(value)) {
return null;
}
}
s_logger.error("configuration value for " + name + " is invalid");
return "Please enter : " + range;
}
} else if (type.equals(Integer.class)) {
final String[] options = range.split("-");
if (options.length != 2) {
final String msg = "configuration range " + range + " for " + name + " is invalid";
s_logger.error(msg);
return msg;
}
final int min = Integer.parseInt(options[0]);
final int max = Integer.parseInt(options[1]);
final int val = Integer.parseInt(value);
if (val < min || val > max) {
s_logger.error("configuration value for " + name + " is invalid");
return "Please enter : " + range;
}
}
return null;
}
use of com.cloud.legacymodel.exceptions.InvalidParameterValueException in project cosmic by MissionCriticalCloud.
the class ConfigurationManagerImpl method validateSourceNatServiceCapablities.
void validateSourceNatServiceCapablities(final Map<Capability, String> sourceNatServiceCapabilityMap) {
if (sourceNatServiceCapabilityMap != null && !sourceNatServiceCapabilityMap.isEmpty()) {
if (sourceNatServiceCapabilityMap.keySet().size() > 2) {
throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + " capabilities can be sepcified for source nat service");
}
for (final Map.Entry<Capability, String> srcNatPair : sourceNatServiceCapabilityMap.entrySet()) {
final Capability capability = srcNatPair.getKey();
final String value = srcNatPair.getValue();
if (capability == Capability.SupportedSourceNatTypes) {
final boolean perAccount = value.contains("peraccount");
final boolean perZone = value.contains("perzone");
if (perAccount && perZone || !perAccount && !perZone) {
throw new InvalidParameterValueException("Either peraccount or perzone source NAT type can be specified for " + Capability.SupportedSourceNatTypes.getName());
}
} else if (capability == Capability.RedundantRouter) {
final boolean enabled = value.contains("true");
final boolean disabled = value.contains("false");
if (!enabled && !disabled) {
throw new InvalidParameterValueException("Unknown specified value for " + Capability.RedundantRouter.getName());
}
} else {
throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + " capabilities can be sepcified for source nat service");
}
}
}
}
use of com.cloud.legacymodel.exceptions.InvalidParameterValueException in project cosmic by MissionCriticalCloud.
the class ConfigurationManagerImpl method updateConfiguration.
@Override
@ActionEvent(eventType = EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, eventDescription = "updating configuration")
public Configuration updateConfiguration(final UpdateCfgCmd cmd) throws InvalidParameterValueException {
final Long userId = CallContext.current().getCallingUserId();
final Account caller = CallContext.current().getCallingAccount();
final User user = _userDao.findById(userId);
final String name = cmd.getCfgName();
String value = cmd.getValue();
final Long zoneId = cmd.getZoneId();
final Long clusterId = cmd.getClusterId();
final Long storagepoolId = cmd.getStoragepoolId();
final Long accountId = cmd.getAccountId();
CallContext.current().setEventDetails(" Name: " + name + " New Value: " + (name.toLowerCase().contains("password") ? "*****" : value == null ? "" : value));
// check if config value exists
final ConfigurationVO config = _configDao.findByName(name);
final String catergory;
// FIX ME - All configuration parameters are not moved from config.java to configKey
if (config == null) {
if (_configDepot.get(name) == null) {
s_logger.warn("Probably the component manager where configuration variable " + name + " is defined needs to implement Configurable interface");
throw new InvalidParameterValueException("Config parameter with name " + name + " doesn't exist");
}
catergory = _configDepot.get(name).category();
} else {
catergory = config.getCategory();
}
if (value == null) {
return _configDao.findByName(name);
}
value = value.trim();
if (value.isEmpty() || value.equals("null")) {
value = null;
}
String scope = null;
Long id = null;
int paramCountCheck = 0;
// Non-ROOT may only update the Account scope
if (!_accountMgr.isRootAdmin(caller.getId()) && accountId == null) {
throw new InvalidParameterValueException("Please specify AccountId to update the config for the given account.");
}
if (accountId != null) {
final Account accountToUpdate = _accountDao.findById(accountId);
_accountMgr.checkAccess(caller, null, true, accountToUpdate);
scope = ConfigKey.Scope.Account.toString();
id = accountId;
paramCountCheck++;
}
if (_accountMgr.isRootAdmin(caller.getId())) {
if (zoneId != null) {
scope = ConfigKey.Scope.Zone.toString();
id = zoneId;
paramCountCheck++;
}
if (clusterId != null) {
scope = ConfigKey.Scope.Cluster.toString();
id = clusterId;
paramCountCheck++;
}
if (storagepoolId != null) {
scope = ConfigKey.Scope.StoragePool.toString();
id = storagepoolId;
paramCountCheck++;
}
}
if (paramCountCheck > 1) {
throw new InvalidParameterValueException("cannot handle multiple IDs, provide only one ID corresponding to the scope");
}
final String updatedValue = updateConfiguration(userId, name, catergory, value, scope, id);
if (value == null && updatedValue == null || updatedValue.equalsIgnoreCase(value)) {
return _configDao.findByName(name);
} else {
throw new CloudRuntimeException("Unable to update configuration parameter " + name);
}
}
use of com.cloud.legacymodel.exceptions.InvalidParameterValueException in project cosmic by MissionCriticalCloud.
the class ConfigurationManagerImpl method createVlanAndPublicIpRange.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_CREATE, eventDescription = "creating vlan ip range", async = false)
public Vlan createVlanAndPublicIpRange(final CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException {
Long zoneId = cmd.getZoneId();
final Long podId = cmd.getPodId();
final String startIP = cmd.getStartIp();
String endIP = cmd.getEndIp();
final String newVlanGateway = cmd.getGateway();
final String newVlanNetmask = cmd.getNetmask();
String vlanId = cmd.getVlan();
// TODO decide if we should be forgiving or demand a valid and complete URI
if (!(vlanId == null || "".equals(vlanId) || vlanId.startsWith(BroadcastDomainType.Vlan.scheme()))) {
vlanId = BroadcastDomainType.Vlan.toUri(vlanId).toString();
}
final Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
Long networkId = cmd.getNetworkID();
Long physicalNetworkId = cmd.getPhysicalNetworkId();
final String accountName = cmd.getAccountName();
final Long projectId = cmd.getProjectId();
final Long domainId = cmd.getDomainId();
final String startIPv6 = cmd.getStartIpv6();
String endIPv6 = cmd.getEndIpv6();
final String ip6Gateway = cmd.getIp6Gateway();
final String ip6Cidr = cmd.getIp6Cidr();
Account vlanOwner = null;
final boolean ipv4 = startIP != null;
final boolean ipv6 = startIPv6 != null;
if (!ipv4 && !ipv6) {
throw new InvalidParameterValueException("StartIP or StartIPv6 is missing in the parameters!");
}
if (ipv4) {
// if end ip is not specified, default it to startIp
if (endIP == null && startIP != null) {
endIP = startIP;
}
}
if (ipv6) {
// if end ip is not specified, default it to startIp
if (endIPv6 == null && startIPv6 != null) {
endIPv6 = startIPv6;
}
}
if (projectId != null) {
if (accountName != null) {
throw new InvalidParameterValueException("Account and projectId are mutually exclusive");
}
final Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by id " + projectId);
}
vlanOwner = _accountMgr.getAccount(project.getProjectAccountId());
if (vlanOwner == null) {
throw new InvalidParameterValueException("Please specify a valid projectId");
}
}
Domain domain = null;
if (accountName != null && domainId != null) {
vlanOwner = _accountDao.findActiveAccount(accountName, domainId);
if (vlanOwner == null) {
throw new InvalidParameterValueException("Please specify a valid account.");
} else if (vlanOwner.getId() == Account.ACCOUNT_ID_SYSTEM) {
// by default vlan is dedicated to system account
vlanOwner = null;
}
} else if (domainId != null) {
domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Please specify a valid domain id");
}
}
// Verify that network exists
Network network = null;
if (networkId != null) {
network = _networkDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Unable to find network by id " + networkId);
} else {
zoneId = network.getDataCenterId();
physicalNetworkId = network.getPhysicalNetworkId();
}
} else if (ipv6) {
throw new InvalidParameterValueException("Only support IPv6 on extending existed network");
}
// Verify that zone exists
final DataCenterVO zone = _zoneDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
}
if (ipv6) {
if (network.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only support IPv6 on extending existed share network without SG");
}
}
// verify that physical network exists
final PhysicalNetworkVO pNtwk;
if (physicalNetworkId != null) {
pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
throw new InvalidParameterValueException("Unable to find Physical Network with id=" + physicalNetworkId);
}
if (zoneId == null) {
zoneId = pNtwk.getDataCenterId();
}
} else {
if (zoneId == null) {
throw new InvalidParameterValueException("");
}
// deduce physicalNetworkFrom Zone or Network.
if (network != null && network.getPhysicalNetworkId() != null) {
physicalNetworkId = network.getPhysicalNetworkId();
} else {
if (forVirtualNetwork) {
// default physical network with public traffic in the zone
physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId();
} else {
if (zone.getNetworkType() == NetworkType.Basic) {
// default physical network with guest traffic in the
// zone
physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId();
} else if (zone.getNetworkType() == NetworkType.Advanced) {
throw new InvalidParameterValueException("Physical Network Id is null, please provide the Network id for Direct vlan creation ");
}
}
}
}
// Check if zone is enabled
final Account caller = CallContext.current().getCallingAccount();
if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
// Untagged, try to locate default networks
if (forVirtualNetwork) {
if (network == null) {
// find default public network in the zone
networkId = _networkModel.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId();
network = _networkModel.getNetwork(networkId);
} else if (network.getGuestType() != null || network.getTrafficType() != TrafficType.Public) {
throw new InvalidParameterValueException("Can't find Public network by id=" + networkId);
}
} else {
if (network == null) {
if (zone.getNetworkType() == NetworkType.Basic) {
networkId = _networkModel.getExclusiveGuestNetwork(zoneId).getId();
network = _networkModel.getNetwork(networkId);
}
} else if (network.getGuestType() == null || network.getGuestType() == GuestType.Isolated && _ntwkOffServiceMapDao.areServicesSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getGuestType());
}
}
Pair<Boolean, Pair<String, String>> sameSubnet = null;
// Can add vlan range only to the network which allows it
if (!network.getSpecifyIpRanges()) {
throw new InvalidParameterValueException("Network " + network + " doesn't support adding ip ranges");
}
if (zone.getNetworkType() == NetworkType.Advanced) {
if (network.getTrafficType() == TrafficType.Guest) {
if (network.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network " + network.getId() + " is " + network.getGuestType());
}
final List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
if (vlans != null && vlans.size() > 0) {
final VlanVO vlan = vlans.get(0);
if (vlanId == null || vlanId.contains(Vlan.UNTAGGED)) {
vlanId = vlan.getVlanTag();
} else if (!NetUtils.isSameIsolationId(vlan.getVlanTag(), vlanId)) {
throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" + +network.getId() + ", only one vlan is allowed on guest network");
}
}
sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
}
} else if (network.getTrafficType() == TrafficType.Management) {
throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network");
} else if (zone.getNetworkType() == NetworkType.Basic) {
final List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
}
if (zoneId == null || ipv6 && (ip6Gateway == null || ip6Cidr == null)) {
throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks");
}
if (forVirtualNetwork) {
if (vlanOwner != null) {
final long accountIpRange = NetUtils.ip2Long(endIP) - NetUtils.ip2Long(startIP) + 1;
// check resource limits
_resourceLimitMgr.checkResourceLimit(vlanOwner, ResourceType.public_ip, accountIpRange);
}
}
// Check if the IP range overlaps with the private ip
if (ipv4) {
checkOverlapPrivateIpRange(zoneId, startIP, endIP);
}
return commitVlan(zoneId, podId, startIP, endIP, newVlanGateway, newVlanNetmask, vlanId, forVirtualNetwork, networkId, physicalNetworkId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, domain, vlanOwner, network, sameSubnet);
}
use of com.cloud.legacymodel.exceptions.InvalidParameterValueException in project cosmic by MissionCriticalCloud.
the class ConfigurationManagerImpl method createZone.
@Override
@DB
public DataCenterVO createZone(final long userId, final String zoneName, final String dns1, final String dns2, final String internalDns1, final String internalDns2, final String guestCidr, final String domain, final Long domainId, final NetworkType zoneType, final String allocationStateStr, final String networkDomain, final boolean isLocalStorageEnabled, final String ip6Dns1, final String ip6Dns2) {
// hence the method below is generic to check for common params
if (guestCidr != null && !NetUtils.validateGuestCidr(guestCidr)) {
throw new InvalidParameterValueException("Please enter a valid guest cidr");
}
// Validate network domain
if (networkDomain != null) {
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters " + "'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
}
}
checkZoneParameters(zoneName, dns1, dns2, internalDns1, internalDns2, true, domainId, allocationStateStr, ip6Dns1, ip6Dns2);
final byte[] bytes = (zoneName + System.currentTimeMillis()).getBytes();
final String zoneToken = UUID.nameUUIDFromBytes(bytes).toString();
// Create the new zone in the database
final DataCenterVO zoneFinal = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr, domain, domainId, zoneType, zoneToken, networkDomain, ip6Dns1, ip6Dns2);
if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
final AllocationState allocationState = AllocationState.valueOf(allocationStateStr);
zoneFinal.setAllocationState(allocationState);
} else {
// Zone will be disabled since 3.0. Admin should enable it after
// physical network and providers setup.
zoneFinal.setAllocationState(AllocationState.Disabled);
}
return Transaction.execute(new TransactionCallback<DataCenterVO>() {
@Override
public DataCenterVO doInTransaction(final TransactionStatus status) {
final DataCenterVO zone = _zoneDao.persist(zoneFinal);
if (domainId != null) {
// zone is explicitly dedicated to this domain
// create affinity group associated and dedicate the zone.
final AffinityGroup group = createDedicatedAffinityGroup(null, domainId, null);
final DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zone.getId(), null, null, null, domainId, null, group.getId());
_dedicatedDao.persist(dedicatedResource);
}
// Create default system networks
createDefaultSystemNetworks(zone.getId());
return zone;
}
});
}
Aggregations