diff --git a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java b/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java index c9db4791431..1ba32622558 100644 --- a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java +++ b/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java @@ -96,9 +96,7 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { Project project= _projectService.getProject(projectId); //verify input parameters if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id", null); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + throw new InvalidParameterValueException("Unable to find project with specified id", null); } return _projectService.getProjectOwner(projectId).getId(); diff --git a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java index 625793d1a4f..f9c5deeabe6 100644 --- a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java +++ b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java @@ -12,6 +12,7 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.commands; +import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; @@ -40,6 +41,7 @@ import com.cloud.network.Network; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; import com.cloud.user.UserContext; +import com.cloud.utils.IdentityProxy; @Implementation(description="Acquires and associates a public IP to an account.", responseObject=IPAddressResponse.class) public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { @@ -158,8 +160,10 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); if (defaultGuestNetwork == null) { + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", getDomainId(), "domainId")); throw new InvalidParameterValueException("Unable to find a default Guest network for account " + - getAccountName() + " in domain id=" + getDomainId(), null); + getAccountName() + " in domain with specified id", idList); } else { return defaultGuestNetwork.getId(); } diff --git a/api/src/com/cloud/api/commands/CreateTemplateCmd.java b/api/src/com/cloud/api/commands/CreateTemplateCmd.java index 33683951253..d863c517f06 100755 --- a/api/src/com/cloud/api/commands/CreateTemplateCmd.java +++ b/api/src/com/cloud/api/commands/CreateTemplateCmd.java @@ -189,14 +189,14 @@ public class CreateTemplateCmd extends BaseAsyncCreateCmd { if (volume != null) { accountId = volume.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId, null); + throw new InvalidParameterValueException("Unable to find volume by id", null); } } else { Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId); if (snapshot != null) { accountId = snapshot.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId, null); + throw new InvalidParameterValueException("Unable to find snapshot by id", null); } } diff --git a/api/src/com/cloud/api/commands/ListProjectsCmd.java b/api/src/com/cloud/api/commands/ListProjectsCmd.java index 0b0162c9681..400e5939519 100644 --- a/api/src/com/cloud/api/commands/ListProjectsCmd.java +++ b/api/src/com/cloud/api/commands/ListProjectsCmd.java @@ -39,7 +39,7 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list projects by project ID") private Long id; @@ -49,13 +49,13 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="list projects by display text") private String displayText; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list projects by state") private String state; - + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "List projects by tags (key/value pairs)") private Map tags; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -71,12 +71,12 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { public String getDisplayText() { return displayText; } - + @Override public String getCommandName() { return s_name; } - + public Map getTags() { Map tagsMap = null; if (tags != null && !tags.isEmpty()) { @@ -88,7 +88,7 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { String key = services.get("key"); String value = services.get("value"); if (value == null) { - throw new InvalidParameterValueException("No value is passed in for key " + key); + throw new InvalidParameterValueException("No value is passed in for key " + key, null); } tagsMap.put(key, value); } @@ -113,7 +113,7 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { } response.setResponses(projectResponses); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java b/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java index f55eb24e0f1..cbc55dcda02 100644 --- a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java +++ b/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java @@ -99,7 +99,7 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { Host destinationHost = _resourceService.getHost(getHostId()); if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId(), null); + throw new InvalidParameterValueException("Unable to find the host to migrate the VM", null); } try{ UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); diff --git a/api/src/com/cloud/api/commands/MigrateVMCmd.java b/api/src/com/cloud/api/commands/MigrateVMCmd.java index d63698cb904..abaff6dc4fe 100644 --- a/api/src/com/cloud/api/commands/MigrateVMCmd.java +++ b/api/src/com/cloud/api/commands/MigrateVMCmd.java @@ -115,14 +115,14 @@ public class MigrateVMCmd extends BaseAsyncCmd { UserVm userVm = _userVmService.getUserVm(getVirtualMachineId()); if (userVm == null) { - throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId(), null); + throw new InvalidParameterValueException("Unable to find VM by id", null); } Host destinationHost = null; if (getHostId() != null) { destinationHost = _resourceService.getHost(getHostId()); if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId(), null); + throw new InvalidParameterValueException("Unable to find the host to migrate the VM to", null); } UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); } diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 851d66431fa..7f7a7af8db2 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -205,7 +205,7 @@ public class ApiDBUtils { static { _ms = (ManagementServer) ComponentLocator.getComponent(ManagementServer.Name); - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); _asyncMgr = locator.getManager(AsyncJobManager.class); _securityGroupMgr = locator.getManager(SecurityGroupManager.class); _storageMgr = locator.getManager(StorageManager.class); @@ -287,20 +287,20 @@ public class ApiDBUtils { // into this utils class. return _ms.getMemoryOrCpuCapacityByHost(poolId, capacityType); } - + public static List getCapacityByClusterPodZone(Long zoneId, Long podId, Long clusterId){ - return _capacityDao.findByClusterPodZone(zoneId,podId,clusterId); + return _capacityDao.findByClusterPodZone(zoneId,podId,clusterId); } - + public static List findNonSharedStorageForClusterPodZone(Long zoneId, Long podId, Long clusterId){ - return _capacityDao.findNonSharedStorageForClusterPodZone(zoneId,podId,clusterId); + return _capacityDao.findNonSharedStorageForClusterPodZone(zoneId,podId,clusterId); } - + public static List getCapacityByPod(){ - return null; - + return null; + } - + public static Long getPodIdForVlan(long vlanDbId) { return _networkMgr.getPodIdForVlan(vlanDbId); } @@ -389,15 +389,15 @@ public class ApiDBUtils { public static StorageStats getSecondaryStorageStatistics(long id) { return _statsCollector.getStorageStats(id); } - + public static CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId, Long podId, Long zoneId){ - return _storageMgr.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId); + return _storageMgr.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId); } public static CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId){ - return _storageMgr.getSecondaryStorageUsedStats(hostId, zoneId); + return _storageMgr.getSecondaryStorageUsedStats(hostId, zoneId); } - + // /////////////////////////////////////////////////////////// // Dao methods // // /////////////////////////////////////////////////////////// @@ -441,7 +441,7 @@ public class ApiDBUtils { public static GuestOS findGuestOSByDisplayName(String displayName) { return _guestOSDao.listByDisplayName(displayName); } - + public static HostVO findHostById(Long hostId) { return _hostDao.findByIdIncludingRemoved(hostId); } @@ -507,15 +507,15 @@ public class ApiDBUtils { } public static VMTemplateVO findTemplateById(Long templateId) { - VMTemplateVO template = _templateDao.findByIdIncludingRemoved(templateId); - if(template != null) { - Map details = _templateDetailsDao.findDetails(templateId); - if(details != null && !details.isEmpty()) - template.setDetails(details); - } - return template; + VMTemplateVO template = _templateDao.findByIdIncludingRemoved(templateId); + if(template != null) { + Map details = _templateDetailsDao.findDetails(templateId); + if(details != null && !details.isEmpty()) + template.setDetails(details); + } + return template; } - + public static VMTemplateHostVO findTemplateHostRef(long templateId, long zoneId) { return findTemplateHostRef(templateId, zoneId, false); } @@ -529,12 +529,12 @@ public class ApiDBUtils { return _storageMgr.getTemplateHostRef(zoneId, templateId, readyOnly); } } - - + + public static VolumeHostVO findVolumeHostRef(long volumeId, long zoneId) { return _volumeHostDao.findVolumeByZone(volumeId, zoneId); } - + public static VMTemplateSwiftVO findTemplateSwiftRef(long templateId) { return _templateSwiftDao.findOneByTemplateId(templateId); } @@ -562,11 +562,11 @@ public class ApiDBUtils { public static Site2SiteVpnGatewayVO findVpnGatewayById(Long vpnGatewayId) { return _site2SiteVpnGatewayDao.findById(vpnGatewayId); } - + public static Site2SiteCustomerGatewayVO findCustomerGatewayById(Long customerGatewayId) { - return _site2SiteCustomerGatewayDao.findById(customerGatewayId); + return _site2SiteCustomerGatewayDao.findById(customerGatewayId); } - + public static List listUsersByAccount(long accountId) { return _userDao.listByAccount(accountId); } @@ -587,9 +587,9 @@ public class ApiDBUtils { public static HypervisorType getVolumeHyperType(long volumeId) { return _volumeDao.getHypervisorType(volumeId); } - + public static HypervisorType getHypervisorTypeFromFormat(ImageFormat format){ - return _storageMgr.getHypervisorTypeFromFormat(format); + return _storageMgr.getHypervisorTypeFromFormat(format); } public static List listTemplateHostBy(long templateId, Long zoneId, boolean readyOnly) { @@ -621,7 +621,7 @@ public class ApiDBUtils { // Check that the volume is valid VolumeVO volume = _volumeDao.findById(volumeId); if (volume == null) { - throw new InvalidParameterValueException("Please specify a valid volume ID."); + throw new InvalidParameterValueException("Please specify a valid volume ID.", null); } return _storageMgr.volumeOnSharedStoragePool(volume); @@ -690,13 +690,13 @@ public class ApiDBUtils { float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1); return cpuOverprovisioningFactor; } - + public static boolean isExtractionDisabled(){ - String disableExtractionString = _configDao.getValue(Config.DisableExtraction.toString()); + String disableExtractionString = _configDao.getValue(Config.DisableExtraction.toString()); boolean disableExtraction = (disableExtractionString == null) ? false : Boolean.parseBoolean(disableExtractionString); return disableExtraction; } - + public static SecurityGroup getSecurityGroup(String groupName, long ownerId) { return _securityGroupMgr.getSecurityGroup(groupName, ownerId); } @@ -704,77 +704,77 @@ public class ApiDBUtils { public static ConsoleProxyVO findConsoleProxy(long id) { return _consoleProxyDao.findById(id); } - + public static List findFirewallSourceCidrs(long id){ return _firewallCidrsDao.getSourceCidrs(id); } - + public static Hashtable listVmDetails(Hashtable vmData){ return _userVmDao.listVmDetails(vmData); } - + public static Account getProjectOwner(long projectId) { return _projectMgr.getProjectOwner(projectId); } - + public static Project findProjectByProjectAccountId(long projectAccountId) { return _projectMgr.findByProjectAccountId(projectAccountId); } - + public static Project findProjectById(long projectId) { return _projectMgr.getProject(projectId); } - + public static long getProjectOwnwerId(long projectId) { return _projectMgr.getProjectOwner(projectId).getId(); } - + public static Map getAccountDetails(long accountId) { - Map details = _accountDetailsDao.findDetails(accountId); - return details.isEmpty() ? null : details; + Map details = _accountDetailsDao.findDetails(accountId); + return details.isEmpty() ? null : details; } public static Map> listNetworkOfferingServices(long networkOfferingId) { return _networkMgr.getNetworkOfferingServiceProvidersMap(networkOfferingId); } - + public static List getElementServices(Provider provider) { - return _networkMgr.getElementServices(provider); + return _networkMgr.getElementServices(provider); } - + public static List getProvidersForService(Service service) { return _networkMgr.listSupportedNetworkServiceProviders(service.getName()); - } + } public static boolean canElementEnableIndividualServices(Provider serviceProvider) { return _networkMgr.canElementEnableIndividualServices(serviceProvider); } - + public static Pair getDomainNetworkDetails(long networkId) { - NetworkDomainVO map = _networkDomainDao.getDomainNetworkMapByNetworkId(networkId); - - boolean subdomainAccess = (map.isSubdomainAccess() != null) ? map.isSubdomainAccess() : _networkMgr.getAllowSubdomainAccessGlobal(); - - return new Pair(map.getDomainId(), subdomainAccess); + NetworkDomainVO map = _networkDomainDao.getDomainNetworkMapByNetworkId(networkId); + + boolean subdomainAccess = (map.isSubdomainAccess() != null) ? map.isSubdomainAccess() : _networkMgr.getAllowSubdomainAccessGlobal(); + + return new Pair(map.getDomainId(), subdomainAccess); } - + public static long countFreePublicIps() { - return _ipAddressDao.countFreePublicIPs(); + return _ipAddressDao.countFreePublicIPs(); } - + public static long findDefaultRouterServiceOffering() { ServiceOfferingVO serviceOffering = _serviceOfferingDao.findByName(ServiceOffering.routerDefaultOffUniqueName); return serviceOffering.getId(); } - + public static IpAddress findIpByAssociatedVmId(long vmId) { return _ipAddressDao.findByAssociatedVmId(vmId); } - + public static String getHaTag() { return _haMgr.getHaTag(); } - + public static String getUuid(String resourceId, TaggedResourceType resourceType) { return _taggedResourceService.getUuid(resourceId, resourceType); } @@ -782,19 +782,19 @@ public class ApiDBUtils { public static Map> listVpcOffServices(long vpcOffId) { return _vpcMgr.getVpcOffSvcProvidersMap(vpcOffId); } - + public static List listVpcNetworks(long vpcId) { return _networkMgr.listNetworksByVpc(vpcId); } - + public static boolean canUseForDeploy(Network network) { return _networkMgr.canUseForDeploy(network); } - + public static List listByResourceTypeAndId(TaggedResourceType type, long resourceId) { return _taggedResourceService.listByResourceTypeAndId(type, resourceId); } - + public static boolean isOfferingForVpc(NetworkOffering offering) { boolean vpcProvider = _configMgr.isOfferingForVpc(offering); return vpcProvider; diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 901a5dca539..de0b969006e 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -531,7 +531,7 @@ public class ApiDispatcher { case STRING: if ((paramObj != null) && paramObj.toString().length() > annotation.length()) { s_logger.error("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName()); - throw new InvalidParameterValueException("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName()); + throw new InvalidParameterValueException("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName(), null); } field.set(cmdObj, paramObj.toString()); break; diff --git a/server/src/com/cloud/async/AsyncJobManagerImpl.java b/server/src/com/cloud/async/AsyncJobManagerImpl.java index dcb744a3361..54e6718946c 100644 --- a/server/src/com/cloud/async/AsyncJobManagerImpl.java +++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Type; @@ -68,232 +68,232 @@ import com.cloud.utils.mgmt.JmxUtil; import com.cloud.utils.net.MacAddress; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; - -@Local(value={AsyncJobManager.class}) -public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListener { - public static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class.getName()); - private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds - - private static final int MAX_ONETIME_SCHEDULE_SIZE = 50; + +@Local(value={AsyncJobManager.class}) +public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListener { + public static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class.getName()); + private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds + + private static final int MAX_ONETIME_SCHEDULE_SIZE = 50; private static final int HEARTBEAT_INTERVAL = 2000; private static final int GC_INTERVAL = 10000; // 10 seconds - - private String _name; - - private AsyncJobExecutorContext _context; - private SyncQueueManager _queueMgr; + + private String _name; + + private AsyncJobExecutorContext _context; + private SyncQueueManager _queueMgr; private ClusterManager _clusterMgr; - private AccountManager _accountMgr; + private AccountManager _accountMgr; private AccountDao _accountDao; private AsyncJobDao _jobDao; private long _jobExpireSeconds = 86400; // 1 day private long _jobCancelThresholdSeconds = 3600; // 1 hour - private ApiDispatcher _dispatcher; - - private final ScheduledExecutorService _heartbeatScheduler = - Executors.newScheduledThreadPool(1, new NamedThreadFactory("AsyncJobMgr-Heartbeat")); - private ExecutorService _executor; - - @Override - public AsyncJobExecutorContext getExecutorContext() { - return _context; - } - - @Override - public AsyncJobVO getAsyncJob(long jobId) { - return _jobDao.findById(jobId); - } - - @Override - public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { - return _jobDao.findInstancePendingAsyncJob(instanceType, instanceId); + private ApiDispatcher _dispatcher; + + private final ScheduledExecutorService _heartbeatScheduler = + Executors.newScheduledThreadPool(1, new NamedThreadFactory("AsyncJobMgr-Heartbeat")); + private ExecutorService _executor; + + @Override + public AsyncJobExecutorContext getExecutorContext() { + return _context; } - + + @Override + public AsyncJobVO getAsyncJob(long jobId) { + return _jobDao.findById(jobId); + } + + @Override + public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { + return _jobDao.findInstancePendingAsyncJob(instanceType, instanceId); + } + @Override public List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId) { - return _jobDao.findInstancePendingAsyncJobs(instanceType, accountId); - } - - @Override - public long submitAsyncJob(AsyncJobVO job) { - return submitAsyncJob(job, false); - } + return _jobDao.findInstancePendingAsyncJobs(instanceType, accountId); + } - @Override @DB + @Override + public long submitAsyncJob(AsyncJobVO job) { + return submitAsyncJob(job, false); + } + + @Override @DB public long submitAsyncJob(AsyncJobVO job, boolean scheduleJobExecutionInContext) { - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - job.setInitMsid(getMsid()); - _jobDao.persist(job); - txt.commit(); + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + job.setInitMsid(getMsid()); + _jobDao.persist(job); + txt.commit(); - // no sync source originally - job.setSyncSource(null); - scheduleExecution(job, scheduleJobExecutionInContext); - if(s_logger.isDebugEnabled()) { + // no sync source originally + job.setSyncSource(null); + scheduleExecution(job, scheduleJobExecutionInContext); + if(s_logger.isDebugEnabled()) { s_logger.debug("submit async job-" + job.getId() + ", details: " + job.toString()); } - return job.getId(); - } catch(Exception e) { - txt.rollback(); - String errMsg = "Unable to schedule async job for command " + job.getCmd() + ", unexpected exception."; + return job.getId(); + } catch(Exception e) { + txt.rollback(); + String errMsg = "Unable to schedule async job for command " + job.getCmd() + ", unexpected exception."; s_logger.warn(errMsg, e); throw new CloudRuntimeException(errMsg); - } - } - - @Override @DB - public void completeAsyncJob(long jobId, int jobStatus, int resultCode, Object resultObject) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Complete async job-" + jobId + ", jobStatus: " + jobStatus + - ", resultCode: " + resultCode + ", result: " + resultObject); - } - - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job == null) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("job-" + jobId + " no longer exists, we just log completion info here. " + jobStatus + - ", resultCode: " + resultCode + ", result: " + resultObject); - } - - txt.rollback(); - return; - } + } + } - job.setCompleteMsid(getMsid()); - job.setStatus(jobStatus); - job.setResultCode(resultCode); + @Override @DB + public void completeAsyncJob(long jobId, int jobStatus, int resultCode, Object resultObject) { + if(s_logger.isDebugEnabled()) { + s_logger.debug("Complete async job-" + jobId + ", jobStatus: " + jobStatus + + ", resultCode: " + resultCode + ", result: " + resultObject); + } - // reset attached object - job.setInstanceType(null); - job.setInstanceId(null); + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job == null) { + if(s_logger.isDebugEnabled()) { + s_logger.debug("job-" + jobId + " no longer exists, we just log completion info here. " + jobStatus + + ", resultCode: " + resultCode + ", result: " + resultObject); + } - if (resultObject != null) { + txt.rollback(); + return; + } + + job.setCompleteMsid(getMsid()); + job.setStatus(jobStatus); + job.setResultCode(resultCode); + + // reset attached object + job.setInstanceType(null); + job.setInstanceId(null); + + if (resultObject != null) { job.setResult(ApiSerializerHelper.toSerializedStringOld(resultObject)); - } + } - job.setLastUpdated(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while completing async job-" + jobId, e); - txt.rollback(); - } - } + job.setLastUpdated(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while completing async job-" + jobId, e); + txt.rollback(); + } + } - @Override @DB - public void updateAsyncJobStatus(long jobId, int processStatus, Object resultObject) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Update async-job progress, job-" + jobId + ", processStatus: " + processStatus + - ", result: " + resultObject); - } - - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job == null) { - if(s_logger.isDebugEnabled()) { + @Override @DB + public void updateAsyncJobStatus(long jobId, int processStatus, Object resultObject) { + if(s_logger.isDebugEnabled()) { + s_logger.debug("Update async-job progress, job-" + jobId + ", processStatus: " + processStatus + + ", result: " + resultObject); + } + + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job == null) { + if(s_logger.isDebugEnabled()) { s_logger.debug("job-" + jobId + " no longer exists, we just log progress info here. progress status: " + processStatus); - } - - txt.rollback(); - return; - } - - job.setProcessStatus(processStatus); - if(resultObject != null) { + } + + txt.rollback(); + return; + } + + job.setProcessStatus(processStatus); + if(resultObject != null) { job.setResult(ApiSerializerHelper.toSerializedStringOld(resultObject)); - } - job.setLastUpdated(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while updating async job-" + jobId + " status: ", e); - txt.rollback(); - } - } + } + job.setLastUpdated(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while updating async job-" + jobId + " status: ", e); + txt.rollback(); + } + } - @Override @DB - public void updateAsyncJobAttachment(long jobId, String instanceType, Long instanceId) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Update async-job attachment, job-" + jobId + ", instanceType: " + instanceType + - ", instanceId: " + instanceId); - } - - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); + @Override @DB + public void updateAsyncJobAttachment(long jobId, String instanceType, Long instanceId) { + if(s_logger.isDebugEnabled()) { + s_logger.debug("Update async-job attachment, job-" + jobId + ", instanceType: " + instanceType + + ", instanceId: " + instanceId); + } - AsyncJobVO job = _jobDao.createForUpdate(); - //job.setInstanceType(instanceType); - job.setInstanceId(instanceId); - job.setLastUpdated(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while updating async job-" + jobId + " attachment: ", e); - txt.rollback(); - } - } + AsyncJobVO job = _jobDao.createForUpdate(); + //job.setInstanceType(instanceType); + job.setInstanceId(instanceId); + job.setLastUpdated(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); - @Override - public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId) { - // This method is re-entrant. If an API developer wants to synchronized on an object, e.g. the router, - // when executing business logic, they will call this method (actually a method in BaseAsyncCmd that calls this). - // This method will get called every time their business logic executes. The first time it exectues for a job - // there will be no sync source, but on subsequent execution there will be a sync souce. If this is the first - // time the job executes we queue the job, otherwise we just return so that the business logic can execute. + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while updating async job-" + jobId + " attachment: ", e); + txt.rollback(); + } + } + + @Override + public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId) { + // This method is re-entrant. If an API developer wants to synchronized on an object, e.g. the router, + // when executing business logic, they will call this method (actually a method in BaseAsyncCmd that calls this). + // This method will get called every time their business logic executes. The first time it exectues for a job + // there will be no sync source, but on subsequent execution there will be a sync souce. If this is the first + // time the job executes we queue the job, otherwise we just return so that the business logic can execute. if (job.getSyncSource() != null) { return; } - + if(s_logger.isDebugEnabled()) { s_logger.debug("Sync job-" + job.getId() + " execution on object " + syncObjType + "." + syncObjId); } - SyncQueueVO queue = null; + SyncQueueVO queue = null; - // to deal with temporary DB exceptions like DB deadlock/Lock-wait time out cased rollbacks - // we retry five times until we throw an exception - Random random = new Random(); + // to deal with temporary DB exceptions like DB deadlock/Lock-wait time out cased rollbacks + // we retry five times until we throw an exception + Random random = new Random(); - for(int i = 0; i < 5; i++) { - queue = _queueMgr.queue(syncObjType, syncObjId, "AsyncJob", job.getId()); - if(queue != null) { + for(int i = 0; i < 5; i++) { + queue = _queueMgr.queue(syncObjType, syncObjId, "AsyncJob", job.getId()); + if(queue != null) { break; } - try { - Thread.sleep(1000 + random.nextInt(5000)); - } catch (InterruptedException e) { - } - } + try { + Thread.sleep(1000 + random.nextInt(5000)); + } catch (InterruptedException e) { + } + } - if (queue == null) { + if (queue == null) { throw new CloudRuntimeException("Unable to insert queue item into database, DB is full?"); - } else { - throw new AsyncCommandQueued(queue, "job-" + job.getId() + " queued"); - } + } else { + throw new AsyncCommandQueued(queue, "job-" + job.getId() + " queued"); + } } - + @Override public AsyncJob queryAsyncJobResult(QueryAsyncJobResultCmd cmd) { Account caller = UserContext.current().getCaller(); AsyncJobVO job = _jobDao.findById(cmd.getId()); if (job == null) { - throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId()); + throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId(), null); } - + User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId()); Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId()); - + //check permissions if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { //regular user can see only jobs he owns @@ -303,66 +303,66 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { _accountMgr.checkAccess(caller, null, true, jobOwner); } - + //poll the job queryAsyncJobResult(cmd.getId()); return _jobDao.findById(cmd.getId()); } - @Override @DB - public AsyncJobResult queryAsyncJobResult(long jobId) { - if(s_logger.isTraceEnabled()) { + @Override @DB + public AsyncJobResult queryAsyncJobResult(long jobId) { + if(s_logger.isTraceEnabled()) { s_logger.trace("Query async-job status, job-" + jobId); - } - - Transaction txt = Transaction.currentTxn(); - AsyncJobResult jobResult = new AsyncJobResult(jobId); - - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job != null) { - jobResult.setCmdOriginator(job.getCmdOriginator()); - jobResult.setJobStatus(job.getStatus()); - jobResult.setProcessStatus(job.getProcessStatus()); - jobResult.setResult(job.getResult()); - jobResult.setResultCode(job.getResultCode()); - jobResult.setUuid(job.getUuid()); - - if(job.getStatus() == AsyncJobResult.STATUS_SUCCEEDED || - job.getStatus() == AsyncJobResult.STATUS_FAILED) { - - if(s_logger.isDebugEnabled()) { + } + + Transaction txt = Transaction.currentTxn(); + AsyncJobResult jobResult = new AsyncJobResult(jobId); + + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job != null) { + jobResult.setCmdOriginator(job.getCmdOriginator()); + jobResult.setJobStatus(job.getStatus()); + jobResult.setProcessStatus(job.getProcessStatus()); + jobResult.setResult(job.getResult()); + jobResult.setResultCode(job.getResultCode()); + jobResult.setUuid(job.getUuid()); + + if(job.getStatus() == AsyncJobResult.STATUS_SUCCEEDED || + job.getStatus() == AsyncJobResult.STATUS_FAILED) { + + if(s_logger.isDebugEnabled()) { s_logger.debug("Async job-" + jobId + " completed"); - } - } else { - job.setLastPolled(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); - } - } else { - if(s_logger.isDebugEnabled()) { + } + } else { + job.setLastPolled(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); + } + } else { + if(s_logger.isDebugEnabled()) { s_logger.debug("Async job-" + jobId + " does not exist, invalid job id?"); - } - - jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); - jobResult.setResult("job-" + jobId + " does not exist"); - } - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while querying async job-" + jobId + " status: ", e); - - jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); - jobResult.setResult("Exception: " + e.toString()); - txt.rollback(); - } - - if(s_logger.isTraceEnabled()) { + } + + jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); + jobResult.setResult("job-" + jobId + " does not exist"); + } + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while querying async job-" + jobId + " status: ", e); + + jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); + jobResult.setResult("Exception: " + e.toString()); + txt.rollback(); + } + + if(s_logger.isTraceEnabled()) { s_logger.trace("Job status: " + jobResult.toString()); - } - - return jobResult; + } + + return jobResult; } - + private void scheduleExecution(final AsyncJobVO job) { scheduleExecution(job, false); } @@ -372,7 +372,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if (executeInContext) { runnable.run(); } else { - _executor.submit(runnable); + _executor.submit(runnable); } } @@ -382,66 +382,66 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe public void run() { try { long jobId = 0; - + try { - JmxUtil.registerMBean("AsyncJobManager", "Active Job " + job.getId(), new AsyncJobMBeanImpl(job)); + JmxUtil.registerMBean("AsyncJobManager", "Active Job " + job.getId(), new AsyncJobMBeanImpl(job)); } catch(Exception e) { - s_logger.warn("Unable to register active job " + job.getId() + " to JMX monitoring due to exception " + ExceptionUtil.toString(e)); + s_logger.warn("Unable to register active job " + job.getId() + " to JMX monitoring due to exception " + ExceptionUtil.toString(e)); } - + BaseAsyncCmd cmdObj = null; Transaction txn = Transaction.open(Transaction.CLOUD_DB); try { jobId = job.getId(); NDC.push("job-" + jobId); - + if(s_logger.isDebugEnabled()) { s_logger.debug("Executing " + job.getCmd() + " for job-" + jobId); } - + Class cmdClass = Class.forName(job.getCmd()); cmdObj = (BaseAsyncCmd)cmdClass.newInstance(); cmdObj.setJob(job); - + Type mapType = new TypeToken>() {}.getType(); Gson gson = ApiGsonHelper.getBuilder().create(); Map params = gson.fromJson(job.getCmdInfo(), mapType); - + // whenever we deserialize, the UserContext needs to be updated String userIdStr = params.get("ctxUserId"); String acctIdStr = params.get("ctxAccountId"); Long userId = null; Account accountObject = null; - + if (userIdStr != null) { userId = Long.parseLong(userIdStr); } - + if (acctIdStr != null) { accountObject = _accountDao.findById(Long.parseLong(acctIdStr)); } - + UserContext.registerContext(userId, accountObject, null, false); try { // dispatch could ultimately queue the job _dispatcher.dispatch(cmdObj, params); - + // serialize this to the async job table completeAsyncJob(jobId, AsyncJobResult.STATUS_SUCCEEDED, 0, cmdObj.getResponseObject()); } finally { UserContext.unregisterContext(); } - + // commands might need to be queued as part of synchronization here, so they just have to be re-dispatched from the queue mechanism... if (job.getSyncSource() != null) { _queueMgr.purgeItem(job.getSyncSource().getId()); checkQueue(job.getSyncSource().getQueueId()); } - + if (s_logger.isDebugEnabled()) { s_logger.debug("Done executing " + job.getCmd() + " for job-" + jobId); } - + } catch(Throwable e) { if (e instanceof AsyncCommandQueued) { if (s_logger.isDebugEnabled()) { @@ -459,16 +459,16 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe errorMsg = sApiEx.getDescription(); errorCode = sApiEx.getErrorCode(); } - + ExceptionResponse response = new ExceptionResponse(); response.setErrorCode(errorCode); response.setErrorText(errorMsg); response.setResponseName((cmdObj == null) ? "unknowncommandresponse" : cmdObj.getCommandName()); - + // FIXME: setting resultCode to BaseCmd.INTERNAL_ERROR is not right, usually executors have their exception handling // and we need to preserve that as much as possible here completeAsyncJob(jobId, AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, response); - + // need to clean up any queue that happened as part of the dispatching and move on to the next item in the queue try { if (job.getSyncSource() != null) { @@ -480,13 +480,13 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } } finally { - + try { - JmxUtil.unregisterMBean("AsyncJobManager", "Active Job " + job.getId()); + JmxUtil.unregisterMBean("AsyncJobManager", "Active Job " + job.getId()); } catch(Exception e) { - s_logger.warn("Unable to unregister active job " + job.getId() + " from JMX monitoring"); + s_logger.warn("Unable to unregister active job " + job.getId() + " from JMX monitoring"); } - + StackMaid.current().exitCleanup(); txn.close(); NDC.pop(); @@ -500,7 +500,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } }; } - + private void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSession) { AsyncJobVO job = _jobDao.findById(item.getContentId()); if (job != null) { @@ -510,17 +510,17 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe job.setFromPreviousSession(fromPreviousSession); job.setSyncSource(item); - + job.setCompleteMsid(getMsid()); _jobDao.update(job.getId(), job); - + try { - scheduleExecution(job); - } catch(RejectedExecutionException e) { - s_logger.warn("Execution for job-" + job.getId() + " is rejected, return it to the queue for next turn"); - _queueMgr.returnItem(item.getId()); - } - + scheduleExecution(job); + } catch(RejectedExecutionException e) { + s_logger.warn("Execution for job-" + job.getId() + " is rejected, return it to the queue for next turn"); + _queueMgr.returnItem(item.getId()); + } + } else { if(s_logger.isDebugEnabled()) { s_logger.debug("Unable to find related job for queue item: " + item.toString()); @@ -530,281 +530,281 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } - @Override - public void releaseSyncSource(AsyncJobExecutor executor) { - if(executor.getSyncSource() != null) { - if(s_logger.isDebugEnabled()) { - s_logger.debug("Release sync source for job-" + executor.getJob().getId() + " sync source: " - + executor.getSyncSource().getContentType() + "-" - + executor.getSyncSource().getContentId()); - } - - _queueMgr.purgeItem(executor.getSyncSource().getId()); - checkQueue(executor.getSyncSource().getQueueId()); - } - } - - private void checkQueue(long queueId) { - while(true) { - try { - SyncQueueItemVO item = _queueMgr.dequeueFromOne(queueId, getMsid()); - if(item != null) { - if(s_logger.isDebugEnabled()) { + @Override + public void releaseSyncSource(AsyncJobExecutor executor) { + if(executor.getSyncSource() != null) { + if(s_logger.isDebugEnabled()) { + s_logger.debug("Release sync source for job-" + executor.getJob().getId() + " sync source: " + + executor.getSyncSource().getContentType() + "-" + + executor.getSyncSource().getContentId()); + } + + _queueMgr.purgeItem(executor.getSyncSource().getId()); + checkQueue(executor.getSyncSource().getQueueId()); + } + } + + private void checkQueue(long queueId) { + while(true) { + try { + SyncQueueItemVO item = _queueMgr.dequeueFromOne(queueId, getMsid()); + if(item != null) { + if(s_logger.isDebugEnabled()) { s_logger.debug("Executing sync queue item: " + item.toString()); - } - - executeQueueItem(item, false); - } else { - break; - } - } catch(Throwable e) { - s_logger.error("Unexpected exception when kicking sync queue-" + queueId, e); - break; - } - } - } - - private Runnable getHeartbeatTask() { - return new Runnable() { - @Override - public void run() { - try { - List l = _queueMgr.dequeueFromAny(getMsid(), MAX_ONETIME_SCHEDULE_SIZE); - if(l != null && l.size() > 0) { - for(SyncQueueItemVO item: l) { - if(s_logger.isDebugEnabled()) { + } + + executeQueueItem(item, false); + } else { + break; + } + } catch(Throwable e) { + s_logger.error("Unexpected exception when kicking sync queue-" + queueId, e); + break; + } + } + } + + private Runnable getHeartbeatTask() { + return new Runnable() { + @Override + public void run() { + try { + List l = _queueMgr.dequeueFromAny(getMsid(), MAX_ONETIME_SCHEDULE_SIZE); + if(l != null && l.size() > 0) { + for(SyncQueueItemVO item: l) { + if(s_logger.isDebugEnabled()) { s_logger.debug("Execute sync-queue item: " + item.toString()); } - executeQueueItem(item, false); - } - } - } catch(Throwable e) { - s_logger.error("Unexpected exception when trying to execute queue item, ", e); - } finally { - StackMaid.current().exitCleanup(); - } - } - }; - } - - @DB - private Runnable getGCTask() { - return new Runnable() { - @Override + executeQueueItem(item, false); + } + } + } catch(Throwable e) { + s_logger.error("Unexpected exception when trying to execute queue item, ", e); + } finally { + StackMaid.current().exitCleanup(); + } + } + }; + } + + @DB + private Runnable getGCTask() { + return new Runnable() { + @Override public void run() { - GlobalLock scanLock = GlobalLock.getInternLock("AsyncJobManagerGC"); - try { - if(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { - try { - reallyRun(); - } finally { - scanLock.unlock(); - } - } - } finally { - scanLock.releaseRef(); - } - } - - private void reallyRun() { - try { - s_logger.trace("Begin cleanup expired async-jobs"); - - Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - _jobExpireSeconds*1000); - - // limit to 100 jobs per turn, this gives cleanup throughput as 600 jobs per minute - // hopefully this will be fast enough to balance potential growth of job table - List l = _jobDao.getExpiredJobs(cutTime, 100); - if(l != null && l.size() > 0) { - for(AsyncJobVO job : l) { - _jobDao.expunge(job.getId()); - } - } - - // forcely cancel blocking queue items if they've been staying there for too long - List blockItems = _queueMgr.getBlockedQueueItems(_jobCancelThresholdSeconds*1000, false); - if(blockItems != null && blockItems.size() > 0) { - for(SyncQueueItemVO item : blockItems) { - if(item.getContentType().equalsIgnoreCase("AsyncJob")) { + GlobalLock scanLock = GlobalLock.getInternLock("AsyncJobManagerGC"); + try { + if(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { + try { + reallyRun(); + } finally { + scanLock.unlock(); + } + } + } finally { + scanLock.releaseRef(); + } + } + + private void reallyRun() { + try { + s_logger.trace("Begin cleanup expired async-jobs"); + + Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - _jobExpireSeconds*1000); + + // limit to 100 jobs per turn, this gives cleanup throughput as 600 jobs per minute + // hopefully this will be fast enough to balance potential growth of job table + List l = _jobDao.getExpiredJobs(cutTime, 100); + if(l != null && l.size() > 0) { + for(AsyncJobVO job : l) { + _jobDao.expunge(job.getId()); + } + } + + // forcely cancel blocking queue items if they've been staying there for too long + List blockItems = _queueMgr.getBlockedQueueItems(_jobCancelThresholdSeconds*1000, false); + if(blockItems != null && blockItems.size() > 0) { + for(SyncQueueItemVO item : blockItems) { + if(item.getContentType().equalsIgnoreCase("AsyncJob")) { completeAsyncJob(item.getContentId(), AsyncJobResult.STATUS_FAILED, 0, getResetResultResponse("Job is cancelled as it has been blocking others for too long")); } - - // purge the item and resume queue processing - _queueMgr.purgeItem(item.getId()); - } - } - - s_logger.trace("End cleanup expired async-jobs"); - } catch(Throwable e) { - s_logger.error("Unexpected exception when trying to execute queue item, ", e); - } finally { - StackMaid.current().exitCleanup(); - } - } - }; - } - - private long getMsid() { - if(_clusterMgr != null) { + + // purge the item and resume queue processing + _queueMgr.purgeItem(item.getId()); + } + } + + s_logger.trace("End cleanup expired async-jobs"); + } catch(Throwable e) { + s_logger.error("Unexpected exception when trying to execute queue item, ", e); + } finally { + StackMaid.current().exitCleanup(); + } + } + }; + } + + private long getMsid() { + if(_clusterMgr != null) { return _clusterMgr.getManagementNodeId(); - } - - return MacAddress.getMacAddress().toLong(); - } - - private void cleanupPendingJobs(List l) { - if(l != null && l.size() > 0) { - for(SyncQueueItemVO item: l) { - if(s_logger.isInfoEnabled()) { + } + + return MacAddress.getMacAddress().toLong(); + } + + private void cleanupPendingJobs(List l) { + if(l != null && l.size() > 0) { + for(SyncQueueItemVO item: l) { + if(s_logger.isInfoEnabled()) { s_logger.info("Discard left-over queue item: " + item.toString()); } - - String contentType = item.getContentType(); - if(contentType != null && contentType.equals("AsyncJob")) { - Long jobId = item.getContentId(); - if(jobId != null) { - s_logger.warn("Mark job as failed as its correspoding queue-item has been discarded. job id: " + jobId); - completeAsyncJob(jobId, AsyncJobResult.STATUS_FAILED, 0, getResetResultResponse("Execution was cancelled because of server shutdown")); - } - } - _queueMgr.purgeItem(item.getId()); - } - } - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - - ComponentLocator locator = ComponentLocator.getCurrentLocator(); - - ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); - if (configDao == null) { - throw new ConfigurationException("Unable to get the configuration dao."); - } - int expireMinutes = NumbersUtil.parseInt( - configDao.getValue(Config.JobExpireMinutes.key()), 24*60); - _jobExpireSeconds = (long)expireMinutes*60; - - _jobCancelThresholdSeconds = NumbersUtil.parseInt( - configDao.getValue(Config.JobCancelThresholdMinutes.key()), 60); - _jobCancelThresholdSeconds *= 60; + String contentType = item.getContentType(); + if(contentType != null && contentType.equals("AsyncJob")) { + Long jobId = item.getContentId(); + if(jobId != null) { + s_logger.warn("Mark job as failed as its correspoding queue-item has been discarded. job id: " + jobId); + completeAsyncJob(jobId, AsyncJobResult.STATUS_FAILED, 0, getResetResultResponse("Execution was cancelled because of server shutdown")); + } + } + _queueMgr.purgeItem(item.getId()); + } + } + } - _accountDao = locator.getDao(AccountDao.class); - if (_accountDao == null) { + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + + ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); + if (configDao == null) { + throw new ConfigurationException("Unable to get the configuration dao."); + } + + int expireMinutes = NumbersUtil.parseInt( + configDao.getValue(Config.JobExpireMinutes.key()), 24*60); + _jobExpireSeconds = (long)expireMinutes*60; + + _jobCancelThresholdSeconds = NumbersUtil.parseInt( + configDao.getValue(Config.JobCancelThresholdMinutes.key()), 60); + _jobCancelThresholdSeconds *= 60; + + _accountDao = locator.getDao(AccountDao.class); + if (_accountDao == null) { throw new ConfigurationException("Unable to get " + AccountDao.class.getName()); - } - _jobDao = locator.getDao(AsyncJobDao.class); - if (_jobDao == null) { - throw new ConfigurationException("Unable to get " - + AsyncJobDao.class.getName()); - } - - _context = locator.getManager(AsyncJobExecutorContext.class); - if (_context == null) { - throw new ConfigurationException("Unable to get " - + AsyncJobExecutorContext.class.getName()); - } - - _queueMgr = locator.getManager(SyncQueueManager.class); - if(_queueMgr == null) { - throw new ConfigurationException("Unable to get " - + SyncQueueManager.class.getName()); - } - - _clusterMgr = locator.getManager(ClusterManager.class); - - _accountMgr = locator.getManager(AccountManager.class); + } + _jobDao = locator.getDao(AsyncJobDao.class); + if (_jobDao == null) { + throw new ConfigurationException("Unable to get " + + AsyncJobDao.class.getName()); + } - _dispatcher = ApiDispatcher.getInstance(); - + _context = locator.getManager(AsyncJobExecutorContext.class); + if (_context == null) { + throw new ConfigurationException("Unable to get " + + AsyncJobExecutorContext.class.getName()); + } + + _queueMgr = locator.getManager(SyncQueueManager.class); + if(_queueMgr == null) { + throw new ConfigurationException("Unable to get " + + SyncQueueManager.class.getName()); + } + + _clusterMgr = locator.getManager(ClusterManager.class); + + _accountMgr = locator.getManager(AccountManager.class); + + _dispatcher = ApiDispatcher.getInstance(); + + + try { + final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); + final Properties dbProps = new Properties(); + dbProps.load(new FileInputStream(dbPropsFile)); - try { - final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); - final Properties dbProps = new Properties(); - dbProps.load(new FileInputStream(dbPropsFile)); - final int cloudMaxActive = Integer.parseInt(dbProps.getProperty("db.cloud.maxActive")); - + int poolSize = (cloudMaxActive * 2) / 3; - + s_logger.info("Start AsyncJobManager thread pool in size " + poolSize); _executor = Executors.newFixedThreadPool(poolSize, new NamedThreadFactory("Job-Executor")); - } catch (final Exception e) { - throw new ConfigurationException("Unable to load db.properties to configure AsyncJobManagerImpl"); - } - - return true; + } catch (final Exception e) { + throw new ConfigurationException("Unable to load db.properties to configure AsyncJobManagerImpl"); + } + + return true; } - + @Override - public void onManagementNodeJoined(List nodeList, long selfNodeId) { + public void onManagementNodeJoined(List nodeList, long selfNodeId) { } - + @Override - public void onManagementNodeLeft(List nodeList, long selfNodeId) { - for(ManagementServerHostVO msHost : nodeList) { - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - txn.start(); - List items = _queueMgr.getActiveQueueItems(msHost.getId(), true); - cleanupPendingJobs(items); - _queueMgr.resetQueueProcess(msHost.getId()); - _jobDao.resetJobProcess(msHost.getId(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart")); - txn.commit(); - } catch(Throwable e) { - s_logger.warn("Unexpected exception ", e); - txn.rollback(); - } finally { - txn.close(); - } - } + public void onManagementNodeLeft(List nodeList, long selfNodeId) { + for(ManagementServerHostVO msHost : nodeList) { + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + txn.start(); + List items = _queueMgr.getActiveQueueItems(msHost.getId(), true); + cleanupPendingJobs(items); + _queueMgr.resetQueueProcess(msHost.getId()); + _jobDao.resetJobProcess(msHost.getId(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart")); + txn.commit(); + } catch(Throwable e) { + s_logger.warn("Unexpected exception ", e); + txn.rollback(); + } finally { + txn.close(); + } + } } - + + @Override + public void onManagementNodeIsolated() { + } + @Override - public void onManagementNodeIsolated() { - } - - @Override public boolean start() { - try { - List l = _queueMgr.getActiveQueueItems(getMsid(), false); - cleanupPendingJobs(l); - _queueMgr.resetQueueProcess(getMsid()); - _jobDao.resetJobProcess(getMsid(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart")); - } catch(Throwable e) { - s_logger.error("Unexpected exception " + e.getMessage(), e); - } - - _heartbeatScheduler.scheduleAtFixedRate(getHeartbeatTask(), HEARTBEAT_INTERVAL, - HEARTBEAT_INTERVAL, TimeUnit.MILLISECONDS); - _heartbeatScheduler.scheduleAtFixedRate(getGCTask(), GC_INTERVAL, - GC_INTERVAL, TimeUnit.MILLISECONDS); - - return true; + try { + List l = _queueMgr.getActiveQueueItems(getMsid(), false); + cleanupPendingJobs(l); + _queueMgr.resetQueueProcess(getMsid()); + _jobDao.resetJobProcess(getMsid(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart")); + } catch(Throwable e) { + s_logger.error("Unexpected exception " + e.getMessage(), e); + } + + _heartbeatScheduler.scheduleAtFixedRate(getHeartbeatTask(), HEARTBEAT_INTERVAL, + HEARTBEAT_INTERVAL, TimeUnit.MILLISECONDS); + _heartbeatScheduler.scheduleAtFixedRate(getGCTask(), GC_INTERVAL, + GC_INTERVAL, TimeUnit.MILLISECONDS); + + return true; } - + private static ExceptionResponse getResetResultResponse(String errorMessage) { - ExceptionResponse resultObject = new ExceptionResponse(); - resultObject.setErrorCode(BaseCmd.INTERNAL_ERROR); - resultObject.setErrorText(errorMessage); - return resultObject; + ExceptionResponse resultObject = new ExceptionResponse(); + resultObject.setErrorCode(BaseCmd.INTERNAL_ERROR); + resultObject.setErrorText(errorMessage); + return resultObject; } - + private static String getSerializedErrorMessage(String errorMessage) { return ApiSerializerHelper.toSerializedStringOld(getResetResultResponse(errorMessage)); - } - - @Override - public boolean stop() { - _heartbeatScheduler.shutdown(); - _executor.shutdown(); - return true; - } - - @Override - public String getName() { - return _name; - } -} + } + + @Override + public boolean stop() { + _heartbeatScheduler.shutdown(); + _executor.shutdown(); + return true; + } + + @Override + public String getName() { + return _name; + } +} diff --git a/server/src/com/cloud/baremetal/BareMetalPingServiceImpl.java b/server/src/com/cloud/baremetal/BareMetalPingServiceImpl.java index 58ece593548..894c493baff 100755 --- a/server/src/com/cloud/baremetal/BareMetalPingServiceImpl.java +++ b/server/src/com/cloud/baremetal/BareMetalPingServiceImpl.java @@ -12,7 +12,7 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.baremetal; -import java.net.URI; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -27,7 +27,6 @@ import com.cloud.agent.api.baremetal.PreparePxeServerCommand; import com.cloud.agent.api.baremetal.prepareCreateTemplateCommand; import com.cloud.baremetal.PxeServerManager.PxeServerType; import com.cloud.dc.DataCenterVO; -import com.cloud.dc.HostPodVO; import com.cloud.deploy.DeployDestination; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; @@ -35,6 +34,7 @@ import com.cloud.host.HostVO; import com.cloud.resource.ResourceManager; import com.cloud.resource.ServerResource; import com.cloud.uservm.UserVm; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -45,119 +45,120 @@ import com.cloud.vm.VirtualMachineProfile; @Local(value=PxeServerService.class) public class BareMetalPingServiceImpl extends BareMetalPxeServiceBase implements PxeServerService { - private static final Logger s_logger = Logger.getLogger(BareMetalPingServiceImpl.class); - @Inject ResourceManager _resourceMgr; - - @Override - public Host addPxeServer(PxeServerProfile profile) { - Long zoneId = profile.getZoneId(); - Long podId = profile.getPodId(); + private static final Logger s_logger = Logger.getLogger(BareMetalPingServiceImpl.class); + @Inject ResourceManager _resourceMgr; - DataCenterVO zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } - - List pxeServers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, podId, zoneId); - if (pxeServers.size() != 0) { - InvalidParameterValueException ex = new InvalidParameterValueException("Already had a PXE server in Pod with specified podId and zone with specified zoneId"); - ex.addProxyObject("pod", podId, "podId"); - ex.addProxyObject(zone, zoneId, "zoneId"); - } - - - String ipAddress = profile.getUrl(); - String username = profile.getUsername(); - String password = profile.getPassword(); - - ServerResource resource = null; - Map params = new HashMap(); - params.put("type", PxeServerType.PING.getName()); - params.put("zone", Long.toString(zoneId)); - params.put("pod", podId.toString()); - params.put("ip", ipAddress); - params.put("username", username); - params.put("password", password); - if (profile.getType().equalsIgnoreCase(PxeServerType.PING.getName())) { - String storageServerIp = profile.getPingStorageServerIp(); - if (storageServerIp == null) { - throw new InvalidParameterValueException("No IP for storage server specified"); - } - String pingDir = profile.getPingDir(); - if (pingDir == null) { - throw new InvalidParameterValueException("No direcotry for storage server specified"); - } - String tftpDir = profile.getTftpDir(); - if (tftpDir == null) { - throw new InvalidParameterValueException("No TFTP directory specified"); - } - String cifsUsername = profile.getPingCifsUserName(); - if (cifsUsername == null || cifsUsername.equalsIgnoreCase("")) { - cifsUsername = "xxx"; - } - String cifsPassword = profile.getPingCifspassword(); - if (cifsPassword == null || cifsPassword.equalsIgnoreCase("")) { - cifsPassword = "xxx"; - } - String guid = getPxeServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), PxeServerType.PING.getName(), ipAddress); - - params.put("storageServer", storageServerIp); - params.put("pingDir", pingDir); - params.put("tftpDir", tftpDir); - params.put("cifsUserName", cifsUsername); - params.put("cifsPassword", cifsPassword); - params.put("guid", guid); - - resource = new PingPxeServerResource(); - try { - resource.configure("PING PXE resource", params); - } catch (Exception e) { - s_logger.debug(e); - throw new CloudRuntimeException(e.getMessage()); - } - - } else { - throw new CloudRuntimeException("Unsupport PXE server type:" + profile.getType()); - } - - Host pxeServer = _resourceMgr.addHost(zoneId, resource, Host.Type.PxeServer, params); - if (pxeServer == null) { - throw new CloudRuntimeException("Cannot add PXE server as a host"); - } - - return pxeServer; - } - - - @Override - public boolean prepare(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context, Long pxeServerId) { - List nics = profile.getNics(); - if (nics.size() == 0) { - throw new CloudRuntimeException("Cannot do PXE start without nic"); - } - - NicProfile pxeNic = nics.get(0); - String mac = pxeNic.getMacAddress(); - String ip = pxeNic.getIp4Address(); - String gateway = pxeNic.getGateway(); - String mask = pxeNic.getNetmask(); - String dns = pxeNic.getDns1(); - if (dns == null) { - dns = pxeNic.getDns2(); - } + @Override + public Host addPxeServer(PxeServerProfile profile) { + Long zoneId = profile.getZoneId(); + Long podId = profile.getPodId(); - try { - String tpl = profile.getTemplate().getUrl(); - assert tpl != null : "How can a null template get here!!!"; - PreparePxeServerCommand cmd = new PreparePxeServerCommand(ip, mac, mask, gateway, dns, tpl, - profile.getVirtualMachine().getInstanceName(), dest.getHost().getName()); - PreparePxeServerAnswer ans = (PreparePxeServerAnswer) _agentMgr.send(pxeServerId, cmd); - return ans.getResult(); - } catch (Exception e) { - s_logger.warn("Cannot prepare PXE server", e); - return false; - } - } + DataCenterVO zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new InvalidParameterValueException("Could not find zone by ID: ", null); + } + + List pxeServers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, podId, zoneId); + if (pxeServers.size() != 0) { + List idList = new ArrayList(); + idList.add(new IdentityProxy("pod", podId, "podId")); + idList.add(new IdentityProxy(zone, zoneId, "zoneId")); + InvalidParameterValueException ex = new InvalidParameterValueException("Already had a PXE server in Pod with specified podId and zone with specified zoneId", idList); + } + + + String ipAddress = profile.getUrl(); + String username = profile.getUsername(); + String password = profile.getPassword(); + + ServerResource resource = null; + Map params = new HashMap(); + params.put("type", PxeServerType.PING.getName()); + params.put("zone", Long.toString(zoneId)); + params.put("pod", podId.toString()); + params.put("ip", ipAddress); + params.put("username", username); + params.put("password", password); + if (profile.getType().equalsIgnoreCase(PxeServerType.PING.getName())) { + String storageServerIp = profile.getPingStorageServerIp(); + if (storageServerIp == null) { + throw new InvalidParameterValueException("No IP for storage server specified", null); + } + String pingDir = profile.getPingDir(); + if (pingDir == null) { + throw new InvalidParameterValueException("No direcotry for storage server specified", null); + } + String tftpDir = profile.getTftpDir(); + if (tftpDir == null) { + throw new InvalidParameterValueException("No TFTP directory specified", null); + } + String cifsUsername = profile.getPingCifsUserName(); + if (cifsUsername == null || cifsUsername.equalsIgnoreCase("")) { + cifsUsername = "xxx"; + } + String cifsPassword = profile.getPingCifspassword(); + if (cifsPassword == null || cifsPassword.equalsIgnoreCase("")) { + cifsPassword = "xxx"; + } + String guid = getPxeServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), PxeServerType.PING.getName(), ipAddress); + + params.put("storageServer", storageServerIp); + params.put("pingDir", pingDir); + params.put("tftpDir", tftpDir); + params.put("cifsUserName", cifsUsername); + params.put("cifsPassword", cifsPassword); + params.put("guid", guid); + + resource = new PingPxeServerResource(); + try { + resource.configure("PING PXE resource", params); + } catch (Exception e) { + s_logger.debug(e); + throw new CloudRuntimeException(e.getMessage()); + } + + } else { + throw new CloudRuntimeException("Unsupport PXE server type:" + profile.getType()); + } + + Host pxeServer = _resourceMgr.addHost(zoneId, resource, Host.Type.PxeServer, params); + if (pxeServer == null) { + throw new CloudRuntimeException("Cannot add PXE server as a host"); + } + + return pxeServer; + } + + + @Override + public boolean prepare(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context, Long pxeServerId) { + List nics = profile.getNics(); + if (nics.size() == 0) { + throw new CloudRuntimeException("Cannot do PXE start without nic"); + } + + NicProfile pxeNic = nics.get(0); + String mac = pxeNic.getMacAddress(); + String ip = pxeNic.getIp4Address(); + String gateway = pxeNic.getGateway(); + String mask = pxeNic.getNetmask(); + String dns = pxeNic.getDns1(); + if (dns == null) { + dns = pxeNic.getDns2(); + } + + try { + String tpl = profile.getTemplate().getUrl(); + assert tpl != null : "How can a null template get here!!!"; + PreparePxeServerCommand cmd = new PreparePxeServerCommand(ip, mac, mask, gateway, dns, tpl, + profile.getVirtualMachine().getInstanceName(), dest.getHost().getName()); + PreparePxeServerAnswer ans = (PreparePxeServerAnswer) _agentMgr.send(pxeServerId, cmd); + return ans.getResult(); + } catch (Exception e) { + s_logger.warn("Cannot prepare PXE server", e); + return false; + } + } @Override @@ -166,7 +167,7 @@ public class BareMetalPingServiceImpl extends BareMetalPxeServiceBase implements if (nics.size() != 1) { throw new CloudRuntimeException("Wrong nic number " + nics.size() + " of vm " + vm.getId()); } - + /* use last host id when VM stopped */ Long hostId = (vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId()); HostVO host = _hostDao.findById(hostId); @@ -180,7 +181,7 @@ public class BareMetalPingServiceImpl extends BareMetalPxeServiceBase implements if (dns == null) { dns = dc.getDns2(); } - + try { prepareCreateTemplateCommand cmd = new prepareCreateTemplateCommand(ip, mac, mask, gateway, dns, templateUrl); Answer ans = _agentMgr.send(pxeServerId, cmd); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index d13afef5712..254fca6886f 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -144,6 +144,7 @@ import com.cloud.user.ResourceLimitService; import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.StringUtils; import com.cloud.utils.component.Adapters; @@ -314,7 +315,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (validationMsg != null) { s_logger.error("Invalid configuration option, name: " + name + ", value:" + value); - throw new InvalidParameterValueException(validationMsg); + throw new InvalidParameterValueException(validationMsg, null); } // Execute all updates in a single transaction @@ -422,11 +423,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String name = cmd.getCfgName(); String value = cmd.getValue(); UserContext.current().setEventDetails(" Name: " + name + " New Value: " + (((name.toLowerCase()).contains("password")) ? "*****" : - (((value == null) ? "" : value)))); + (((value == null) ? "" : value)))); // check if config value exists ConfigurationVO config = _configDao.findByName(name); if (config == null) { - throw new InvalidParameterValueException("Config parameter with name " + name + " doesn't exist"); + throw new InvalidParameterValueException("Config parameter with name " + name + " doesn't exist", null); } if (value == null) { @@ -487,11 +488,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura try { int val = Integer.parseInt(value); if (val <= 0) { - throw new InvalidParameterValueException("Please enter a positive value for the configuration parameter:" + name); + throw new InvalidParameterValueException("Please enter a positive value for the configuration parameter:" + name, null); } } catch (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); + throw new InvalidParameterValueException("There was an error trying to parse the integer value for:" + name, null); } } @@ -509,7 +510,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } catch (NullPointerException e) { s_logger.error("Error parsing ip address for " + name); - throw new InvalidParameterValueException("Error parsing ip address"); + throw new InvalidParameterValueException("Error parsing ip address", null); } } else if (range.equals("netmask")) { if (!NetUtils.isValidNetmask(value)) { @@ -638,7 +639,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (checkForDuplicates) { // Check if the pod already exists if (validPod(podName, zoneId)) { - throw new InvalidParameterValueException("A pod with name: " + podName + " already exists in zone " + zoneId + ". Please specify a different pod name. "); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("A pod with name: " + podName + " already exists in zone with specified id. Please specify a different pod name.", idList); } } @@ -650,7 +653,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura cidrAddress = getCidrAddress(cidr); cidrSize = getCidrSize(cidr); } else { - throw new InvalidParameterValueException("Please enter a valid CIDR for pod: " + podName); + throw new InvalidParameterValueException("Please enter a valid CIDR for pod: " + podName, null); } // Check if the IP range is valid @@ -663,18 +666,18 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Check if the gateway is a valid IP address if (!NetUtils.isValidIp(gateway)) { - throw new InvalidParameterValueException("The gateway is not a valid IP address."); + throw new InvalidParameterValueException("The gateway is not a valid IP address.", null); } // Check if the gateway is in the CIDR subnet if (!NetUtils.getCidrSubNet(gateway, cidrSize).equalsIgnoreCase(NetUtils.getCidrSubNet(cidrAddress, cidrSize))) { - throw new InvalidParameterValueException("The gateway is not in the CIDR subnet."); + throw new InvalidParameterValueException("The gateway is not in the CIDR subnet.", null); } // Don't allow gateway to overlap with start/endIp if (!skipGatewayOverlapCheck) { if (NetUtils.ipRangesOverlap(startIp, endIp, gateway, gateway)) { - throw new InvalidParameterValueException("The gateway shouldn't overlap start/end ip addresses"); + throw new InvalidParameterValueException("The gateway shouldn't overlap start/end ip addresses", null); } } @@ -693,7 +696,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura try { allocationState = Grouping.AllocationState.valueOf(allocationStateStr); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve Allocation State '" + allocationStateStr + "' to a supported state"); + throw new InvalidParameterValueException("Unable to resolve Allocation State '" + allocationStateStr + "' to a supported state", null); } } } @@ -707,7 +710,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Make sure the pod exists if (!validPod(podId)) { - throw new InvalidParameterValueException("A pod with ID: " + podId + " does not exist."); + throw new InvalidParameterValueException("Couldn't find pod by id", null); } checkIfPodIsDeletable(podId); @@ -766,7 +769,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura HostPodVO pod = _podDao.findById(id); ; if (pod == null) { - throw new InvalidParameterValueException("Unable to find pod by id " + id); + throw new InvalidParameterValueException("Unable to find pod by id", null); } String[] existingPodIpRange = pod.getDescription().split("-"); @@ -920,7 +923,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Check if the zone is valid if (!validZone(zoneId)) { - throw new InvalidParameterValueException("Please specify a valid zone."); + throw new InvalidParameterValueException("Please specify a valid zone.", null); } // Check if zone is disabled @@ -949,7 +952,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (startIp != null) { ipRange = startIp + "-" + endIp; } else { - throw new InvalidParameterValueException("Start ip is required parameter"); + throw new InvalidParameterValueException("Start ip is required parameter", null); } HostPodVO pod = new HostPodVO(podName, zoneId, gateway, cidrAddress, cidrSize, ipRange); @@ -1073,7 +1076,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (checkForDuplicates) { // Check if a zone with the specified name already exists if (validZone(zoneName)) { - throw new InvalidParameterValueException("A zone with that name already exists. Please specify a unique zone name."); + throw new InvalidParameterValueException("A zone with that name already exists. Please specify a unique zone name.", null); } } @@ -1082,26 +1085,26 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Please specify a valid domain id"); + throw new InvalidParameterValueException("Please specify a valid domain id", null); } } // Check IP validity for DNS addresses // Empty strings is a valid input -- hence the length check if (dns1 != null && dns1.length() > 0 && !NetUtils.isValidIp(dns1)) { - throw new InvalidParameterValueException("Please enter a valid IP address for DNS1"); + throw new InvalidParameterValueException("Please enter a valid IP address for DNS1", null); } if (dns2 != null && dns2.length() > 0 && !NetUtils.isValidIp(dns2)) { - throw new InvalidParameterValueException("Please enter a valid IP address for DNS2"); + throw new InvalidParameterValueException("Please enter a valid IP address for DNS2", null); } if ((internalDns1 != null && internalDns1.length() > 0 && !NetUtils.isValidIp(internalDns1))) { - throw new InvalidParameterValueException("Please enter a valid IP address for internal DNS1"); + throw new InvalidParameterValueException("Please enter a valid IP address for internal DNS1", null); } if (internalDns2 != null && internalDns2.length() > 0 && !NetUtils.isValidIp(internalDns2)) { - throw new InvalidParameterValueException("Please enter a valid IP address for internal DNS2"); + throw new InvalidParameterValueException("Please enter a valid IP address for internal DNS2", null); } Grouping.AllocationState allocationState = null; @@ -1109,30 +1112,30 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura try { allocationState = Grouping.AllocationState.valueOf(allocationStateStr); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve Allocation State '" + allocationStateStr + "' to a supported state"); + throw new InvalidParameterValueException("Unable to resolve Allocation State '" + allocationStateStr + "' to a supported state", null); } } } private void checkIpRange(String startIp, String endIp, String cidrAddress, long cidrSize) { if (!NetUtils.isValidIp(startIp)) { - throw new InvalidParameterValueException("The start address of the IP range is not a valid IP address."); + throw new InvalidParameterValueException("The start address of the IP range is not a valid IP address.", null); } if (endIp != null && !NetUtils.isValidIp(endIp)) { - throw new InvalidParameterValueException("The end address of the IP range is not a valid IP address."); + throw new InvalidParameterValueException("The end address of the IP range is not a valid IP address.", null); } if (!NetUtils.getCidrSubNet(startIp, cidrSize).equalsIgnoreCase(NetUtils.getCidrSubNet(cidrAddress, cidrSize))) { - throw new InvalidParameterValueException("The start address of the IP range is not in the CIDR subnet."); + throw new InvalidParameterValueException("The start address of the IP range is not in the CIDR subnet.", null); } if (endIp != null && !NetUtils.getCidrSubNet(endIp, cidrSize).equalsIgnoreCase(NetUtils.getCidrSubNet(cidrAddress, cidrSize))) { - throw new InvalidParameterValueException("The end address of the IP range is not in the CIDR subnet."); + throw new InvalidParameterValueException("The end address of the IP range is not in the CIDR subnet.", null); } if (endIp != null && NetUtils.ip2Long(startIp) > NetUtils.ip2Long(endIp)) { - throw new InvalidParameterValueException("The start IP address must have a lower value than the end IP address."); + throw new InvalidParameterValueException("The start IP address must have a lower value than the end IP address.", null); } } @@ -1145,7 +1148,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura for (IPAddressVO publicIPVO : existingPublicIPs) { long publicIP = NetUtils.ip2Long(publicIPVO.getAddress().addr()); if ((publicIP >= privateStartIp) && (publicIP <= privateEndIp)) { - throw new InvalidParameterValueException("The Start IP and endIP address range overlap with Public IP :" + publicIPVO.getAddress().addr()); + throw new InvalidParameterValueException("The Start IP and endIP address range overlap with Public IP :" + publicIPVO.getAddress().addr(), null); } } } @@ -1160,7 +1163,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1])) continue; if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { - throw new InvalidParameterValueException("The Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]); + throw new InvalidParameterValueException("The Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1], null); } } } @@ -1182,7 +1185,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Make sure the zone exists if (!validZone(zoneId)) { - throw new InvalidParameterValueException("A zone with ID: " + zoneId + " does not exist."); + throw new InvalidParameterValueException("Couldn't find zone by id", null); } checkIfZoneIsDeletable(zoneId); @@ -1239,7 +1242,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String trustStorePassword = cmd.getTrustStorePassword(); if (bindDN != null && bindPasswd == null) { - throw new InvalidParameterValueException("If you specify a bind name then you need to provide bind password too."); + throw new InvalidParameterValueException("If you specify a bind name then you need to provide bind password too.", null); } // check if the info is correct @@ -1250,7 +1253,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura env.put(Context.SECURITY_PROTOCOL, "ssl"); protocol = "ldaps://"; if (trustStore == null || trustStorePassword == null) { - throw new InvalidParameterValueException("If you plan to use SSL then you need to configure the trust store."); + throw new InvalidParameterValueException("If you plan to use SSL then you need to configure the trust store.", null); } System.setProperty("javax.net.ssl.trustStore", trustStore); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); @@ -1334,7 +1337,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura s_logger.debug("The ldap server is configured: " + hostname); } catch (NamingException ne) { ne.printStackTrace(); - throw new InvalidParameterValueException("Naming Exception, check you ldap data ! " + ne.getMessage() + (ne.getCause() != null ? ("Caused by:" + ne.getCause().getMessage()) : "")); + throw new InvalidParameterValueException("Naming Exception, check you ldap data ! " + ne.getMessage() + (ne.getCause() != null ? ("Caused by:" + ne.getCause().getMessage()) : ""), null); } return true; } @@ -1368,7 +1371,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String value = (String) detail.get("value"); if ((key == null) || (value == null)) { throw new InvalidParameterValueException( - "Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form: details[0].key=XXX&details[0].value=YYY"); + "Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form: details[0].key=XXX&details[0].value=YYY", null); } // validate the zone detail keys are known keys /* @@ -1386,7 +1389,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!NetUtils.verifyDomainName(dom)) { throw new InvalidParameterValueException( "Invalid network domain suffixes. 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 \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } newDetails.put(ZoneConfig.DnsSearchOrder.getName(), StringUtils.join(dnsSearchOrder, ",")); @@ -1394,7 +1397,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura DataCenterVO zone = _zoneDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("unable to find zone by id " + zoneId); + throw new InvalidParameterValueException("unable to find zone by id ", null); } if (zoneName == null) { @@ -1402,12 +1405,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if ((guestCidr != null) && !NetUtils.validateGuestCidr(guestCidr)) { - throw new InvalidParameterValueException("Please enter a valid guest cidr"); + throw new InvalidParameterValueException("Please enter a valid guest cidr", null); } // Make sure the zone exists if (!validZone(zoneId)) { - throw new InvalidParameterValueException("A zone with ID: " + zoneId + " does not exist."); + throw new InvalidParameterValueException("Couldn't find zone by id", null); } String oldZoneName = zone.getName(); @@ -1429,9 +1432,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (internalDns2 == null) { - internalDns2 = zone.getInternalDns2(); + internalDns2 = zone.getInternalDns2(); } - + if (guestCidr == null) { guestCidr = zone.getGuestNetworkCidr(); } @@ -1441,7 +1444,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura 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 \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } @@ -1514,7 +1517,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network " + mgmtPhyNetwork.getId() + " with same configure of management traffic type"); } } catch (InvalidParameterValueException ex) { - throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage()); + throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage(), null); } } _capacityDao.updateCapacityState(zone.getId(), null, null, null, allocationStateStr); @@ -1542,7 +1545,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // not use these params for updatezone // 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"); + throw new InvalidParameterValueException("Please enter a valid guest cidr", null); } // Validate network domain @@ -1550,7 +1553,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura 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 \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } @@ -1648,7 +1651,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (!(type.equalsIgnoreCase(NetworkType.Basic.toString())) && !(type.equalsIgnoreCase(NetworkType.Advanced.toString()))) { - throw new InvalidParameterValueException("Invalid zone type; only Advanced and Basic values are supported"); + throw new InvalidParameterValueException("Invalid zone type; only Advanced and Basic values are supported", null); } else if (type.equalsIgnoreCase(NetworkType.Basic.toString())) { isBasic = true; } @@ -1657,7 +1660,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // error out when the parameter specified for Basic zone if (zoneType == NetworkType.Basic && guestCidr != null) { - throw new InvalidParameterValueException("guestCidrAddress parameter is not supported for Basic zone"); + throw new InvalidParameterValueException("guestCidrAddress parameter is not supported for Basic zone", null); } DomainVO domainVO = null; @@ -1684,32 +1687,32 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String name = cmd.getServiceOfferingName(); if ((name == null) || (name.length() == 0)) { - throw new InvalidParameterValueException("Failed to create service offering: specify the name that has non-zero length"); + throw new InvalidParameterValueException("Failed to create service offering: specify the name that has non-zero length", null); } String displayText = cmd.getDisplayText(); if ((displayText == null) || (displayText.length() == 0)) { - throw new InvalidParameterValueException("Failed to create service offering " + name + ": specify the display text that has non-zero length"); + throw new InvalidParameterValueException("Failed to create service offering " + name + ": specify the display text that has non-zero length", null); } Long cpuNumber = cmd.getCpuNumber(); if ((cpuNumber == null) || (cpuNumber.intValue() <= 0) || (cpuNumber.intValue() > 2147483647)) { - throw new InvalidParameterValueException("Failed to create service offering " + name + ": specify the cpu number value between 1 and 2147483647"); + throw new InvalidParameterValueException("Failed to create service offering " + name + ": specify the cpu number value between 1 and 2147483647", null); } Long cpuSpeed = cmd.getCpuSpeed(); if ((cpuSpeed == null) || (cpuSpeed.intValue() <= 0) || (cpuSpeed.intValue() > 2147483647)) { - throw new InvalidParameterValueException("Failed to create service offering " + name + ": specify the cpu speed value between 1 and 2147483647"); + throw new InvalidParameterValueException("Failed to create service offering " + name + ": specify the cpu speed value between 1 and 2147483647", null); } Long memory = cmd.getMemory(); if ((memory == null) || (memory.intValue() < 32) || (memory.intValue() > 2147483647)) { - throw new InvalidParameterValueException("Failed to create service offering " + name + ": specify the memory value between 32 and 2147483647 MB"); + throw new InvalidParameterValueException("Failed to create service offering " + name + ": specify the memory value between 32 and 2147483647 MB", null); } // check if valid domain if (cmd.getDomainId() != null && _domainDao.findById(cmd.getDomainId()) == null) { - throw new InvalidParameterValueException("Please specify a valid domain id"); + throw new InvalidParameterValueException("Please specify a valid domain id", null); } boolean localStorageRequired = false; @@ -1718,7 +1721,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (storageType.equalsIgnoreCase(ServiceOffering.StorageType.local.toString())) { localStorageRequired = true; } else if (!storageType.equalsIgnoreCase(ServiceOffering.StorageType.shared.toString())) { - throw new InvalidParameterValueException("Invalid storage type " + storageType + " specified, valid types are: 'local' and 'shared'"); + throw new InvalidParameterValueException("Invalid storage type " + storageType + " specified, valid types are: 'local' and 'shared'", null); } } @@ -1745,7 +1748,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura vmType = VirtualMachine.Type.SecondaryStorageVm; } else { throw new InvalidParameterValueException("Invalid systemVmType. Supported types are: " + VirtualMachine.Type.DomainRouter + ", " + VirtualMachine.Type.ConsoleProxy + ", " - + VirtualMachine.Type.SecondaryStorageVm); + + VirtualMachine.Type.SecondaryStorageVm, null); } } else { allowNetworkRate = true; @@ -1753,7 +1756,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (cmd.getNetworkRate() != null && !allowNetworkRate) { - throw new InvalidParameterValueException("Network rate can be specified only for non-System offering and system offerings having \"domainrouter\" systemvmtype"); + throw new InvalidParameterValueException("Network rate can be specified only for non-System offering and system offerings having \"domainrouter\" systemvmtype", null); } return createServiceOffering(userId, cmd.getIsSystem(), vmType, cmd.getServiceOfferingName(), cpuNumber.intValue(), memory.intValue(), cpuSpeed.intValue(), cmd.getDisplayText(), @@ -1793,7 +1796,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura ServiceOffering offeringHandle = getServiceOffering(id); if (offeringHandle == null) { - throw new InvalidParameterValueException("unable to find service offering " + id); + throw new InvalidParameterValueException("unable to find service offering by id", null); } boolean updateNeeded = (name != null || displayText != null || sortKey != null); @@ -1853,9 +1856,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura public DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized) { long diskSize = 0;// special case for custom disk offerings if (numGibibytes != null && (numGibibytes <= 0)) { - throw new InvalidParameterValueException("Please specify a disk size of at least 1 Gb."); + throw new InvalidParameterValueException("Please specify a disk size of at least 1 Gb.", null); } else if (numGibibytes != null && (numGibibytes > _maxVolumeSizeInGb)) { - throw new InvalidParameterValueException("The maximum size for a disk is " + _maxVolumeSizeInGb + " Gb."); + throw new InvalidParameterValueException("The maximum size for a disk is " + _maxVolumeSizeInGb + " Gb.", null); } if (numGibibytes != null) { @@ -1884,8 +1887,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String description = cmd.getDisplayText(); Long numGibibytes = cmd.getDiskSize(); boolean isCustomized = cmd.isCustomized() != null ? cmd.isCustomized() : false; // false - // by - // default + // by + // default String tags = cmd.getTags(); // Long domainId = cmd.getDomainId() != null ? cmd.getDomainId() : // Long.valueOf(DomainVO.ROOT_DOMAIN); // disk offering @@ -1894,7 +1897,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Long domainId = cmd.getDomainId(); if (!isCustomized && numGibibytes == null) { - throw new InvalidParameterValueException("Disksize is required for non-customized disk offering"); + throw new InvalidParameterValueException("Disksize is required for non-customized disk offering", null); } return createDiskOffering(domainId, name, description, numGibibytes, tags, isCustomized); @@ -1912,7 +1915,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura DiskOffering diskOfferingHandle = getDiskOffering(diskOfferingId); if (diskOfferingHandle == null) { - throw new InvalidParameterValueException("Unable to find disk offering by id " + diskOfferingId); + throw new InvalidParameterValueException("Unable to find disk offering by id", null); } boolean updateNeeded = (name != null || displayText != null || sortKey != null); @@ -1975,7 +1978,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura DiskOffering offering = getDiskOffering(diskOfferingId); if (offering == null) { - throw new InvalidParameterValueException("Unable to find disk offering by id " + diskOfferingId); + throw new InvalidParameterValueException("Unable to find disk offering by id", null); } if (_diskOfferingDao.remove(diskOfferingId)) { @@ -2000,11 +2003,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Verify service offering id ServiceOffering offering = getServiceOffering(offeringId); if (offering == null) { - throw new InvalidParameterValueException("unable to find service offering " + offeringId); + throw new InvalidParameterValueException("unable to find service offering by id", null); } if (offering.getDefaultUse()) { - throw new InvalidParameterValueException("Default service offerings cannot be deleted"); + throw new InvalidParameterValueException("Default service offerings cannot be deleted", null); } if (_serviceOfferingDao.remove(offeringId)) { @@ -2037,11 +2040,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (projectId != null) { if (accountName != null) { - throw new InvalidParameterValueException("Account and projectId are mutually exclusive"); + throw new InvalidParameterValueException("Account and projectId are mutually exclusive", null); } Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } vlanOwner = _accountMgr.getAccount(project.getProjectAccountId()); @@ -2050,7 +2053,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if ((accountName != null) && (domainId != null)) { vlanOwner = _accountDao.findActiveAccount(accountName, domainId); if (vlanOwner == null) { - throw new InvalidParameterValueException("Please specify a valid account."); + throw new InvalidParameterValueException("Please specify a valid account.", null); } } @@ -2059,17 +2062,17 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (networkId != null) { network = _networkDao.findById(networkId); if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + networkId); + throw new InvalidParameterValueException("Unable to find network by id", null); } else { zoneId = network.getDataCenterId(); physicalNetworkId = network.getPhysicalNetworkId(); } } - + // Verify that zone exists DataCenterVO zone = _zoneDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Unable to find zone by id " + zoneId); + throw new InvalidParameterValueException("Unable to find zone by id", null); } // verify that physical network exists @@ -2077,14 +2080,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (physicalNetworkId != null) { pNtwk = _physicalNetworkDao.findById(physicalNetworkId); if (pNtwk == null) { - throw new InvalidParameterValueException("Unable to find Physical Network with id=" + physicalNetworkId); + throw new InvalidParameterValueException("Unable to find Physical Network by id", null); } if (zoneId == null) { zoneId = pNtwk.getDataCenterId(); } } else { if (zoneId == null) { - throw new InvalidParameterValueException(""); + throw new InvalidParameterValueException("Couldn't find zone by id", null); } // deduce physicalNetworkFrom Zone or Network. if (network != null && network.getPhysicalNetworkId() != null) { @@ -2101,14 +2104,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zone.isSecurityGroupEnabled()) { physicalNetworkId = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId(); } else { - throw new InvalidParameterValueException("Physical Network Id is null, please provide the Network id for Direct vlan creation "); + throw new InvalidParameterValueException("Physical Network Id is null, please provide the Network id for Direct vlan creation", null); } } } } } - - + + // Check if zone is enabled Account caller = UserContext.current().getCaller(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { @@ -2116,7 +2119,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (zone.isSecurityGroupEnabled() && zone.getNetworkType() != DataCenter.NetworkType.Basic && forVirtualNetwork) { - throw new InvalidParameterValueException("Can't add virtual ip range into a zone with security group enabled"); + throw new InvalidParameterValueException("Can't add virtual ip range into a zone with security group enabled", null); } // If networkId is not specified, and vlan is Virtual or Direct Untagged, try to locate default networks @@ -2126,7 +2129,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura networkId = _networkMgr.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId(); network = _networkMgr.getNetwork(networkId); } else if (network.getGuestType() != null || network.getTrafficType() != TrafficType.Public) { - throw new InvalidParameterValueException("Can't find Public network by id=" + networkId); + throw new InvalidParameterValueException("Can't find Public network by id", null); } } else { if (network == null) { @@ -2136,7 +2139,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } else { network = _networkMgr.getNetworkWithSecurityGroupEnabled(zoneId); if (network == null) { - throw new InvalidParameterValueException("Nework id is required for Direct vlan creation "); + throw new InvalidParameterValueException("Nework id is required for Direct vlan creation", null); } networkId = network.getId(); } @@ -2147,7 +2150,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // 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"); + throw new InvalidParameterValueException("Network " + network + " doesn't support adding ip ranges", null); } // if end ip is not specified, default it to startIp @@ -2157,7 +2160,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (forVirtualNetwork || zone.getNetworkType() == DataCenter.NetworkType.Basic || zone.isSecurityGroupEnabled()) { if (vlanGateway == null || vlanNetmask == null || zoneId == null) { - throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks"); + throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks", null); } } else { // check if startIp and endIp belong to network Cidr @@ -2168,12 +2171,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Check if ip addresses are in network range if (!NetUtils.sameSubnet(startIP, networkGateway, networkNetmask)) { - throw new InvalidParameterValueException("Start ip is not in network cidr: " + networkCidr); + throw new InvalidParameterValueException("Start ip is not in network cidr: " + networkCidr, null); } if (endIP != null) { if (!NetUtils.sameSubnet(endIP, networkGateway, networkNetmask)) { - throw new InvalidParameterValueException("End ip is not in network cidr: " + networkCidr); + throw new InvalidParameterValueException("End ip is not in network cidr: " + networkCidr, null); } } @@ -2193,7 +2196,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura //check resource limits _resourceLimitMgr.checkResourceLimit(vlanOwner, ResourceType.public_ip, accountIpRange); - + associateIpRangeToAccount = true; } } @@ -2231,29 +2234,29 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura public Vlan createVlanAndPublicIpRange(long zoneId, long networkId, long physicalNetworkId, boolean forVirtualNetwork, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, String vlanId, Account vlanOwner) { - - + + Network network = _networkMgr.getNetwork(networkId); - + //Validate the zone DataCenterVO zone = _zoneDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + throw new InvalidParameterValueException("Please specify a valid zone.", null); } - + // ACL check checkZoneAccess(UserContext.current().getCaller(), zone); - + //Validate the physical network if (_physicalNetworkDao.findById(physicalNetworkId) == null) { - throw new InvalidParameterValueException("Please specify a valid physical network id"); + throw new InvalidParameterValueException("Please specify a valid physical network id", null); } - + //Validate the pod if (podId != null) { Pod pod = _podDao.findById(podId); if (pod == null) { - throw new InvalidParameterValueException("Please specify a valid pod."); + throw new InvalidParameterValueException("Please specify a valid pod.", null); } if (pod.getDataCenterId() != zoneId) { throw new InvalidParameterValueException("Pod id=" + podId + " doesn't belong to zone id=" + zoneId); @@ -2261,10 +2264,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura //pod vlans can be created in basic zone only if (zone.getNetworkType() != NetworkType.Basic || network.getTrafficType() != TrafficType.Guest) { throw new InvalidParameterValueException("Pod id can be specified only for the networks of type " - + TrafficType.Guest + " in zone of type " + NetworkType.Basic); + + TrafficType.Guest + " in zone of type " + NetworkType.Basic, null); } } - + //1) if vlan is specified for the guest network range, it should be the same as network's vlan //2) if vlan is missing, default it to the guest network's vlan if (network.getTrafficType() == TrafficType.Guest) { @@ -2274,39 +2277,39 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String[] vlan = uri.toString().split("vlan:\\/\\/"); networkVlanId = vlan[1]; } - + if (vlanId != null) { // if vlan is specified, throw an error if it's not equal to network's vlanId if (networkVlanId != null && !networkVlanId.equalsIgnoreCase(vlanId)) { - throw new InvalidParameterValueException("Vlan doesn't match vlan of the network"); + throw new InvalidParameterValueException("Vlan doesn't match vlan of the network", null); } } else { vlanId = networkVlanId; } } else if (network.getTrafficType() == TrafficType.Public && vlanId == null) { //vlan id is required for public network - throw new InvalidParameterValueException("Vlan id is required when add ip range to the public network"); + throw new InvalidParameterValueException("Vlan id is required when add ip range to the public network", null); } - + if (vlanId == null) { vlanId = Vlan.UNTAGGED; } VlanType vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; - - + + if (vlanOwner != null && zone.getNetworkType() != NetworkType.Advanced) { - throw new InvalidParameterValueException("Vlan owner can be defined only in the zone of type " + NetworkType.Advanced); + throw new InvalidParameterValueException("Vlan owner can be defined only in the zone of type " + NetworkType.Advanced, null); } // Make sure the gateway is valid if (!NetUtils.isValidIp(vlanGateway)) { - throw new InvalidParameterValueException("Please specify a valid gateway"); + throw new InvalidParameterValueException("Please specify a valid gateway", null); } // Make sure the netmask is valid if (!NetUtils.isValidIp(vlanNetmask)) { - throw new InvalidParameterValueException("Please specify a valid netmask"); + throw new InvalidParameterValueException("Please specify a valid netmask", null); } String newVlanSubnet = NetUtils.getSubNet(vlanGateway, vlanNetmask); @@ -2331,7 +2334,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (newVlanSubnet.equals(guestSubnet)) { throw new InvalidParameterValueException("The new IP range you have specified has the same subnet as the guest network in zone: " + zone.getName() - + ". Please specify a different gateway/netmask."); + + ". Please specify a different gateway/netmask.", null); } } @@ -2363,7 +2366,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (forVirtualNetwork && !vlanId.equals(vlan.getVlanTag()) && newVlanSubnet.equals(otherVlanSubnet) && !allowIpRangeOverlap(vlan, forVirtualNetwork, networkId)) { throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " in zone " + zone.getName() - + " has the same subnet. Please specify a different gateway/netmask."); + + " has the same subnet. Please specify a different gateway/netmask.", null); } boolean vlansUntaggedAndVirtual = (vlanId.equals(Vlan.UNTAGGED) && vlanId.equals(vlan.getVlanTag()) && forVirtualNetwork && vlan.getVlanType() == VlanType.VirtualNetwork); @@ -2375,12 +2378,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (vlanId.equals(vlan.getVlanTag()) && newVlanSubnet.equals(otherVlanSubnet)) { if (NetUtils.ipRangesOverlap(startIP, endIP, otherVlanStartIP, otherVlanEndIP)) { throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() - + " already has IPs that overlap with the new range. Please specify a different start IP/end IP."); + + " already has IPs that overlap with the new range. Please specify a different start IP/end IP.", null); } if (!vlanGateway.equals(otherVlanGateway)) { throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " has already been added with gateway " + otherVlanGateway - + ". Please specify a different tag."); + + ". Please specify a different tag.", null); } } } @@ -2441,9 +2444,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura public boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId, Account caller) { VlanVO vlan = _vlanDao.findById(vlanDbId); if (vlan == null) { - throw new InvalidParameterValueException("Please specify a valid IP range id."); + throw new InvalidParameterValueException("Please specify a valid IP range id.", null); } - + boolean isAccountSpecific = false; List acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlan.getId()); // Check for account wide pool. It will have an entry for account_vlan_map. @@ -2461,25 +2464,25 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (vlan == null) { throw new CloudRuntimeException("Unable to acquire vlan configuration: " + vlanDbId); } - + if (s_logger.isDebugEnabled()) { s_logger.debug("lock vlan " + vlanDbId + " is acquired"); } - + List ips = _publicIpAddressDao.listByVlanId(vlanDbId); - + for (IPAddressVO ip : ips) { if (ip.isOneToOneNat()) { throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is used for static nat purposes. Cleanup the rules first"); } - + if (ip.isSourceNat() && _networkMgr.getNetwork(ip.getAssociatedWithNetworkId()) != null) { throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() + ". IP range with the source nat ip address can be removed either as a part of Network, or account removal"); } - + if (_firewallDao.countRulesByIpId(ip.getId()) > 0) { throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range has firewall rules applied. Cleanup the rules first"); @@ -2494,7 +2497,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura _vlanDao.releaseFromLockTable(vlanDbId); } } else { - throw new InvalidParameterValueException("The IP range can't be deleted because it has allocated public IP addresses."); + throw new InvalidParameterValueException("The IP range can't be deleted because it has allocated public IP addresses.", null); } } @@ -2572,7 +2575,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return true; } - + @DB protected boolean savePublicIPRange(String startIP, String endIP, long zoneId, long vlanDbId, long sourceNetworkid, long physicalNetworkId) { @@ -2589,53 +2592,53 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura private void checkPublicIpRangeErrors(long zoneId, String vlanId, String vlanGateway, String vlanNetmask, String startIP, String endIP) { // Check that the start and end IPs are valid if (!NetUtils.isValidIp(startIP)) { - throw new InvalidParameterValueException("Please specify a valid start IP"); + throw new InvalidParameterValueException("Please specify a valid start IP", null); } if (endIP != null && !NetUtils.isValidIp(endIP)) { - throw new InvalidParameterValueException("Please specify a valid end IP"); + throw new InvalidParameterValueException("Please specify a valid end IP", null); } if (endIP != null && !NetUtils.validIpRange(startIP, endIP)) { - throw new InvalidParameterValueException("Please specify a valid IP range."); + throw new InvalidParameterValueException("Please specify a valid IP range.", null); } // Check that the IPs that are being added are compatible with the // VLAN's gateway and netmask if (vlanNetmask == null) { - throw new InvalidParameterValueException("Please ensure that your IP range's netmask is specified"); + throw new InvalidParameterValueException("Please ensure that your IP range's netmask is specified", null); } if (endIP != null && !NetUtils.sameSubnet(startIP, endIP, vlanNetmask)) { - throw new InvalidParameterValueException("Please ensure that your start IP and end IP are in the same subnet, as per the IP range's netmask."); + throw new InvalidParameterValueException("Please ensure that your start IP and end IP are in the same subnet, as per the IP range's netmask.", null); } if (!NetUtils.sameSubnet(startIP, vlanGateway, vlanNetmask)) { - throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as your IP range's gateway, as per the IP range's netmask."); + throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as your IP range's gateway, as per the IP range's netmask.", null); } if (endIP != null && !NetUtils.sameSubnet(endIP, vlanGateway, vlanNetmask)) { - throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as your IP range's gateway, as per the IP range's netmask."); + throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as your IP range's gateway, as per the IP range's netmask.", null); } } private void checkPrivateIpRangeErrors(Long podId, String startIP, String endIP) { HostPodVO pod = _podDao.findById(podId); if (pod == null) { - throw new InvalidParameterValueException("Please specify a valid pod."); + throw new InvalidParameterValueException("Please specify a valid pod.", null); } // Check that the start and end IPs are valid if (!NetUtils.isValidIp(startIP)) { - throw new InvalidParameterValueException("Please specify a valid start IP"); + throw new InvalidParameterValueException("Please specify a valid start IP", null); } if (endIP != null && !NetUtils.isValidIp(endIP)) { - throw new InvalidParameterValueException("Please specify a valid end IP"); + throw new InvalidParameterValueException("Please specify a valid end IP", null); } if (endIP != null && !NetUtils.validIpRange(startIP, endIP)) { - throw new InvalidParameterValueException("Please specify a valid IP range."); + throw new InvalidParameterValueException("Please specify a valid IP range.", null); } // Check that the IPs that are being added are compatible with the pod's @@ -2644,15 +2647,15 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura long cidrSize = getCidrSize(podId); if (endIP != null && !NetUtils.sameSubnetCIDR(startIP, endIP, cidrSize)) { - throw new InvalidParameterValueException("Please ensure that your start IP and end IP are in the same subnet, as per the pod's CIDR size."); + throw new InvalidParameterValueException("Please ensure that your start IP and end IP are in the same subnet, as per the pod's CIDR size.", null); } if (!NetUtils.sameSubnetCIDR(startIP, cidrAddress, cidrSize)) { - throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as the pod's CIDR address."); + throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as the pod's CIDR address.", null); } if (endIP != null && !NetUtils.sameSubnetCIDR(endIP, cidrAddress, cidrSize)) { - throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as the pod's CIDR address."); + throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as the pod's CIDR address.", null); } } @@ -2733,10 +2736,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Check that cidrSubnet does not equal guestSubnet if (cidrSubnet.equals(guestSubnet)) { if (podName.equals("newPod")) { - throw new InvalidParameterValueException("The subnet of the pod you are adding conflicts with the subnet of the Guest IP Network. Please specify a different CIDR."); + throw new InvalidParameterValueException("The subnet of the pod you are adding conflicts with the subnet of the Guest IP Network. Please specify a different CIDR.", null); } else { throw new InvalidParameterValueException("Warning: The subnet of pod " + podName + " in zone " + zoneName - + " conflicts with the subnet of the Guest IP Network. Please change either the pod's CIDR or the Guest IP Network's subnet, and re-run install-vmops-management."); + + " conflicts with the subnet of the Guest IP Network. Please change either the pod's CIDR or the Guest IP Network's subnet, and re-run install-vmops-management.", null); } } } @@ -2765,17 +2768,17 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String otherPodName = getPodName(otherPodId.longValue()); if (podName.equals("newPod")) { throw new InvalidParameterValueException("The subnet of the pod you are adding conflicts with the subnet of pod " + otherPodName + " in zone " + zoneName - + ". Please specify a different CIDR."); + + ". Please specify a different CIDR.", null); } else { throw new InvalidParameterValueException("Warning: The pods " + podName + " and " + otherPodName + " in zone " + zoneName - + " have conflicting CIDR subnets. Please change the CIDR of one of these pods."); + + " have conflicting CIDR subnets. Please change the CIDR of one of these pods.", null); } } } } } - + private boolean validPod(long podId) { return (_podDao.findById(podId) != null); } @@ -2813,12 +2816,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String ipNums = _configDao.getValue("linkLocalIp.nums"); int nums = Integer.parseInt(ipNums); if (nums > 16 || nums <= 0) { - throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16"); + throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16", null); } /* local link ip address starts from 169.254.0.2 - 169.254.(nums) */ String[] ipRanges = NetUtils.getLinkLocalIPRange(nums); if (ipRanges == null) { - throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16"); + throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16", null); } return ipRanges; } @@ -2830,7 +2833,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura VlanVO vlan = _vlanDao.findById(vlanDbId); if (vlan == null) { - throw new InvalidParameterValueException("Please specify a valid IP range id."); + throw new InvalidParameterValueException("Please specify a valid IP range id.", null); } return deleteVlanAndPublicIpRange(UserContext.current().getCallerUserId(), vlanDbId, UserContext.current().getCaller()); @@ -2895,12 +2898,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } if (trafficType == null) { - throw new InvalidParameterValueException("Invalid value for traffictype. Supported traffic types: Public, Management, Control, Guest, Vlan or Storage"); + throw new InvalidParameterValueException("Invalid value for traffictype. Supported traffic types: Public, Management, Control, Guest, Vlan or Storage", null); } // Only GUEST traffic type is supported in Acton if (trafficType != TrafficType.Guest) { - throw new InvalidParameterValueException("Only traffic type " + TrafficType.Guest + " is supported in the current release"); + throw new InvalidParameterValueException("Only traffic type " + TrafficType.Guest + " is supported in the current release", null); } // Verify offering type @@ -2912,7 +2915,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (guestType == null) { - throw new InvalidParameterValueException("Invalid \"type\" parameter is given; can have Shared and Isolated values"); + throw new InvalidParameterValueException("Invalid \"type\" parameter is given; can have Shared and Isolated values", null); } // Verify availability @@ -2923,7 +2926,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (availability == null) { - throw new InvalidParameterValueException("Invalid value for Availability. Supported types: " + Availability.Required + ", " + Availability.Optional); + throw new InvalidParameterValueException("Invalid value for Availability. Supported types: " + Availability.Required + ", " + Availability.Optional, null); } Long serviceOfferingId = cmd.getServiceOfferingId(); @@ -2931,7 +2934,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (serviceOfferingId != null) { ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOfferingId); if (offering == null) { - throw new InvalidParameterValueException("Cannot find specified service offering: " + serviceOfferingId); + throw new InvalidParameterValueException("Cannot find specified service offering by id", null); } if (!VirtualMachine.Type.DomainRouter.toString().equalsIgnoreCase(offering.getSystemVmType())) { throw new InvalidParameterValueException("The specified service offering " + serviceOfferingId + " cannot be used by virtual router!"); @@ -2947,13 +2950,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // validate if the service is supported Service service = Network.Service.getService(serviceName); if (service == null || service == Service.Gateway) { - throw new InvalidParameterValueException("Invalid service " + serviceName); + throw new InvalidParameterValueException("Invalid service " + serviceName, null); } if (service == Service.SecurityGroup) { // allow security group service for Shared networks only if (guestType != GuestType.Shared) { - throw new InvalidParameterValueException("Secrity group service is supported for network offerings with guest ip type " + GuestType.Shared); + throw new InvalidParameterValueException("Secrity group service is supported for network offerings with guest ip type " + GuestType.Shared, null); } Set sgProviders = new HashSet(); sgProviders.add(Provider.SecurityGroupProvider); @@ -2981,19 +2984,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // in Acton, don't allow to specify more than 1 provider per service if (svcPrv.get(serviceStr) != null && svcPrv.get(serviceStr).size() > 1) { throw new InvalidParameterValueException("In the current release only one provider can be " + - "specified for the service"); + "specified for the service", null); } for (String prvNameStr : svcPrv.get(serviceStr)) { // check if provider is supported Network.Provider provider = Network.Provider.getProvider(prvNameStr); if (provider == null) { - throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); + throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr, null); } if (provider == Provider.JuniperSRX) { firewallProvider = Provider.JuniperSRX; } - + if ((service == Service.PortForwarding || service == Service.StaticNat) && provider == Provider.VirtualRouter){ firewallProvider = Provider.VirtualRouter; } @@ -3013,7 +3016,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura serviceProviderMap.put(service, providers); } else { throw new InvalidParameterValueException("Service " + serviceStr + " is not enabled for the network " + - "offering, can't add a provider to it"); + "offering, can't add a provider to it", null); } } } @@ -3024,21 +3027,21 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // validate the LB service capabilities specified in the network offering Map lbServiceCapabilityMap = cmd.getServiceCapabilities(Service.Lb); if (!serviceProviderMap.containsKey(Service.Lb) && lbServiceCapabilityMap != null && !lbServiceCapabilityMap.isEmpty()) { - throw new InvalidParameterValueException("Capabilities for LB service can be specifed only when LB service is enabled for network offering."); + throw new InvalidParameterValueException("Capabilities for LB service can be specifed only when LB service is enabled for network offering.", null); } validateLoadBalancerServiceCapabilities(lbServiceCapabilityMap); // validate the Source NAT service capabilities specified in the network offering Map sourceNatServiceCapabilityMap = cmd.getServiceCapabilities(Service.SourceNat); if (!serviceProviderMap.containsKey(Service.SourceNat) && sourceNatServiceCapabilityMap != null && !sourceNatServiceCapabilityMap.isEmpty()) { - throw new InvalidParameterValueException("Capabilities for source NAT service can be specifed only when source NAT service is enabled for network offering."); + throw new InvalidParameterValueException("Capabilities for source NAT service can be specifed only when source NAT service is enabled for network offering.", null); } validateSourceNatServiceCapablities(sourceNatServiceCapabilityMap); // validate the Static Nat service capabilities specified in the network offering Map staticNatServiceCapabilityMap = cmd.getServiceCapabilities(Service.StaticNat); if (!serviceProviderMap.containsKey(Service.StaticNat) && sourceNatServiceCapabilityMap != null && !staticNatServiceCapabilityMap.isEmpty()) { - throw new InvalidParameterValueException("Capabilities for static NAT service can be specifed only when static NAT service is enabled for network offering."); + throw new InvalidParameterValueException("Capabilities for static NAT service can be specifed only when static NAT service is enabled for network offering.", null); } validateStaticNatServiceCapablities(staticNatServiceCapabilityMap); @@ -3062,7 +3065,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura void validateLoadBalancerServiceCapabilities(Map lbServiceCapabilityMap) { if (lbServiceCapabilityMap != null && !lbServiceCapabilityMap.isEmpty()) { if (lbServiceCapabilityMap.keySet().size() > 2 || !lbServiceCapabilityMap.containsKey(Capability.SupportedLBIsolation)) { - throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service", null); } for (Capability cap : lbServiceCapabilityMap.keySet()) { @@ -3071,16 +3074,16 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura boolean dedicatedLb = value.contains("dedicated"); boolean sharedLB = value.contains("shared"); if ((dedicatedLb && sharedLB) || (!dedicatedLb && !sharedLB)) { - throw new InvalidParameterValueException("Either dedicated or shared isolation can be specified for " + Capability.SupportedLBIsolation.getName()); + throw new InvalidParameterValueException("Either dedicated or shared isolation can be specified for " + Capability.SupportedLBIsolation.getName(), null); } } else if (cap == Capability.ElasticLb) { boolean enabled = value.contains("true"); boolean disabled = value.contains("false"); if (!enabled && !disabled) { - throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticLb.getName()); + throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticLb.getName(), null); } } else { - throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service", null); } } } @@ -3089,7 +3092,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura void validateSourceNatServiceCapablities(Map 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"); + throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + " capabilities can be sepcified for source nat service", null); } for (Capability capability : sourceNatServiceCapabilityMap.keySet()) { @@ -3098,16 +3101,16 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura boolean perAccount = value.contains("peraccount"); 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()); + throw new InvalidParameterValueException("Either peraccount or perzone source NAT type can be specified for " + Capability.SupportedSourceNatTypes.getName(), null); } } else if (capability == Capability.RedundantRouter) { boolean enabled = value.contains("true"); boolean disabled = value.contains("false"); if (!enabled && !disabled) { - throw new InvalidParameterValueException("Unknown specified value for " + Capability.RedundantRouter.getName()); + throw new InvalidParameterValueException("Unknown specified value for " + Capability.RedundantRouter.getName(), null); } } else { - throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + " capabilities can be sepcified for source nat service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + " capabilities can be sepcified for source nat service", null); } } } @@ -3116,7 +3119,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura void validateStaticNatServiceCapablities(Map staticNatServiceCapabilityMap) { if (staticNatServiceCapabilityMap != null && !staticNatServiceCapabilityMap.isEmpty()) { if (staticNatServiceCapabilityMap.keySet().size() > 1) { - throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capabilitiy can be sepcified for static nat service"); + throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capabilitiy can be sepcified for static nat service", null); } for (Capability capability : staticNatServiceCapabilityMap.keySet()) { @@ -3125,10 +3128,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura boolean enabled = value.contains("true"); boolean disabled = value.contains("false"); if (!enabled && !disabled) { - throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticIp.getName()); + throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticIp.getName(), null); } } else { - throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capabilitiy can be sepcified for static nat service"); + throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capabilitiy can be sepcified for static nat service", null); } } } @@ -3143,20 +3146,20 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - + if (specifyVlan != specifyIpRanges) { - throw new InvalidParameterValueException("SpecifyVlan should be equal to specifyIpRanges which is " + specifyIpRanges); + throw new InvalidParameterValueException("SpecifyVlan should be equal to specifyIpRanges which is " + specifyIpRanges, null); } // specifyVlan should always be true for Shared network offerings if (!specifyVlan && type == GuestType.Shared) { - throw new InvalidParameterValueException("SpecifyVlan should be true if network offering's type is " + type); + throw new InvalidParameterValueException("SpecifyVlan should be true if network offering's type is " + type, null); } - + //specifyIpRanges should always be false for Isolated offering with Source nat service enabled if (specifyVlan && type == GuestType.Isolated && serviceProviderMap.containsKey(Service.SourceNat)) { throw new InvalidParameterValueException("SpecifyVlan should be false if the network offering type is " - + type + " and service " + Service.SourceNat.getName() + " is supported"); + + type + " and service " + Service.SourceNat.getName() + " is supported", null); } // validate availability value @@ -3165,7 +3168,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!canOffBeRequired) { throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " - + Service.SourceNat.getName() + " enabled"); + + Service.SourceNat.getName() + " enabled", null); } // only one network offering in the system can be Required @@ -3288,7 +3291,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zoneId != null) { zone = getZone(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Unable to find the zone by id=" + zoneId); + throw new InvalidParameterValueException("Unable to find the zone by id", null); } } @@ -3354,12 +3357,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // check if network exists and the caller can operate with it Network network = _networkMgr.getNetwork(networkId); if (network == null) { - throw new InvalidParameterValueException("Unable to find the network by id=" + networkId); + throw new InvalidParameterValueException("Unable to find the network by id", null); } // Don't allow to update system network NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId()); if (offering.isSystemOnly()) { - throw new InvalidParameterValueException("Can't update system networks"); + throw new InvalidParameterValueException("Can't update system networks", null); } _accountMgr.checkAccess(caller, null, true, network); @@ -3424,7 +3427,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura for (String supportedServiceStr : supportedServicesStr) { Service service = Service.getService(supportedServiceStr); if (service == null) { - throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr); + throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr, null); } else { supportedServices[i] = service; } @@ -3459,7 +3462,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (sourceNatSupported != null) { addOffering = addOffering && (_networkMgr.areServicesSupportedByNetworkOffering(offering.getId(), Network.Service.SourceNat) == sourceNatSupported); } - + if (forVpc != null) { addOffering = addOffering && (isOfferingForVpc(offering) == forVpc.booleanValue()); } @@ -3492,14 +3495,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Verify network offering id NetworkOfferingVO offering = _networkOfferingDao.findById(offeringId); if (offering == null) { - throw new InvalidParameterValueException("unable to find network offering " + offeringId); + throw new InvalidParameterValueException("unable to find network offering by id", null); } else if (offering.getRemoved() != null || offering.isSystemOnly()) { - throw new InvalidParameterValueException("unable to find network offering " + offeringId); + throw new InvalidParameterValueException("unable to find network offering by id", null); } // Don't allow to delete default network offerings if (offering.isDefault() == true) { - throw new InvalidParameterValueException("Default network offering can't be deleted"); + throw new InvalidParameterValueException("Default network offering can't be deleted", null); } // don't allow to delete network offering if it's in use by existing networks (the offering can be disabled @@ -3532,12 +3535,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Verify input parameters NetworkOfferingVO offeringToUpdate = _networkOfferingDao.findById(id); if (offeringToUpdate == null) { - throw new InvalidParameterValueException("unable to find network offering " + id); + throw new InvalidParameterValueException("unable to find network offering by id", null); } // Don't allow to update system network offering if (offeringToUpdate.isSystemOnly()) { - throw new InvalidParameterValueException("Can't update system network offerings"); + throw new InvalidParameterValueException("Can't update system network offerings", null); } NetworkOfferingVO offering = _networkOfferingDao.createForUpdate(id); @@ -3563,7 +3566,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } if (!validState) { - throw new InvalidParameterValueException("Incorrect state value: " + state); + throw new InvalidParameterValueException("Incorrect state value: " + state, null); } } @@ -3576,22 +3579,22 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (availability == null) { throw new InvalidParameterValueException("Invalid value for Availability. Supported types: " - + Availability.Required + ", " + Availability.Optional); + + Availability.Required + ", " + Availability.Optional, null); } else { if (availability == NetworkOffering.Availability.Required) { boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkMgr.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat)); if (!canOffBeRequired) { throw new InvalidParameterValueException("Availability can be " + - NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " - + Service.SourceNat.getName() + " enabled"); + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + + Service.SourceNat.getName() + " enabled", null); } // only one network offering in the system can be Required List offerings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (!offerings.isEmpty() && offerings.get(0).getId() != offeringToUpdate.getId()) { throw new InvalidParameterValueException("System already has network offering id=" + - offerings.get(0).getId() + " with availability " + Availability.Required); + offerings.get(0).getId() + " with availability " + Availability.Required); } } offering.setAvailability(availability); @@ -3607,33 +3610,33 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_MARK_DEFAULT_ZONE, eventDescription = "Marking account with the " + - "default zone", async=true) + "default zone", async=true) public AccountVO markDefaultZone(String accountName, long domainId, long defaultZoneId) { - - // Check if the account exists - Account account = _accountDao.findEnabledAccount(accountName, domainId); - if (account == null) { + + // Check if the account exists + Account account = _accountDao.findEnabledAccount(accountName, domainId); + if (account == null) { s_logger.error("Unable to find account by name: " + accountName + " in domain " + domainId); throw new InvalidParameterValueException("Account by name: " + accountName + " doesn't exist in domain " + domainId); } // Don't allow modification of system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Can not modify system account"); - } + throw new InvalidParameterValueException("Can not modify system account", null); + } - AccountVO acctForUpdate = _accountDao.findById(account.getId()); - - acctForUpdate.setDefaultZoneId(defaultZoneId); - - if (_accountDao.update(account.getId(), acctForUpdate)) { - UserContext.current().setEventDetails("Default zone id= " + defaultZoneId); - return _accountDao.findById(account.getId()); - } else { - return null; - } + AccountVO acctForUpdate = _accountDao.findById(account.getId()); + + acctForUpdate.setDefaultZoneId(defaultZoneId); + + if (_accountDao.update(account.getId(), acctForUpdate)) { + UserContext.current().setEventDetails("Default zone id= " + defaultZoneId); + return _accountDao.findById(account.getId()); + } else { + return null; + } } - + // Note: This method will be used for entity name validations in the coming // releases (place holder for now) private void validateEntityName(String str) { @@ -3646,7 +3649,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura char ch = str.charAt(i); for (int j = 0; j < searchChars.length; j++) { if (searchChars[j] == ch) { - throw new InvalidParameterValueException("Name cannot contain any of the following special characters:" + forbidden); + throw new InvalidParameterValueException("Name cannot contain any of the following special characters:" + forbidden, null); } } } @@ -3668,7 +3671,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // validate network offering information NetworkOffering no = getNetworkOffering(networkOfferingId); if (no == null) { - throw new InvalidParameterValueException("Unable to find network offering by id=" + networkOfferingId); + throw new InvalidParameterValueException("Unable to find network offering by id", null); } Integer networkRate; @@ -3761,31 +3764,31 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura public ClusterVO getCluster(long id) { return _clusterDao.findById(id); } - + @Override public AllocationState findClusterAllocationState(ClusterVO cluster){ - - if(cluster.getAllocationState() == AllocationState.Disabled){ - return AllocationState.Disabled; - }else if(ApiDBUtils.findPodById(cluster.getPodId()).getAllocationState() == AllocationState.Disabled){ - return AllocationState.Disabled; - }else { - DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); - return zone.getAllocationState(); - } + + if(cluster.getAllocationState() == AllocationState.Disabled){ + return AllocationState.Disabled; + }else if(ApiDBUtils.findPodById(cluster.getPodId()).getAllocationState() == AllocationState.Disabled){ + return AllocationState.Disabled; + }else { + DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); + return zone.getAllocationState(); + } } @Override public AllocationState findPodAllocationState(HostPodVO pod){ - - if(pod.getAllocationState() == AllocationState.Disabled){ - return AllocationState.Disabled; - }else { - DataCenterVO zone = ApiDBUtils.findZoneById(pod.getDataCenterId()); - return zone.getAllocationState(); - } + + if(pod.getAllocationState() == AllocationState.Disabled){ + return AllocationState.Disabled; + }else { + DataCenterVO zone = ApiDBUtils.findZoneById(pod.getDataCenterId()); + return zone.getAllocationState(); + } } - + private boolean allowIpRangeOverlap(VlanVO vlan, boolean forVirtualNetwork, long networkId) { // FIXME - delete restriction for virtual network in the future if (vlan.getVlanType() == VlanType.DirectAttached && !forVirtualNetwork) { @@ -3816,7 +3819,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // validate network offering information ServiceOffering offering = _serviceOfferingDao.findById(serviceOfferingId); if (offering == null) { - throw new InvalidParameterValueException("Unable to find service offering by id=" + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find service offering by id", null); } Integer networkRate; diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index a66aa4a9920..ee008041108 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -1308,7 +1308,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified.", null); } if ((volumeId != null) && (snapshotId != null)) { - throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")", null); + throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID or snapshot ID", null); } HypervisorType hyperType; @@ -1814,7 +1814,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters UserVmVO vmInstance = _vmDao.findById(vmId.longValue()); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find a virtual machine by id ", null); + throw new InvalidParameterValueException("unable to find a virtual machine by id", null); } _accountMgr.checkAccess(caller, null, true, vmInstance); @@ -2071,7 +2071,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (networkIdList == null || networkIdList.isEmpty()) { NetworkVO networkWithSecurityGroup = _networkMgr.getNetworkWithSecurityGroupEnabled(zone.getId()); if (networkWithSecurityGroup == null) { - throw new InvalidParameterValueException("No network with security enabled is found in zone id=" + zone.getId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy(zone, zone.getId(), "zoneId")); + throw new InvalidParameterValueException("No network with security enabled is found in zone with specified id", idList); } networkList.add(networkWithSecurityGroup); @@ -2089,11 +2091,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager NetworkVO network = _networkDao.findById(networkIdList.get(0).longValue()); if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); + throw new InvalidParameterValueException("Unable to find network by id", null); } if (!_networkMgr.isSecurityGroupSupportedInNetwork(network)) { - throw new InvalidParameterValueException("Network is not security group enabled: " + network.getId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, network.getId(), "networkId")); + throw new InvalidParameterValueException("Network with specified id is not security group enabled", idList); } networkList.add(network); @@ -2106,7 +2110,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager NetworkVO network = _networkDao.findById(networkId); if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); + throw new InvalidParameterValueException("Unable to find network by id", null); } boolean isSecurityGroupEnabled = _networkMgr.isSecurityGroupSupportedInNetwork(network); @@ -2201,7 +2205,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager defaultNetwork = virtualNetworks.get(0); } } else { - throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); + List idList = new ArrayList(); + idList.add(new IdentityProxy(requiredOfferings.get(0), requiredOfferings.get(0).getId(), "networkOfferingId")); + throw new InvalidParameterValueException("Required network offering with specified id is not in " + NetworkOffering.State.Enabled, idList); } networkList.add(defaultNetwork); @@ -2210,7 +2216,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager for (Long networkId : networkIdList) { NetworkVO network = _networkDao.findById(networkId); if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue()); + throw new InvalidParameterValueException("Unable to find network by id", null); } _networkMgr.checkNetworkPermissions(owner, network); @@ -2218,7 +2224,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //don't allow to use system networks NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); if (networkOffering.isSystemOnly()) { - throw new InvalidParameterValueException("Network id=" + networkId + " is system only and can't be used for vm deployment"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, networkId, "networkId")); + throw new InvalidParameterValueException("Network with specified id is system only and can't be used for vm deployment", idList); } networkList.add(network); } @@ -2265,7 +2273,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager for (Long securityGroupId : securityGroupIdList) { SecurityGroup sg = _securityGroupDao.findById(securityGroupId); if (sg == null) { - throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId); + throw new InvalidParameterValueException("Unable to find security group by id", null); } else { //verify permissions _accountMgr.checkAccess(caller, null, true, owner, sg); @@ -2282,15 +2290,15 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOffering.getId()); if (template.getTemplateType().equals(TemplateType.SYSTEM)) { - throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm"); + throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm", null); } List listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId()); if (listZoneTemplate == null || listZoneTemplate.isEmpty()) { - throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use"); + throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use", null); } boolean isIso = Storage.ImageFormat.ISO == template.getFormat(); if (isIso && !template.isBootable()) { - throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId()); + throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: ", null); } // Check templates permissions @@ -2306,7 +2314,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (isIso) { if (diskOfferingId == null) { - throw new InvalidParameterValueException("Installing from ISO requires a disk offering to be specified for the root disk."); + throw new InvalidParameterValueException("Installing from ISO requires a disk offering to be specified for the root disk.", null); } DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); if (diskOffering == null) { @@ -2359,7 +2367,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean vpcNetwork = false; for (NetworkVO network : networkList) { if (network.getDataCenterId() != zone.getId()) { - throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy(zone, zone.getId(), "zoneId")); + idList.add(new IdentityProxy(network, network.getId(), "networkId")); + throw new InvalidParameterValueException("Network with specified id doesn't belong to zone with specified id", idList); } String requestedIp = null; @@ -2384,11 +2395,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (_networkMgr.isSecurityGroupSupportedInNetwork(network)) { securityGroupEnabled = true; } - + //vm can't be a part of more than 1 VPC network if (network.getVpcId() != null) { if (vpcNetwork) { - throw new InvalidParameterValueException("Vm can't be a part of more than 1 VPC network"); + throw new InvalidParameterValueException("Vm can't be a part of more than 1 VPC network", null); } vpcNetwork = true; } @@ -2751,12 +2762,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // if account is removed, return error if (callerAccount != null && callerAccount.getRemoved() != null) { - throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed"); + throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed", null); } UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine by id ", null); + throw new InvalidParameterValueException("unable to find a virtual machine by id", null); } _accountMgr.checkAccess(callerAccount, null, true, vm); @@ -2764,7 +2775,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Account owner = _accountDao.findById(vm.getAccountId()); if (owner == null) { - throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId()); + throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId(), null); } if (owner.getState() == Account.State.disabled) { @@ -2779,7 +2790,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } destinationHost = _hostDao.findById(hostId); if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to deploy the VM, host id=" + hostId); + throw new InvalidParameterValueException("Unable to find the host to deploy the VM", null); } } @@ -3137,9 +3148,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager public HypervisorType getHypervisorTypeOfUserVM(long vmId) { UserVmVO userVm = _vmDao.findById(vmId); if (userVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); - ex.addProxyObject(userVm, vmId, "vmId"); - throw ex; + throw new InvalidParameterValueException("unable to find a virtual machine by id", null); } return userVm.getHypervisorType(); @@ -3174,23 +3183,23 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } if (vm.getState() != State.Stopped) { - InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to migrate the vm having the specified id"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("VM is not Stopped, unable to migrate the vm having the specified id", idList); } if (vm.getType() != VirtualMachine.Type.User) { - throw new InvalidParameterValueException("can only do storage migration on user vm"); + throw new InvalidParameterValueException("can only do storage migration on user vm", null); } List vols = _volsDao.findByInstance(vm.getId()); if (vols.size() > 1) { - throw new InvalidParameterValueException("Data disks attached to the vm, can not migrate. Need to dettach data disks at first"); + throw new InvalidParameterValueException("Data disks attached to the vm, can not migrate. Need to dettach data disks at first", null); } HypervisorType destHypervisorType = _clusterDao.findById(destPool.getClusterId()).getHypervisorType(); if (vm.getHypervisorType() != destHypervisorType) { - throw new InvalidParameterValueException("hypervisor is not compatible: dest: " + destHypervisorType.toString() + ", vm: " + vm.getHypervisorType().toString()); + throw new InvalidParameterValueException("hypervisor is not compatible: dest: " + destHypervisorType.toString() + ", vm: " + vm.getHypervisorType().toString(), null); } VMInstanceVO migratedVm = _itMgr.storageMigration(vm, destPool); return migratedVm; @@ -3211,14 +3220,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { - throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId); + throw new InvalidParameterValueException("Unable to find the VM by id", null); } // business logic if (vm.getState() != State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is not Running, unable to migrate the vm " + vm); } - InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Running, unable to migrate the vm with specified id"); + InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Running, unable to migrate the vm with specified id", null); ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -3226,7 +3235,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is not XenServer/VMware/KVM/Ovm, cannot migrate this VM."); } - throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM only"); + throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM only", null); } ServiceOfferingVO svcOffering = _serviceOfferingDao.findById(vm.getServiceOfferingId()); @@ -3234,18 +3243,18 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is using Local Storage, cannot migrate this VM."); } - throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate"); + throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate", null); } //check if migrating to same host long srcHostId = vm.getHostId(); if(destinationHost.getId() == srcHostId){ - throw new InvalidParameterValueException("Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM"); + throw new InvalidParameterValueException("Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM", null); } //check if host is UP if(destinationHost.getStatus() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled){ - throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: "+destinationHost.getStatus() + ", state: " +destinationHost.getResourceState()); + throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: "+destinationHost.getStatus() + ", state: " +destinationHost.getResourceState(), null); } // call to core process @@ -3279,71 +3288,77 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //VV 1: verify the two users Account caller = UserContext.current().getCaller(); if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && caller.getType() != Account.ACCOUNT_TYPE_DOMAIN_ADMIN){ // only root admin can assign VMs - throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType()); + throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType(), null); } //get and check the valid VM UserVmVO vm = _vmDao.findById(cmd.getVmId()); if (vm == null){ - throw new InvalidParameterValueException("There is no vm by that id " + cmd.getVmId()); + throw new InvalidParameterValueException("Couldn't find VM by id", null); } else if (vm.getState() == State.Running) { // VV 3: check if vm is running if (s_logger.isDebugEnabled()) { s_logger.debug("VM is Running, unable to move the vm " + vm); } - InvalidParameterValueException ex = new InvalidParameterValueException("VM is Running, unable to move the vm with specified vmId"); - ex.addProxyObject(vm, cmd.getVmId(), "vmId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, cmd.getVmId(), "vmId")); + throw new InvalidParameterValueException("VM is Running, unable to move the vm with specified vmId", idList); } Account oldAccount = _accountService.getActiveAccountById(vm.getAccountId()); if (oldAccount == null) { - throw new InvalidParameterValueException("Invalid account for VM " + vm.getAccountId() + " in domain."); + throw new InvalidParameterValueException("Invalid account for VM " + vm.getAccountId() + " in domain.", null); } //don't allow to move the vm from the project if (oldAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { - InvalidParameterValueException ex = new InvalidParameterValueException("Specified Vm id belongs to the project and can't be moved"); + InvalidParameterValueException ex = new InvalidParameterValueException("Specified Vm id belongs to the project and can't be moved", null); ex.addProxyObject(vm, cmd.getVmId(), "vmId"); throw ex; } Account newAccount = _accountService.getActiveAccountByName(cmd.getAccountName(), cmd.getDomainId()); if (newAccount == null || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain " + cmd.getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", cmd.getDomainId(), "domainId")); + throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain with specified id", idList); } if (newAccount.getState() == Account.State.disabled) { - throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled."); + throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled.", null); } // make sure the accounts are under same domain if (oldAccount.getDomainId() != newAccount.getDomainId()){ - throw new InvalidParameterValueException("The account should be under same domain for moving VM between two accounts. Old owner domain =" + oldAccount.getDomainId() + - " New owner domain=" + newAccount.getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", oldAccount.getDomainId(), "oldDomainId")); + idList.add(new IdentityProxy("domain", newAccount.getDomainId(), "newDomainId")); + throw new InvalidParameterValueException("The account should be under same domain for moving VM between two accounts. Old and new owner domain IDs are specified", idList); } // make sure the accounts are not same if (oldAccount.getAccountId() == newAccount.getAccountId()){ - throw new InvalidParameterValueException("The account should be same domain for moving VM between two accounts. Account id =" + oldAccount.getAccountId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy(oldAccount, oldAccount.getAccountId(), "accountId")); + throw new InvalidParameterValueException("The account with the specified id should be same domain for moving VM between two accounts.", idList); } // don't allow to move the vm if there are existing PF/LB/Static Nat rules, or vm is assigned to static Nat ip List pfrules = _portForwardingDao.listByVm(cmd.getVmId()); if (pfrules != null && pfrules.size() > 0){ - throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user.", null); } List snrules = _rulesDao.listStaticNatByVmId(vm.getId()); if (snrules != null && snrules.size() > 0){ - throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user.", null); } List maps = _loadBalancerVMMapDao.listByInstanceId(vm.getId()); if (maps != null && maps.size() > 0) { - throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user.", null); } // check for one on one nat IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(cmd.getVmId()); if (ip != null){ if (ip.isOneToOneNat()){ - throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString()); + throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString(), null); } } @@ -3407,7 +3422,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (zone.getNetworkType() == NetworkType.Basic) { if (networkIdList != null && !networkIdList.isEmpty()) { - throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM"); + throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM", null); } //cleanup the old security groups _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId()); @@ -3421,7 +3436,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Network defaultNetwork = _networkMgr.getExclusiveGuestNetwork(zone.getId()); if (defaultNetwork == null) { - throw new InvalidParameterValueException("Unable to find a default network to start a vm"); + throw new InvalidParameterValueException("Unable to find a default network to start a vm", null); } else { networkList.add(_networkDao.findById(defaultNetwork.getId())); } @@ -3429,7 +3444,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware); if (securityGroupIdList != null && isVmWare) { - throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor"); + throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor", null); } else if (!isVmWare && _networkMgr.isSecurityGroupSupportedInNetwork(defaultNetwork) && _networkMgr.canAddDefaultSecurityGroup()) { if (securityGroupIdList == null) { securityGroupIdList = new ArrayList(); @@ -3474,10 +3489,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.debug("AssignVM: Basic zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName() ); } else { if (zone.isSecurityGroupEnabled()) { - throw new InvalidParameterValueException("Not yet implemented for SecurityGroupEnabled advanced networks."); + throw new InvalidParameterValueException("Not yet implemented for SecurityGroupEnabled advanced networks.", null); } else { if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) { - throw new InvalidParameterValueException("Can't move vm with security groups; security group feature is not enabled in this zone"); + throw new InvalidParameterValueException("Can't move vm with security groups; security group feature is not enabled in this zone", null); } //cleanup the network for the oldOwner _networkMgr.cleanupNics(vmOldProfile); @@ -3490,9 +3505,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager for (Long networkId : networkIdList) { NetworkVO network = _networkDao.findById(networkId); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; + throw new InvalidParameterValueException("Unable to find specified network id", null); } _networkMgr.checkNetworkPermissions(newAccount, network); @@ -3500,9 +3513,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //don't allow to use system networks NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); if (networkOffering.isSystemOnly()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, networkId, "networkId")); + throw new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment", idList); } applicableNetworks.add(network); } @@ -3512,7 +3525,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { throw new InvalidParameterValueException("Unable to find network offering with availability=" - + Availability.Required + " to automatically create the network as a part of vm creation"); + + Availability.Required + " to automatically create the network as a part of vm creation", null); } PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); @@ -3529,13 +3542,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + - "for account " + newAccount + "; please specify networkIds"); + "for account " + newAccount + "; please specify networkIds", null); } else { defaultNetwork = virtualNetworks.get(0); } } else { - throw new InvalidParameterValueException("Required network offering id=" + - requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); + List idList = new ArrayList(); + idList.add(new IdentityProxy(requiredOfferings.get(0), requiredOfferings.get(0).getId(), "networkOfferingId")); + throw new InvalidParameterValueException("Required network offering with specified id is not in " + NetworkOffering.State.Enabled, idList); } applicableNetworks.add(defaultNetwork); @@ -3574,14 +3588,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long vmId = cmd.getVmId(); UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Cann not find VM with ID " + vmId); + InvalidParameterValueException ex = new InvalidParameterValueException("Cann not find VM by ID ", null); ex.addProxyObject(vm, vmId, "vmId"); throw ex; } Account owner = _accountDao.findById(vm.getAccountId()); if (owner == null) { - throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId()); + throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId(), null); } if (owner.getState() == Account.State.disabled) { @@ -3598,19 +3612,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List rootVols = _volsDao.findByInstance(vmId); if (rootVols.isEmpty()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can not find root volume for VM " + vmId); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("Can not find root volume for VM with specified id", idList); } VolumeVO root = rootVols.get(0); long templateId = root.getTemplateId(); VMTemplateVO template = _templateDao.findById(templateId); if (template == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template for specified volumeid and vmId"); - ex.addProxyObject(vm, vmId, "vmId"); - ex.addProxyObject(root, root.getId(), "volumeId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + idList.add(new IdentityProxy(root, root.getId(), "volumeId")); + throw new InvalidParameterValueException("Cannot find template for specified volumeid and vmId", idList); } if (needRestart) { diff --git a/utils/src/com/cloud/utils/IdentityProxy.java b/utils/src/com/cloud/utils/IdentityProxy.java index 567752e86ab..cf3d89039fc 100644 --- a/utils/src/com/cloud/utils/IdentityProxy.java +++ b/utils/src/com/cloud/utils/IdentityProxy.java @@ -12,23 +12,23 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.utils; - -public class IdentityProxy { - private String _tableName; - private Long _value; - private String _idFieldName; - - public IdentityProxy() { - } - - public IdentityProxy(String tableName) { - _tableName = tableName; - } - - public IdentityProxy(String tableName, Long id, String fieldName) { - setTableName(tableName); - setValue(id); - setIdFieldName(fieldName); + +public class IdentityProxy { + private String _tableName; + private Long _value; + private String _idFieldName; + + public IdentityProxy() { + } + + public IdentityProxy(String tableName) { + _tableName = tableName; + } + + public IdentityProxy(String tableName, Long id, String fieldName) { + setTableName(tableName); + setValue(id); + setIdFieldName(fieldName); } public IdentityProxy(Object vo, Long id, String fieldName) { @@ -42,29 +42,29 @@ public class IdentityProxy { } setValue(id); setIdFieldName(fieldName); - } - - public String getTableName() { - return _tableName; - } - - public void setTableName(String tableName) { - _tableName = tableName; - } - - public Long getValue() { - return _value; - } - - public void setValue(Long value) { - _value = value; - } - - public void setIdFieldName(String value) { - _idFieldName = value; - } - - public String getidFieldName() { - return _idFieldName; - } -} + } + + public String getTableName() { + return _tableName; + } + + public void setTableName(String tableName) { + _tableName = tableName; + } + + public Long getValue() { + return _value; + } + + public void setValue(Long value) { + _value = value; + } + + public void setIdFieldName(String value) { + _idFieldName = value; + } + + public String getidFieldName() { + return _idFieldName; + } +}