diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 4246e7f7534..0e6bd113827 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -207,6 +207,7 @@ import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.SSHKeyPairDao; import com.cloud.user.dao.UserDao; import com.cloud.utils.EnumUtils; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; @@ -223,7 +224,6 @@ import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.MacAddress; @@ -305,7 +305,7 @@ public class ManagementServerImpl implements ManagementServer { private final Adapters _hostAllocators; private final ConfigurationManager _configMgr; private final ResourceTagDao _resourceTagDao; - + @Inject ProjectManager _projectMgr; private final ResourceManager _resourceMgr; @@ -537,10 +537,10 @@ public class ManagementServerImpl implements ManagementServer { protected void checkPortParameters(String publicPort, String privatePort, String privateIp, String proto) { if (!NetUtils.isValidPort(publicPort)) { - throw new InvalidParameterValueException("publicPort is an invalid value"); + throw new InvalidParameterValueException("publicPort is an invalid value", null); } if (!NetUtils.isValidPort(privatePort)) { - throw new InvalidParameterValueException("privatePort is an invalid value"); + throw new InvalidParameterValueException("privatePort is an invalid value", null); } // s_logger.debug("Checking if " + privateIp + " is a valid private IP address. Guest IP address is: " + @@ -550,7 +550,7 @@ public class ManagementServerImpl implements ManagementServer { // throw new InvalidParameterValueException("Invalid private ip address"); // } if (!NetUtils.isValidProto(proto)) { - throw new InvalidParameterValueException("Invalid protocol"); + throw new InvalidParameterValueException("Invalid protocol", null); } } @@ -648,7 +648,7 @@ public class ManagementServerImpl implements ManagementServer { String vmTypeStr = cmd.getSystemVmType(); if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && isSystem) { - throw new InvalidParameterValueException("Only ROOT admins can access system's offering"); + throw new InvalidParameterValueException("Only ROOT admins can access system's offering", null); } // Keeping this logic consistent with domain specific zones @@ -663,14 +663,14 @@ public class ManagementServerImpl implements ManagementServer { // For non-root users if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { if (isSystem) { - throw new InvalidParameterValueException("Only root admins can access system's offering"); + throw new InvalidParameterValueException("Only root admins can access system's offering", null); } return searchServiceOfferingsInternal(caller, name, id, vmId, keyword, searchFilter); } // for root users, the existing flow if (caller.getDomainId() != 1 && isSystem) { // NON ROOT admin - throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering"); + throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering", null); } if (keyword != null) { @@ -682,9 +682,7 @@ public class ManagementServerImpl implements ManagementServer { } else if (vmId != null) { UserVmVO vmInstance = _userVmDao.findById(vmId); if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); - ex.addProxyObject(vmInstance, vmId, "vmId"); - throw ex; + throw new InvalidParameterValueException("unable to find virtual machine by id", null); } _accountMgr.checkAccess(caller, null, true, vmInstance); @@ -754,9 +752,7 @@ public class ManagementServerImpl implements ManagementServer { } else if (vmId != null) { UserVmVO vmInstance = _userVmDao.findById(vmId); if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); - ex.addProxyObject(vmInstance, vmId, "vmId"); - throw ex; + throw new InvalidParameterValueException("Unable to find a virtual machine by id", null); } _accountMgr.checkAccess(caller, null, false, vmInstance); @@ -801,20 +797,20 @@ public class ManagementServerImpl implements ManagementServer { return sol; } - + @Override public List searchForClusters(long zoneId, Long startIndex, Long pageSizeVal, String hypervisorType) { - Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal); - SearchCriteria sc = _clusterDao.createSearchCriteria(); - - zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); + Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal); + SearchCriteria sc = _clusterDao.createSearchCriteria(); - sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); - sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); - - return _clusterDao.search(sc, searchFilter); + zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); + + sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); + sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); + + return _clusterDao.search(sc, searchFilter); } - + @Override public List searchForClusters(ListClustersCmd cmd) { Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -899,18 +895,16 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; + 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"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("VM is not Running, unable to migrate the vm with specified id", idList); } if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) @@ -918,14 +912,14 @@ public class ManagementServerImpl implements ManagementServer { 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 = _offeringsDao.findById(vm.getServiceOfferingId()); if (svcOffering.getUseLocalStorage()) { 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); } long srcHostId = vm.getHostId(); // why is this not HostVO? @@ -934,10 +928,10 @@ public class ManagementServerImpl implements ManagementServer { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the host with id: " + srcHostId + " of this VM:" + vm); } - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the host (with specified id) of VM with specified id"); - ex.addProxyObject(srcHost, srcHostId, "hostId"); - ex.addProxyObject(vm, vmId, "vmId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(srcHost, srcHostId, "hostId")); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("Unable to find the host (with specified id) of VM with specified id", idList); } Long cluster = srcHost.getClusterId(); Type hostType = srcHost.getType(); @@ -987,7 +981,7 @@ public class ManagementServerImpl implements ManagementServer { private List searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, Object cluster, Object id, Object keyword, Object resourceState, Object haHosts) { Filter searchFilter = new Filter(HostVO.class, "id", Boolean.TRUE, startIndex, pageSize); - + SearchBuilder sb = _hostDao.createSearchBuilder(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); @@ -997,7 +991,7 @@ public class ManagementServerImpl implements ManagementServer { sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ); - + String haTag = _haMgr.getHaTag(); SearchBuilder hostTagSearch = null; if (haHosts != null && haTag != null && !haTag.isEmpty()) { @@ -1012,7 +1006,7 @@ public class ManagementServerImpl implements ManagementServer { hostTagSearch.cp(); sb.join("hostTagSearch", hostTagSearch, sb.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER); } - + SearchCriteria sc = sb.create(); if (keyword != null) { @@ -1050,7 +1044,7 @@ public class ManagementServerImpl implements ManagementServer { if (resourceState != null) { sc.setParameters("resourceState", resourceState); } - + if (haHosts != null && haTag != null && !haTag.isEmpty()) { sc.setJoinParameters("hostTagSearch", "tag", haTag); } @@ -1112,15 +1106,15 @@ public class ManagementServerImpl implements ManagementServer { if (accountName != null && domainId != null) { if (projectId != null) { - throw new InvalidParameterValueException("Account and projectId can't be specified together"); + throw new InvalidParameterValueException("Account and projectId can't be specified together", null); } Account account = _accountDao.findActiveAccount(accountName, domainId); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain"); + List idList = new ArrayList(); // Since we don't have a DomainVO object here, we directly set tablename to "domain". - String tablename = "domain"; - ex.addProxyObject(tablename, domainId, "domainId"); - throw ex; + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account " + accountName + + " in domain with specified domainId", idList); } else { accountId = account.getId(); } @@ -1138,9 +1132,7 @@ public class ManagementServerImpl implements ManagementServer { if (projectId != null) { Project project = _projectMgr.getProject(projectId); if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + throw new InvalidParameterValueException("Unable to find project by id ", null); } accountId = project.getProjectAccountId(); } @@ -1307,19 +1299,19 @@ public class ManagementServerImpl implements ManagementServer { if (templateId != null) { template = _templateDao.findById(templateId); if (template == null) { - throw new InvalidParameterValueException("Please specify a valid template ID."); + throw new InvalidParameterValueException("Please specify a valid template ID.", null); }// If ISO requested then it should be ISO. if (isIso && template.getFormat() != ImageFormat.ISO) { s_logger.error("Template Id " + templateId + " is not an ISO"); - InvalidParameterValueException ex = new InvalidParameterValueException("Specified Template Id is not an ISO"); + InvalidParameterValueException ex = new InvalidParameterValueException("Specified Template Id is not an ISO", null); ex.addProxyObject(template, templateId, "templateId"); throw ex; }// If ISO not requested then it shouldn't be an ISO. if (!isIso && template.getFormat() == ImageFormat.ISO) { s_logger.error("Incorrect format of the template id " + templateId); - InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id"); - ex.addProxyObject(template, templateId, "templateId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(template, templateId, "templateId")); + throw new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id", idList); } } @@ -1344,7 +1336,7 @@ public class ManagementServerImpl implements ManagementServer { templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags); - + for (Pair tmpltPair : templateZonePairSet2) { if (!templateZonePairSet.contains(new Pair(tmpltPair.first(), -1L))) { templateZonePairSet.add(tmpltPair); @@ -1401,16 +1393,14 @@ public class ManagementServerImpl implements ManagementServer { // verify that template exists VMTemplateVO template = _templateDao.findById(id); if (template == null || template.getRemoved() != null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id"); - ex.addProxyObject(template, id, "templateId"); - throw ex; + throw new InvalidParameterValueException("unable to find template/iso by id", null); } // Don't allow to modify system template if (id == Long.valueOf(1)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id"); - ex.addProxyObject(template, id, "templateId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(template, id, "templateId")); + throw new InvalidParameterValueException("Template/iso of specified id is a system template, and cannot be modified", idList); } // do a permission check @@ -1440,7 +1430,7 @@ public class ManagementServerImpl implements ManagementServer { try { imageFormat = ImageFormat.valueOf(format.toUpperCase()); } catch (IllegalArgumentException e) { - throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values())); + throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()), null); } template.setFormat(imageFormat); @@ -1450,7 +1440,7 @@ public class ManagementServerImpl implements ManagementServer { GuestOSVO guestOS = _guestOSDao.findById(guestOSId); if (guestOS == null) { - throw new InvalidParameterValueException("Please specify a valid guest OS ID."); + throw new InvalidParameterValueException("Please specify a valid guest OS ID.", null); } else { template.setGuestOSId(guestOSId); } @@ -1569,7 +1559,7 @@ public class ManagementServerImpl implements ManagementServer { if ((entryTime != null) && (duration != null)) { if (entryTime <= duration) { - throw new InvalidParameterValueException("Entry time must be greater than duration"); + throw new InvalidParameterValueException("Entry time must be greater than duration", null); } Calendar calMin = Calendar.getInstance(); Calendar calMax = Calendar.getInstance(); @@ -1628,7 +1618,7 @@ public class ManagementServerImpl implements ManagementServer { sb.and("podId", sb.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); - + if (forVpc != null) { if (forVpc) { sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL); @@ -1646,7 +1636,7 @@ public class ManagementServerImpl implements ManagementServer { sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } - + SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -1662,27 +1652,27 @@ public class ManagementServerImpl implements ManagementServer { if (name != null) { sc.setParameters("name", "%" + name + "%"); } - + if (id != null) { sc.setParameters("id", id); } - + if (state != null) { sc.setParameters("state", state); } - + if (zone != null) { sc.setParameters("dataCenterId", zone); } - + if (pod != null) { sc.setParameters("podId", pod); } - + if (hostId != null) { sc.setParameters("hostId", hostId); } - + if (networkId != null) { sc.setJoinParameters("nicSearch", "networkId", networkId); } @@ -1710,12 +1700,12 @@ public class ManagementServerImpl implements ManagementServer { Long vpcId = cmd.getVpcId(); Map tags = cmd.getTags(); - + Boolean isAllocated = cmd.isAllocatedOnly(); if (isAllocated == null) { isAllocated = Boolean.TRUE; } - + Filter searchFilter = new Filter(IPAddressVO.class, "address", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _publicIpAddressDao.createSearchBuilder(); Long domainId = null; @@ -1745,7 +1735,7 @@ public class ManagementServerImpl implements ManagementServer { sb.and("isStaticNat", sb.entity().isOneToOneNat(), SearchCriteria.Op.EQ); sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); - if (forLoadBalancing != null && (Boolean) forLoadBalancing) { + if (forLoadBalancing != null && forLoadBalancing) { SearchBuilder lbSearch = _loadbalancerDao.createSearchBuilder(); sb.join("lbSearch", lbSearch, sb.entity().getId(), lbSearch.entity().getSourceIpAddressId(), JoinType.INNER); sb.groupBy(sb.entity().getId()); @@ -1754,7 +1744,7 @@ public class ManagementServerImpl implements ManagementServer { if (keyword != null && address == null) { sb.and("addressLIKE", sb.entity().getAddress(), SearchCriteria.Op.LIKE); } - + if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); for (int count=0; count < tags.size(); count++) { @@ -1780,18 +1770,18 @@ public class ManagementServerImpl implements ManagementServer { VlanType vlanType = null; if (forVirtualNetwork != null) { - vlanType = (Boolean) forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; + vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; } else { vlanType = VlanType.VirtualNetwork; } SearchCriteria sc = sb.create(); if (isAllocated) { - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); } sc.setJoinParameters("vlanSearch", "vlanType", vlanType); - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.PublicIpAddress.toString()); @@ -1809,7 +1799,7 @@ public class ManagementServerImpl implements ManagementServer { if (vpcId != null) { sc.setParameters("vpcId", vpcId); } - + if (ipId != null) { sc.setParameters("id", ipId); } @@ -1862,11 +1852,11 @@ public class ManagementServerImpl implements ManagementServer { if (osCategoryId != null) { sc.addAnd("categoryId", SearchCriteria.Op.EQ, osCategoryId); } - + if (description != null) { sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + description + "%"); } - + if (keyword != null) { sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } @@ -1886,11 +1876,11 @@ public class ManagementServerImpl implements ManagementServer { if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); } - + if (name != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - + if (keyword != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } @@ -1977,12 +1967,10 @@ public class ManagementServerImpl implements ManagementServer { // check if domain exists in the system DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id"); - ex.addProxyObject(domain, domainId, "domainId"); - throw ex; + throw new InvalidParameterValueException("Unable to find domain by id", null); } else if (domain.getParent() == null && domainName != null) { // check if domain is ROOT domain - and deny to edit it with the new name - throw new InvalidParameterValueException("ROOT domain can not be edited with a new name"); + throw new InvalidParameterValueException("ROOT domain can not be edited with a new name", null); } // check permissions @@ -1998,9 +1986,9 @@ public class ManagementServerImpl implements ManagementServer { boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId); if (!domains.isEmpty() && !sameDomain) { - InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system"); - ex.addProxyObject(domain, domainId, "domainId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system", idList); } } @@ -2009,7 +1997,7 @@ public class ManagementServerImpl implements ManagementServer { 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); } } @@ -2099,7 +2087,7 @@ public class ManagementServerImpl implements ManagementServer { Long clusterId = cmd.getClusterId(); if (clusterId != null) { - throw new InvalidParameterValueException("Currently clusterId param is not suppoerted"); + throw new InvalidParameterValueException("Currently clusterId param is not suppoerted", null); } zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); List summedCapacities = new ArrayList(); @@ -2146,7 +2134,7 @@ public class ManagementServerImpl implements ManagementServer { try { pageSize = Integer.valueOf(cmd.getPageSizeVal().toString()); } catch (IllegalArgumentException e) { - throw new InvalidParameterValueException("pageSize " + cmd.getPageSizeVal() + " is out of Integer range is not supported for this call"); + throw new InvalidParameterValueException("pageSize " + cmd.getPageSizeVal() + " is out of Integer range is not supported for this call", null); } summedCapacities = summedCapacities.subList(0, summedCapacities.size() < cmd.getPageSizeVal() ? summedCapacities.size() : pageSize); @@ -2232,11 +2220,11 @@ public class ManagementServerImpl implements ManagementServer { } else if (zoneId != null) { dcList.add(ApiDBUtils.findZoneById(zoneId)); } else { - if (clusterId != null){ - zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId(); - }else{ - zoneId = ApiDBUtils.findPodById(podId).getDataCenterId(); - } + if (clusterId != null){ + zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId(); + }else{ + zoneId = ApiDBUtils.findPodById(podId).getDataCenterId(); + } if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_STORAGE) { capacities.add(_storageMgr.getStoragePoolUsedStats(null, clusterId, podId, zoneId)); } @@ -2704,9 +2692,7 @@ public class ManagementServerImpl implements ManagementServer { public VirtualMachine.Type findSystemVMTypeById(long instanceId) { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId"); - ex.addProxyObject(systemVm, instanceId, "instanceId"); - throw ex; + throw new InvalidParameterValueException("Unable to find system vm by Id", null); } return systemVm.getType(); } @@ -2716,9 +2702,7 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(vmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, vmId, "vmId"); - throw ex; + throw new InvalidParameterValueException("unable to find system vm by id", null); } if (systemVm.getType() == VirtualMachine.Type.ConsoleProxy) { @@ -2726,9 +2710,7 @@ public class ManagementServerImpl implements ManagementServer { } else if (systemVm.getType() == VirtualMachine.Type.SecondaryStorageVm) { return startSecondaryStorageVm(vmId); } else { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, vmId, "vmId"); - throw ex; + throw new InvalidParameterValueException("Unable to find system vm by Id", null); } } @@ -2739,9 +2721,7 @@ public class ManagementServerImpl implements ManagementServer { // verify parameters VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(id, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, id, "vmId"); - throw ex; + throw new InvalidParameterValueException("unable to find system vm by Id", null); } try { @@ -2761,9 +2741,7 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, cmd.getId(), "vmId"); - throw ex; + throw new InvalidParameterValueException("unable to find system vm by Id", null); } if (systemVm.getType().equals(VirtualMachine.Type.ConsoleProxy)) { @@ -2778,9 +2756,7 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, cmd.getId(), "vmId"); - throw ex; + throw new InvalidParameterValueException("unable to find a system vm by Id", null); } if (systemVm.getType().equals(VirtualMachine.Type.ConsoleProxy)) { @@ -2816,9 +2792,7 @@ public class ManagementServerImpl implements ManagementServer { // verify that user exists User user = _accountMgr.getUserIncludingRemoved(userId); if ((user == null) || (user.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id"); - ex.addProxyObject(user, userId, "userId"); - throw ex; + throw new InvalidParameterValueException("Unable to find active user by Id", null); } // check permissions @@ -2865,7 +2839,7 @@ public class ManagementServerImpl implements ManagementServer { supportELB = networkType; } } - + long diskOffMaxSize = Long.valueOf(_configDao.getValue(Config.CustomDiskOfferingMaxSize.key())); String userPublicTemplateEnabled = _configs.get(Config.AllowPublicUserTemplates.key()); @@ -2877,7 +2851,7 @@ public class ManagementServerImpl implements ManagementServer { capabilities.put("projectInviteRequired", _projectMgr.projectInviteRequired()); capabilities.put("allowusercreateprojects", _projectMgr.allowUserToCreateProject()); capabilities.put("customDiskOffMaxSize", diskOffMaxSize); - + return capabilities; } @@ -2902,19 +2876,17 @@ public class ManagementServerImpl implements ManagementServer { VolumeVO volume = _volumeDao.findById(volumeId); if (volume == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId"); - ex.addProxyObject(volume, volumeId, "volumeId"); - throw ex; + throw new InvalidParameterValueException("Unable to find volume by Id", null); } // perform permission check _accountMgr.checkAccess(account, null, true, volume); if (_dcDao.findById(zoneId) == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + throw new InvalidParameterValueException("Please specify a valid zone.", null); } if (volume.getPoolId() == null) { - throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it"); + throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it", null); } // Extract activity only for detached volumes or for volumes whose instance is stopped if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) { @@ -2931,8 +2903,8 @@ public class ManagementServerImpl implements ManagementServer { boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global // admins are always allowed to extract - PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted"); - ex.addProxyObject(volume, volumeId, "volumeId"); + PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted"); + ex.addProxyObject(volume, volumeId, "volumeId"); throw ex; } } @@ -2940,7 +2912,7 @@ public class ManagementServerImpl implements ManagementServer { Upload.Mode extractMode; if (mode == null || (!mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString()))) { - throw new InvalidParameterValueException("Please specify a valid extract Mode "); + throw new InvalidParameterValueException("Please specify a valid extract Mode ", null); } else { extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD; } @@ -3068,9 +3040,7 @@ public class ManagementServerImpl implements ManagementServer { // Verify input parameters InstanceGroupVO group = _vmGroupDao.findById(groupId.longValue()); if (group == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a vm group with specified groupId"); - ex.addProxyObject(group, groupId, "groupId"); - throw ex; + throw new InvalidParameterValueException("unable to find a vm group by Id", null); } _accountMgr.checkAccess(caller, null, true, group); @@ -3079,7 +3049,7 @@ public class ManagementServerImpl implements ManagementServer { boolean isNameInUse = _vmGroupDao.isNameInUse(group.getAccountId(), groupName); if (isNameInUse && !group.getName().equals(groupName)) { - throw new InvalidParameterValueException("Unable to update vm group, a group with name " + groupName + " already exists for account"); + throw new InvalidParameterValueException("Unable to update vm group, a group with name " + groupName + " already exists for account", null); } if (groupName != null) { @@ -3185,21 +3155,21 @@ public class ManagementServerImpl implements ManagementServer { @DB public String uploadCertificate(UploadCustomCertificateCmd cmd) { if (cmd.getPrivateKey() != null && cmd.getAlias() != null) { - throw new InvalidParameterValueException("Can't change the alias for private key certification"); + throw new InvalidParameterValueException("Can't change the alias for private key certification", null); } if (cmd.getPrivateKey() == null) { if (cmd.getAlias() == null) { - throw new InvalidParameterValueException("alias can't be empty, if it's a certification chain"); + throw new InvalidParameterValueException("alias can't be empty, if it's a certification chain", null); } if (cmd.getCertIndex() == null) { - throw new InvalidParameterValueException("index can't be empty, if it's a certifciation chain"); + throw new InvalidParameterValueException("index can't be empty, if it's a certifciation chain", null); } } if (cmd.getPrivateKey() != null && !_ksMgr.validateCertificate(cmd.getCertificate(), cmd.getPrivateKey(), cmd.getDomainSuffix())) { - throw new InvalidParameterValueException("Failed to pass certificate validation check"); + throw new InvalidParameterValueException("Failed to pass certificate validation check", null); } if (cmd.getPrivateKey() != null) { @@ -3268,7 +3238,7 @@ public class ManagementServerImpl implements ManagementServer { SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s != null) { - throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' already exists."); + throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' already exists.", null); } SSHKeysHelper keys = new SSHKeysHelper(); @@ -3292,9 +3262,9 @@ public class ManagementServerImpl implements ManagementServer { SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + " in specified domain id"); - ex.addProxyObject(owner, owner.getDomainId(), "domainId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(owner, owner.getDomainId(), "domainId")); + throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + " in specified domain id", idList); } return _sshKeyPairDao.deleteByName(caller.getAccountId(), caller.getDomainId(), cmd.getName()); @@ -3339,14 +3309,14 @@ public class ManagementServerImpl implements ManagementServer { SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s != null) { - throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' already exists."); + throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' already exists.", null); } String name = cmd.getName(); String publicKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(cmd.getPublicKey()); if (publicKey == null) { - throw new InvalidParameterValueException("Public key is invalid"); + throw new InvalidParameterValueException("Public key is invalid", null); } String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(publicKey); @@ -3375,9 +3345,7 @@ public class ManagementServerImpl implements ManagementServer { UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); - ex.addProxyObject(vm, cmd.getId(), "vmId"); - throw ex; + throw new InvalidParameterValueException("Could not find VM by id", null); } // make permission check @@ -3386,9 +3354,9 @@ public class ManagementServerImpl implements ManagementServer { _userVmDao.loadDetails(vm); String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { - InvalidParameterValueException ex = new InvalidParameterValueException("No password for VM with specified id found."); - ex.addProxyObject(vm, cmd.getId(), "vmId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, cmd.getId(), "vmId")); + throw new InvalidParameterValueException("No password for VM with specified id found.", idList); } return password; @@ -3398,19 +3366,19 @@ public class ManagementServerImpl implements ManagementServer { @DB public boolean updateHostPassword(UpdateHostPasswordCmd cmd) { if (cmd.getClusterId() == null && cmd.getHostId() == null) { - throw new InvalidParameterValueException("You should provide one of cluster id or a host id."); + throw new InvalidParameterValueException("You should provide one of cluster id or a host id.", null); } else if (cmd.getClusterId() == null) { HostVO host = _hostDao.findById(cmd.getHostId()); if (host != null && host.getHypervisorType() == HypervisorType.XenServer) { - throw new InvalidParameterValueException("You should provide cluster id for Xenserver cluster."); + throw new InvalidParameterValueException("You should provide cluster id for Xenserver cluster.", null); } else { - throw new InvalidParameterValueException("This operation is not supported for this hypervisor type"); + throw new InvalidParameterValueException("This operation is not supported for this hypervisor type", null); } } else { ClusterVO cluster = ApiDBUtils.findClusterById(cmd.getClusterId()); if (cluster == null || cluster.getHypervisorType() != HypervisorType.XenServer) { - throw new InvalidParameterValueException("This operation is not supported for this hypervisor type"); + throw new InvalidParameterValueException("This operation is not supported for this hypervisor type", null); } // get all the hosts in this cluster List hosts = _resourceMgr.listAllHostsInCluster(cmd.getClusterId()); @@ -3430,7 +3398,7 @@ public class ManagementServerImpl implements ManagementServer { } else { // if one host in the cluster has diff username then rollback to maintain consistency txn.rollback(); - throw new InvalidParameterValueException("The username is not same for all hosts, please modify passwords for individual hosts."); + throw new InvalidParameterValueException("The username is not same for all hosts, please modify passwords for individual hosts.", null); } } txn.commit(); @@ -3492,9 +3460,7 @@ public class ManagementServerImpl implements ManagementServer { HypervisorCapabilitiesVO hpvCapabilities = _hypervisorCapabilitiesDao.findById(id, true); if (hpvCapabilities == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find the hypervisor capabilities for specified id"); - ex.addProxyObject(hpvCapabilities, id, "Id"); - throw ex; + throw new InvalidParameterValueException("unable to find the hypervisor capabilities by id", null); } boolean updateNeeded = (maxGuestsLimit != null || securityGroupEnabled != null); @@ -3520,8 +3486,8 @@ public class ManagementServerImpl implements ManagementServer { return null; } } - - + + @Override public VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd) { Long systemVmId = cmd.getId(); @@ -3531,16 +3497,16 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(systemVmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - throw new InvalidParameterValueException("Unable to find SystemVm with id " + systemVmId); + throw new InvalidParameterValueException("Unable to find SystemVm by id", null); } _accountMgr.checkAccess(caller, null, true, systemVm); - + // Check that the specified service offering ID is valid _itMgr.checkIfCanUpgrade(systemVm, serviceOfferingId); boolean result = _itMgr.upgradeVmDb(systemVmId, serviceOfferingId); - + if (result) { return _vmInstanceDao.findById(systemVmId); } else { diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 9fb8a081f2c..f45e0ced711 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -165,6 +165,7 @@ import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; import com.cloud.utils.EnumUtils; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; @@ -346,7 +347,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag protected BigDecimal _overProvisioningFactor = new BigDecimal(1); private long _maxVolumeSizeInGb; private long _serverId; - private StateMachine2 _volStateMachine; + private final StateMachine2 _volStateMachine; private int _customDiskOfferingMinSize = 1; private int _customDiskOfferingMaxSize = 1024; @@ -723,31 +724,31 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag @DB public VolumeVO copyVolumeFromSecToPrimary(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId, ServiceOfferingVO offering, DiskOfferingVO diskOffering, List avoids, long size, HypervisorType hyperType) throws NoTransitionException { - - final HashSet avoidPools = new HashSet(avoids); - DiskProfile dskCh = createDiskCharacteristics(volume, template, dc, diskOffering); - dskCh.setHyperType(vm.getHypervisorType()); - // Find a suitable storage to create volume on - StoragePoolVO destPool = findStoragePool(dskCh, dc, pod, clusterId, vm, avoidPools); - - // Copy the volume from secondary storage to the destination storage pool - VolumeHostVO volumeHostVO = _volumeHostDao.findByVolumeId(volume.getId()); - HostVO secStorage = _hostDao.findById(volumeHostVO.getHostId()); - String secondaryStorageURL = secStorage.getStorageUrl(); - String[] volumePath = volumeHostVO.getInstallPath().split("/"); - String volumeUUID = volumePath[volumePath.length - 1].split("\\.")[0]; - + + final HashSet avoidPools = new HashSet(avoids); + DiskProfile dskCh = createDiskCharacteristics(volume, template, dc, diskOffering); + dskCh.setHyperType(vm.getHypervisorType()); + // Find a suitable storage to create volume on + StoragePoolVO destPool = findStoragePool(dskCh, dc, pod, clusterId, vm, avoidPools); + + // Copy the volume from secondary storage to the destination storage pool + VolumeHostVO volumeHostVO = _volumeHostDao.findByVolumeId(volume.getId()); + HostVO secStorage = _hostDao.findById(volumeHostVO.getHostId()); + String secondaryStorageURL = secStorage.getStorageUrl(); + String[] volumePath = volumeHostVO.getInstallPath().split("/"); + String volumeUUID = volumePath[volumePath.length - 1].split("\\.")[0]; + CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volumeUUID, destPool, secondaryStorageURL, false, _copyvolumewait); CopyVolumeAnswer cvAnswer; - try { + try { cvAnswer = (CopyVolumeAnswer) sendToPool(destPool, cvCmd); } catch (StorageUnavailableException e1) { - stateTransitTo(volume, Event.CopyFailed); + stateTransitTo(volume, Event.CopyFailed); throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); } if (cvAnswer == null || !cvAnswer.getResult()) { - stateTransitTo(volume, Event.CopyFailed); + stateTransitTo(volume, Event.CopyFailed); throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); } Transaction txn = Transaction.currentTxn(); @@ -761,11 +762,11 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), null, volume.getSize()); _usageEventDao.persist(usageEvent); _volumeHostDao.remove(volumeHostVO.getId()); - txn.commit(); - return volume; - + txn.commit(); + return volume; + } - + @Override @DB public VolumeVO createVolume(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId, ServiceOfferingVO offering, DiskOfferingVO diskOffering, @@ -1204,7 +1205,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag Map ds = cmd.getDetails(); if (clusterId != null && podId == null) { - throw new InvalidParameterValueException("Cluster id requires pod id"); + throw new InvalidParameterValueException("Cluster id requires pod id", null); } Map details = new HashMap(); @@ -1225,7 +1226,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag Long zoneId = cmd.getZoneId(); DataCenterVO zone = _dcDao.findById(cmd.getZoneId()); if (zone == null) { - throw new InvalidParameterValueException("unable to find zone by id " + zoneId); + throw new InvalidParameterValueException("unable to find zone by id", null); } // Check if zone is disabled Account account = UserContext.current().getCaller(); @@ -1242,26 +1243,26 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag try { uri = new URI(cmd.getUrl()); if (uri.getScheme() == null) { - throw new InvalidParameterValueException("scheme is null " + cmd.getUrl() + ", add nfs:// as a prefix"); + throw new InvalidParameterValueException("scheme is null " + cmd.getUrl() + ", add nfs:// as a prefix", null); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { String uriHost = uri.getHost(); String uriPath = uri.getPath(); if (uriHost == null || uriPath == null || uriHost.trim().isEmpty() || uriPath.trim().isEmpty()) { - throw new InvalidParameterValueException("host or path is null, should be nfs://hostname/path"); + throw new InvalidParameterValueException("host or path is null, should be nfs://hostname/path", null); } } else if (uri.getScheme().equalsIgnoreCase("sharedMountPoint")) { String uriPath = uri.getPath(); if (uriPath == null) { - throw new InvalidParameterValueException("host or path is null, should be sharedmountpoint://localhost/path"); + throw new InvalidParameterValueException("host or path is null, should be sharedmountpoint://localhost/path", null); } } else if (uri.getScheme().equalsIgnoreCase("clvm")) { String uriPath = uri.getPath(); if (uriPath == null) { - throw new InvalidParameterValueException("host or path is null, should be clvm://localhost/path"); + throw new InvalidParameterValueException("host or path is null, should be clvm://localhost/path", null); } } } catch (URISyntaxException e) { - throw new InvalidParameterValueException(cmd.getUrl() + " is not a valid uri"); + throw new InvalidParameterValueException(cmd.getUrl() + " is not a valid uri", null); } String tags = cmd.getTags(); @@ -1464,12 +1465,14 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag StoragePoolVO sPool = _storagePoolDao.findById(id); if (sPool == null) { s_logger.warn("Unable to find pool:" + id); - throw new InvalidParameterValueException("Unable to find pool by id " + id); + throw new InvalidParameterValueException("Unable to find pool by id", null); } if (sPool.getPoolType().equals(StoragePoolType.LVM) || sPool.getPoolType().equals(StoragePoolType.EXT)) { s_logger.warn("Unable to delete local storage id:" + id); - throw new InvalidParameterValueException("Unable to delete local storage id: " + id); + List idList = new ArrayList(); + idList.add(new IdentityProxy(sPool, id, "storageId")); + throw new InvalidParameterValueException("Unable to delete local storage id", idList); } Pair vlms = _volsDao.getCountAndTotalByPool(id); @@ -1491,10 +1494,10 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // If it does , then you cannot delete the pool if (vlms.first() > 0) { throw new CloudRuntimeException("Cannot delete pool " + sPool.getName() + " as there are associated vols" + - " for this pool"); + " for this pool"); } } - + // First get the host_id from storage_pool_host_ref for given pool id StoragePoolVO lock = _storagePoolDao.acquireInLockTable(sPool.getId()); @@ -1690,7 +1693,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag return _volsDao.findById(volume.getId()); } - + /* * Upload the volume to secondary storage. * @@ -1699,19 +1702,19 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag @DB @ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPLOAD, eventDescription = "uploading volume", async = true) public VolumeVO uploadVolume(UploadVolumeCmd cmd) throws ResourceAllocationException{ - Account caller = UserContext.current().getCaller(); + Account caller = UserContext.current().getCaller(); long ownerId = cmd.getEntityOwnerId(); Long zoneId = cmd.getZoneId(); String volumeName = cmd.getVolumeName(); String url = cmd.getUrl(); String format = cmd.getFormat(); - - validateVolume(caller, ownerId, zoneId, volumeName, url, format); - VolumeVO volume = persistVolume(caller, ownerId, zoneId, volumeName, url, cmd.getFormat()); - _downloadMonitor.downloadVolumeToStorage(volume, zoneId, url, cmd.getChecksum(), ImageFormat.valueOf(format.toUpperCase())); - return volume; + + validateVolume(caller, ownerId, zoneId, volumeName, url, format); + VolumeVO volume = persistVolume(caller, ownerId, zoneId, volumeName, url, cmd.getFormat()); + _downloadMonitor.downloadVolumeToStorage(volume, zoneId, url, cmd.getChecksum(), ImageFormat.valueOf(format.toUpperCase())); + return volume; } - + private boolean validateVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url, String format) throws ResourceAllocationException{ // permission check @@ -1719,87 +1722,87 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // Check that the resource limit for volumes won't be exceeded _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.volume); - + // Verify that zone exists DataCenterVO zone = _dcDao.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); } // Check if zone is disabled if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId); } - - if (url.toLowerCase().contains("file://")) { - throw new InvalidParameterValueException("File:// type urls are currently unsupported"); - } - - ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase()); - if (imgfmt == null) { - throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); - } - + + if (url.toLowerCase().contains("file://")) { + throw new InvalidParameterValueException("File:// type urls are currently unsupported", null); + } + + ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase()); + if (imgfmt == null) { + throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); + } + String userSpecifiedName = volumeName; if (userSpecifiedName == null) { userSpecifiedName = getRandomVolumeName(); } - if((!url.toLowerCase().endsWith("vhd"))&&(!url.toLowerCase().endsWith("vhd.zip")) - &&(!url.toLowerCase().endsWith("vhd.bz2"))&&(!url.toLowerCase().endsWith("vhd.gz")) - &&(!url.toLowerCase().endsWith("qcow2"))&&(!url.toLowerCase().endsWith("qcow2.zip")) - &&(!url.toLowerCase().endsWith("qcow2.bz2"))&&(!url.toLowerCase().endsWith("qcow2.gz")) - &&(!url.toLowerCase().endsWith("ova"))&&(!url.toLowerCase().endsWith("ova.zip")) - &&(!url.toLowerCase().endsWith("ova.bz2"))&&(!url.toLowerCase().endsWith("ova.gz")) - &&(!url.toLowerCase().endsWith("img"))&&(!url.toLowerCase().endsWith("raw"))){ - throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase()); - } - - if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith(".vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase().endsWith("vhd.gz") )) - || (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith(".qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz") )) - || (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith(".ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase().endsWith("ova.gz"))) - || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith(".img") && !url.toLowerCase().endsWith("raw")))) { - throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase()); - } - validateUrl(url); - - return false; - } - - private String validateUrl(String url){ - try { - URI uri = new URI(url); - if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") - && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { - throw new IllegalArgumentException("Unsupported scheme for url: " + url); - } + if((!url.toLowerCase().endsWith("vhd"))&&(!url.toLowerCase().endsWith("vhd.zip")) + &&(!url.toLowerCase().endsWith("vhd.bz2"))&&(!url.toLowerCase().endsWith("vhd.gz")) + &&(!url.toLowerCase().endsWith("qcow2"))&&(!url.toLowerCase().endsWith("qcow2.zip")) + &&(!url.toLowerCase().endsWith("qcow2.bz2"))&&(!url.toLowerCase().endsWith("qcow2.gz")) + &&(!url.toLowerCase().endsWith("ova"))&&(!url.toLowerCase().endsWith("ova.zip")) + &&(!url.toLowerCase().endsWith("ova.bz2"))&&(!url.toLowerCase().endsWith("ova.gz")) + &&(!url.toLowerCase().endsWith("img"))&&(!url.toLowerCase().endsWith("raw"))){ + throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase(), null); + } - int port = uri.getPort(); - if (!(port == 80 || port == 443 || port == -1)) { - throw new IllegalArgumentException("Only ports 80 and 443 are allowed"); - } - String host = uri.getHost(); - try { - InetAddress hostAddr = InetAddress.getByName(host); - if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) { - throw new IllegalArgumentException("Illegal host specified in url"); - } - if (hostAddr instanceof Inet6Address) { - throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); - } - } catch (UnknownHostException uhe) { - throw new IllegalArgumentException("Unable to resolve " + host); - } - - return uri.toString(); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid URL " + url); - } - + if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith(".vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase().endsWith("vhd.gz") )) + || (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith(".qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz") )) + || (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith(".ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase().endsWith("ova.gz"))) + || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith(".img") && !url.toLowerCase().endsWith("raw")))) { + throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase(), null); + } + validateUrl(url); + + return false; } - + + private String validateUrl(String url){ + try { + URI uri = new URI(url); + if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") + && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { + throw new IllegalArgumentException("Unsupported scheme for url: " + url); + } + + int port = uri.getPort(); + if (!(port == 80 || port == 443 || port == -1)) { + throw new IllegalArgumentException("Only ports 80 and 443 are allowed"); + } + String host = uri.getHost(); + try { + InetAddress hostAddr = InetAddress.getByName(host); + if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) { + throw new IllegalArgumentException("Illegal host specified in url"); + } + if (hostAddr instanceof Inet6Address) { + throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); + } + } catch (UnknownHostException uhe) { + throw new IllegalArgumentException("Unable to resolve " + host); + } + + return uri.toString(); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid URL " + url); + } + + } + private VolumeVO persistVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url, String format) { - + Transaction txn = Transaction.currentTxn(); txn.start(); @@ -1818,21 +1821,21 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag volume = _volsDao.persist(volume); try { - stateTransitTo(volume, Event.UploadRequested); - } catch (NoTransitionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + stateTransitTo(volume, Event.UploadRequested); + } catch (NoTransitionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } UserContext.current().setEventDetails("Volume Id: " + volume.getId()); // Increment resource count during allocation; if actual creation fails, decrement it _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume); txn.commit(); - return volume; - } - - + return volume; + } + + /* * Just allocate a volume in the database, don't send the createvolume cmd to hypervisor. The volume will be finally * created @@ -1859,7 +1862,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // validate input parameters before creating the volume if ((cmd.getSnapshotId() == null && cmd.getDiskOfferingId() == null) || (cmd.getSnapshotId() != null && cmd.getDiskOfferingId() != null)) { - throw new InvalidParameterValueException("Either disk Offering Id or snapshot Id must be passed whilst creating volume"); + throw new InvalidParameterValueException("Either disk Offering Id or snapshot Id must be passed whilst creating volume", null); } if (cmd.getSnapshotId() == null) {// create a new volume @@ -1871,29 +1874,29 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (size > 0) { size = size * 1024 * 1024 * 1024; // user specify size in GB } else { - throw new InvalidParameterValueException("Disk size must be larger than 0"); + throw new InvalidParameterValueException("Disk size must be larger than 0", null); } } if (diskOfferingId == null) { - throw new InvalidParameterValueException("Missing parameter(s),either a positive volume size or a valid disk offering id must be specified."); + throw new InvalidParameterValueException("Missing parameter(s),either a positive volume size or a valid disk offering id must be specified.", null); } // Check that the the disk offering is specified DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); if ((diskOffering == null) || diskOffering.getRemoved() != null || !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) { - throw new InvalidParameterValueException("Please specify a valid disk offering."); + throw new InvalidParameterValueException("Please specify a valid disk offering.", null); } if (diskOffering.isCustomized()) { if (size == null) { - throw new InvalidParameterValueException("This disk offering requires a custom size specified"); + throw new InvalidParameterValueException("This disk offering requires a custom size specified", null); } if ((sizeInGB < _customDiskOfferingMinSize) || (sizeInGB > _customDiskOfferingMaxSize)) { - throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + _customDiskOfferingMaxSize + " Min:" + _customDiskOfferingMinSize); + throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + _customDiskOfferingMaxSize + " Min:" + _customDiskOfferingMinSize, null); } } if (!diskOffering.isCustomized() && size != null) { - throw new InvalidParameterValueException("This disk offering does not allow custom size"); + throw new InvalidParameterValueException("This disk offering does not allow custom size", null); } if (diskOffering.getDomainId() == null) { @@ -1907,17 +1910,20 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } if (!validateVolumeSizeRange(size)) {// convert size from mb to gb for validation - throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size + " ,max volume size is:" + _maxVolumeSizeInGb); + throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size + " ,max volume size is:" + _maxVolumeSizeInGb, null); } } else { // create volume from snapshot Long snapshotId = cmd.getSnapshotId(); SnapshotVO snapshotCheck = _snapshotDao.findById(snapshotId); if (snapshotCheck == null) { - throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId); + throw new InvalidParameterValueException("unable to find a snapshot by id", null); } if (snapshotCheck.getStatus() != Snapshot.Status.BackedUp) { - throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for volume creation"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(snapshotCheck, snapshotId, "snapshotId")); + throw new InvalidParameterValueException("Snapshot with specified snapshotId is not in " + + Snapshot.Status.BackedUp + " state yet and can't be used for volume creation", idList); } diskOfferingId = (cmd.getDiskOfferingId() != null) ? cmd.getDiskOfferingId() : snapshotCheck.getDiskOfferingId(); @@ -1941,7 +1947,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // Verify that zone exists DataCenterVO zone = _dcDao.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); } // Check if zone is disabled @@ -1961,11 +1967,14 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // Check that there is at least one host in the specified zone List hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByType(Host.Type.Routing, zoneId); if (hosts.isEmpty()) { - throw new InvalidParameterValueException("There is no workable host in data center id " + zoneId + ", please check hosts' agent status and see if they are disabled"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(zone, zoneId, "zoneId")); + throw new InvalidParameterValueException("There is no workable host in data center with specified zoneId, " + + "please check hosts' agent status and see if they are disabled", idList); } if (!sharedPoolExists) { - throw new InvalidParameterValueException("Please specify a zone that has at least one shared primary storage pool."); + throw new InvalidParameterValueException("Please specify a zone that has at least one shared primary storage pool.", null); } String userSpecifiedName = cmd.getVolumeName(); @@ -2102,7 +2111,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (capacities.size() == 0) { CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), storagePool.getClusterId(), allocated, totalOverProvCapacity, capacityType); CapacityState capacityState = _configMgr.findClusterAllocationState(ApiDBUtils.findClusterById(storagePool.getClusterId())) == AllocationState.Disabled ? - CapacityState.Disabled : CapacityState.Enabled; + CapacityState.Disabled : CapacityState.Enabled; capacity.setCapacityState(capacityState); _capacityDao.persist(capacity); } else { @@ -2123,7 +2132,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag s_logger.debug("Successfully set Capacity - " + totalOverProvCapacity + " for capacity type - " + capacityType + " , DataCenterId - " + storagePool.getDataCenterId() + ", HostOrPoolId - " + storagePool.getId() + ", PodId " + storagePool.getPodId()); } - + @Override public List getUpHostsInPool(long poolId) { SearchCriteria sc = UpHostsInPoolSearch.create(); @@ -2362,7 +2371,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag s_logger.warn("problem cleaning up snapshots in secondary storage " + secondaryStorageHost, e2); } } - + //CleanUp volumes on Secondary Storage. for (HostVO secondaryStorageHost : secondaryStorageHosts) { try { @@ -2390,7 +2399,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag _volumeHostDao.remove(destroyedVolumeHostVO.getId()); } } - + }catch (Exception e2) { s_logger.warn("problem cleaning up volumes in secondary storage " + secondaryStorageHost, e2); } @@ -2437,7 +2446,10 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } if (!primaryStorage.getStatus().equals(StoragePoolStatus.Up) && !primaryStorage.getStatus().equals(StoragePoolStatus.ErrorInMaintenance)) { - throw new InvalidParameterValueException("Primary storage with id " + primaryStorageId + " is not ready for migration, as the status is:" + primaryStorage.getStatus().toString()); + List idList = new ArrayList(); + idList.add(new IdentityProxy(primaryStorage, primaryStorageId, "storageId")); + throw new InvalidParameterValueException("Primary storage with specified storageId is not ready for " + + "migration, as the status is:" + primaryStorage.getStatus().toString(), idList); } List hosts = _resourceMgr.listHostsInClusterByStatus(primaryStorage.getClusterId(), Status.Up); @@ -2812,11 +2824,11 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // Check that the volume ID is valid VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { - throw new InvalidParameterValueException("Unable to aquire volume with ID: " + volumeId); + throw new InvalidParameterValueException("Unable to find volume by ID", null); } if (!_snapshotMgr.canOperateOnVolume(volume)) { - throw new InvalidParameterValueException("There are snapshot creating on it, Unable to delete the volume"); + throw new InvalidParameterValueException("There are snapshot creating on it, Unable to delete the volume", null); } // permission check @@ -2824,17 +2836,17 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // Check that the volume is not currently attached to any VM if (volume.getInstanceId() != null) { - throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM."); + throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.", null); } // Check that volume is completely Uploaded if (volume.getState() == Volume.State.UploadOp){ - VolumeHostVO volumeHost = _volumeHostDao.findByVolumeId(volume.getId()); + VolumeHostVO volumeHost = _volumeHostDao.findByVolumeId(volume.getId()); if (volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS){ - throw new InvalidParameterValueException("Please specify a volume that is not uploading"); + throw new InvalidParameterValueException("Please specify a volume that is not uploading", null); } } - + // Check that the volume is not already destroyed if (volume.getState() != Volume.State.Destroy) { if (!destroyVolume(volume)) { @@ -2854,9 +2866,9 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag private boolean validateVolumeSizeRange(long size) { if (size < 0 || (size > 0 && size < (1024 * 1024 * 1024))) { - throw new InvalidParameterValueException("Please specify a size of at least 1 Gb."); + throw new InvalidParameterValueException("Please specify a size of at least 1 Gb.", null); } else if (size > (_maxVolumeSizeInGb * 1024 * 1024 * 1024)) { - throw new InvalidParameterValueException("volume size " + size + ", but the maximum size allowed is " + _maxVolumeSizeInGb + " Gb."); + throw new InvalidParameterValueException("volume size " + size + ", but the maximum size allowed is " + _maxVolumeSizeInGb + " Gb.", null); } return true; @@ -2984,24 +2996,24 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag public Volume migrateVolume(Long volumeId, Long storagePoolId) throws ConcurrentOperationException { VolumeVO vol = _volsDao.findById(volumeId); if (vol == null) { - throw new InvalidParameterValueException("Failed to find the volume id: " + volumeId); + throw new InvalidParameterValueException("Failed to find volume by id", null); } if (vol.getState() != Volume.State.Ready) { - throw new InvalidParameterValueException("Volume must be in ready state"); + throw new InvalidParameterValueException("Volume must be in ready state", null); } if (vol.getInstanceId() != null) { - throw new InvalidParameterValueException("Volume needs to be dettached from VM"); + throw new InvalidParameterValueException("Volume needs to be dettached from VM", null); } StoragePool destPool = _storagePoolDao.findById(storagePoolId); if (destPool == null) { - throw new InvalidParameterValueException("Failed to find the destination storage pool: " + storagePoolId); + throw new InvalidParameterValueException("Failed to find the destination storage pool by id", null); } if (!volumeOnSharedStoragePool(vol)) { - throw new InvalidParameterValueException("Migration of volume from local storage pool is not supported"); + throw new InvalidParameterValueException("Migration of volume from local storage pool is not supported", null); } List vols = new ArrayList(); @@ -3195,8 +3207,8 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag assignedPool = dest.getStorageForDisks().get(vol); } if (assignedPool == null && recreate) { - assignedPool = _storagePoolDao.findById(vol.getPoolId()); - + assignedPool = _storagePoolDao.findById(vol.getPoolId()); + } if (assignedPool != null || recreate) { Volume.State state = vol.getState(); @@ -3234,7 +3246,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); vm.addDisk(new VolumeTO(vol, pool)); } - + } } } else { @@ -3253,10 +3265,10 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag VolumeVO newVol; StoragePool existingPool = null; if (recreate && (dest.getStorageForDisks() == null || dest.getStorageForDisks().get(vol) == null)) { - existingPool = _storagePoolDao.findById(vol.getPoolId()); - s_logger.debug("existing pool: " + existingPool.getId()); + existingPool = _storagePoolDao.findById(vol.getPoolId()); + s_logger.debug("existing pool: " + existingPool.getId()); } - + if (vol.getState() == Volume.State.Allocated || vol.getState() == Volume.State.Creating) { newVol = vol; } else { @@ -3345,12 +3357,12 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (toBeCreated.getTemplateId() != null) { template = _templateDao.findById(toBeCreated.getTemplateId()); } - + StoragePool pool = null; if (sPool != null) { - pool = sPool; + pool = sPool; } else { - pool = dest.getStorageForDisks().get(toBeCreated); + pool = dest.getStorageForDisks().get(toBeCreated); } if (pool != null) { @@ -3416,27 +3428,27 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (s_logger.isDebugEnabled()) { s_logger.debug("Expunging " + vol); } - + //Find out if the volume is present on secondary storage VolumeHostVO volumeHost = _volumeHostDao.findByVolumeId(vol.getId()); if(volumeHost != null){ - if (volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED){ - HostVO ssHost = _hostDao.findById(volumeHost.getHostId()); - DeleteVolumeCommand dtCommand = new DeleteVolumeCommand(ssHost.getStorageUrl(), volumeHost.getInstallPath()); - Answer answer = _agentMgr.sendToSecStorage(ssHost, dtCommand); - if (answer == null || !answer.getResult()) { - s_logger.debug("Failed to delete " + volumeHost + " due to " + ((answer == null) ? "answer is null" : answer.getDetails())); - return; - } - }else if(volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS){ - s_logger.debug("Volume: " + vol.getName() + " is currently being uploaded; cant' delete it."); - throw new CloudRuntimeException("Please specify a volume that is not currently being uploaded."); - } + if (volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED){ + HostVO ssHost = _hostDao.findById(volumeHost.getHostId()); + DeleteVolumeCommand dtCommand = new DeleteVolumeCommand(ssHost.getStorageUrl(), volumeHost.getInstallPath()); + Answer answer = _agentMgr.sendToSecStorage(ssHost, dtCommand); + if (answer == null || !answer.getResult()) { + s_logger.debug("Failed to delete " + volumeHost + " due to " + ((answer == null) ? "answer is null" : answer.getDetails())); + return; + } + }else if(volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS){ + s_logger.debug("Volume: " + vol.getName() + " is currently being uploaded; cant' delete it."); + throw new CloudRuntimeException("Please specify a volume that is not currently being uploaded."); + } _volumeHostDao.remove(volumeHost.getId()); _volumeDao.remove(vol.getId()); - return; + return; } - + String vmName = null; if (vol.getVolumeType() == Type.ROOT && vol.getInstanceId() != null) { VirtualMachine vm = _vmInstanceDao.findByIdIncludingRemoved(vol.getInstanceId()); @@ -3481,7 +3493,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } catch (RuntimeException ex) { if (force) { s_logger.info("Failed to expunge volume, but marking volume id=" + vol.getId() + " as expunged anyway " + - "due to force=true. Volume failed to expunge due to ", ex); + "due to force=true. Volume failed to expunge due to ", ex); removeVolume = true; } else { throw ex; @@ -3714,25 +3726,27 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag public Host updateSecondaryStorage(long secStorageId, String newUrl) { HostVO secHost = _hostDao.findById(secStorageId); if (secHost == null) { - throw new InvalidParameterValueException("Can not find out the secondary storage id: " + secStorageId); + throw new InvalidParameterValueException("Can not find secondary storage by id", null); } if (secHost.getType() != Host.Type.SecondaryStorage) { - throw new InvalidParameterValueException("host: " + secStorageId + " is not a secondary storage"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(secHost, secStorageId, "storageId")); + throw new InvalidParameterValueException("host with specified storageId is not secondary storage", idList); } URI uri = null; try { uri = new URI(UriUtils.encodeURIComponent(newUrl)); if (uri.getScheme() == null) { - throw new InvalidParameterValueException("uri.scheme is null " + newUrl + ", add nfs:// as a prefix"); + throw new InvalidParameterValueException("uri.scheme is null " + newUrl + ", add nfs:// as a prefix", null); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) { - throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path"); + throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path", null); } } } catch (URISyntaxException e) { - throw new InvalidParameterValueException(newUrl + " is not a valid uri"); + throw new InvalidParameterValueException(newUrl + " is not a valid uri", null); } String oldUrl = secHost.getStorageUrl(); @@ -3741,7 +3755,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag try { oldUri = new URI(UriUtils.encodeURIComponent(oldUrl)); if (!oldUri.getScheme().equalsIgnoreCase(uri.getScheme())) { - throw new InvalidParameterValueException("can not change old scheme:" + oldUri.getScheme() + " to " + uri.getScheme()); + throw new InvalidParameterValueException("can not change old scheme:" + oldUri.getScheme() + " to " + uri.getScheme(), null); } } catch (URISyntaxException e) { s_logger.debug("Failed to get uri from " + oldUrl); @@ -3804,7 +3818,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag vmSearch.and("type", vmSearch.entity().getType(), SearchCriteria.Op.NIN); vmSearch.or("nulltype", vmSearch.entity().getType(), SearchCriteria.Op.NULL); sb.join("vmSearch", vmSearch, sb.entity().getInstanceId(), vmSearch.entity().getId(), JoinBuilder.JoinType.LEFTOUTER); - + if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); for (int count=0; count < tags.size(); count++) { @@ -3834,7 +3848,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } sc.setJoinParameters("diskOfferingSearch", "systemUse", 1); - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Volume.toString()); @@ -3887,14 +3901,14 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag return null; } } - + @Override public HypervisorType getHypervisorTypeFromFormat(ImageFormat format) { - - if(format == null) { + + if(format == null) { return HypervisorType.None; - } - + } + if (format == ImageFormat.VHD) { return HypervisorType.XenServer; } else if (format == ImageFormat.OVA) { @@ -3907,5 +3921,5 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag return HypervisorType.None; } } - + } diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index 50ac4bf7f46..2ad5f0dcbdf 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -103,6 +103,7 @@ import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.utils.DateUtil; import com.cloud.utils.DateUtil.IntervalType; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; @@ -185,7 +186,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma private VolumeDao _volumeDao; @Inject private ResourceTagDao _resourceTagDao; - + String _name; private int _totalRetries; private int _pauseInterval; @@ -295,7 +296,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId()); ManageSnapshotCommand cmd = new ManageSnapshotCommand(snapshotId, volume.getPath(), srcPool, preSnapshotPath, snapshot.getName(), vmName); - + ManageSnapshotAnswer answer = (ManageSnapshotAnswer) sendToPool(volume, cmd); // Update the snapshot in the database if ((answer != null) && answer.getResult()) { @@ -313,7 +314,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma _snapshotDao.update(snapshotId, snapshot); } else { long preSnapshotId = 0; - + if (preSnapshotVO != null && preSnapshotVO.getBackupSnapshotId() != null) { preSnapshotId = preId; // default delta snap number is 16 @@ -337,12 +338,12 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma preSnapshotId = 0; } } - + //If the volume is moved around, backup a full snapshot to secondary storage if (volume.getLastPoolId() != null && !volume.getLastPoolId().equals(volume.getPoolId())) { - preSnapshotId = 0; - volume.setLastPoolId(volume.getPoolId()); - _volumeDao.update(volume.getId(), volume); + preSnapshotId = 0; + volume.setLastPoolId(volume.getPoolId()); + _volumeDao.update(volume.getId(), volume); } snapshot = updateDBOnCreate(snapshotId, answer.getSnapshotPath(), preSnapshotId); } @@ -380,12 +381,14 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot); - throw new InvalidParameterValueException("No such volume exist"); + throw new InvalidParameterValueException("No such volume exists", null); } - + if (volume.getState() != Volume.State.Ready) { _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot); - throw new InvalidParameterValueException("Volume is not in ready state"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(volume, volumeId, "volumeId")); + throw new InvalidParameterValueException("Volume with specified id is not in ready state", idList); } SnapshotVO snapshot = null; @@ -400,7 +403,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma s_logger.debug("Decrementing the resource count for account: " + snapshotOwner.getAccountName() + ", access failed"); throw pe; } - + try { Long poolId = volume.getPoolId(); @@ -409,11 +412,11 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } if (_volsDao.getHypervisorType(volume.getId()).equals(HypervisorType.KVM)) { - uservm = _vmDao.findById(volume.getInstanceId()); - if (uservm != null && uservm.getType() != VirtualMachine.Type.User) { - throw new CloudRuntimeException("Can't take a snapshot on system vm "); - } - + uservm = _vmDao.findById(volume.getInstanceId()); + if (uservm != null && uservm.getType() != VirtualMachine.Type.User) { + throw new CloudRuntimeException("Can't take a snapshot on system vm "); + } + StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId()); ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId()); List hosts = _resourceMgr.listAllHostsInCluster(cluster.getId()); @@ -435,10 +438,10 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma throw new CloudRuntimeException("Creating snapshot failed due to volume:" + volumeId + " is associated with vm:" + userVm.getInstanceName() + " is in " + userVm.getState().toString() + " state"); } - + if(userVm.getHypervisorType() == HypervisorType.VMware || userVm.getHypervisorType() == HypervisorType.KVM) { - List activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.Status.Creating, Snapshot.Status.CreatedOnPrimary, Snapshot.Status.BackingUp); - if(activeSnapshots.size() > 1) + List activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.Status.Creating, Snapshot.Status.CreatedOnPrimary, Snapshot.Status.BackingUp); + if(activeSnapshots.size() > 1) throw new CloudRuntimeException("There is other active snapshot tasks on the instance to which the volume is attached, please try again later"); } } @@ -591,7 +594,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } catch (Exception e) { throw new CloudRuntimeException("downloadSnapshotsFromSwift failed due to " + e.toString()); } - + } @@ -614,9 +617,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma String primaryStoragePoolNameLabel = _storageMgr.getPrimaryStorageNameLabel(volume); Long dcId = volume.getDataCenterId(); Long accountId = volume.getAccountId(); - + HostVO secHost = getSecHost(volumeId, volume.getDataCenterId()); - + String secondaryStoragePoolUrl = secHost.getStorageUrl(); String snapshotUuid = snapshot.getPath(); // In order to verify that the snapshot is not empty, @@ -628,7 +631,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma SwiftTO swift = _swiftMgr.getSwiftTO(); - + long prevSnapshotId = snapshot.getPrevSnapshotId(); if (prevSnapshotId > 0) { prevSnapshot = _snapshotDao.findByIdIncludingRemoved(prevSnapshotId); @@ -651,7 +654,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if ( swift != null ) { backupSnapshotCommand.setSwift(swift); } - + String backedUpSnapshotUuid = null; // By default, assume failed. boolean backedUp = false; @@ -718,7 +721,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma public void postCreateSnapshot(Long volumeId, Long snapshotId, Long policyId, boolean backedUp) { Long userId = getSnapshotUserId(); SnapshotVO snapshot = _snapshotDao.findById(snapshotId); - + if (snapshot != null && snapshot.isRecursive()) { postCreateRecurringSnapshotForPolicy(userId, volumeId, snapshotId, policyId); } @@ -740,8 +743,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma long oldSnapId = oldestSnapshot.getId(); s_logger.debug("Max snaps: " + policy.getMaxSnaps() + " exceeded for snapshot policy with Id: " + policyId + ". Deleting oldest snapshot: " + oldSnapId); if(deleteSnapshotInternal(oldSnapId)){ - //log Snapshot delete event - EventUtils.saveEvent(User.UID_SYSTEM, oldestSnapshot.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_SNAPSHOT_DELETE, "Successfully deleted oldest snapshot: " + oldSnapId, 0); + //log Snapshot delete event + EventUtils.saveEvent(User.UID_SYSTEM, oldestSnapshot.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_SNAPSHOT_DELETE, "Successfully deleted oldest snapshot: " + oldSnapId, 0); } snaps.remove(oldestSnapshot); } @@ -756,15 +759,17 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma // Verify parameters Snapshot snapshotCheck = _snapshotDao.findById(snapshotId); if (snapshotCheck == null) { - throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId); + throw new InvalidParameterValueException("unable to find snapshot by id", null); } - + _accountMgr.checkAccess(caller, null, true, snapshotCheck); - + if( !Status.BackedUp.equals(snapshotCheck.getStatus() ) ) { - throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is not in BackedUp Status"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(snapshotCheck, snapshotId, "snapshotId")); + throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is not in BackedUp Status", idList); } - + return deleteSnapshotInternal(snapshotId); } @@ -787,8 +792,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma txn.start(); _snapshotDao.remove(snapshotId); if (snapshot.getStatus() == Snapshot.Status.BackedUp) { - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_DELETE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, 0L); - _usageEventDao.persist(usageEvent); + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_SNAPSHOT_DELETE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, 0L); + _usageEventDao.persist(usageEvent); } _resourceLimitMgr.decrementResourceCount(snapshot.getAccountId(), ResourceType.snapshot); txn.commit(); @@ -913,7 +918,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma String snapshotTypeStr = cmd.getSnapshotType(); String intervalTypeStr = cmd.getIntervalType(); Map tags = cmd.getTags(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -926,11 +931,11 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(SnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _snapshotDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -941,18 +946,18 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("snapshotTypeEQ", sb.entity().getsnapshotType(), SearchCriteria.Op.IN); sb.and("snapshotTypeNEQ", sb.entity().getsnapshotType(), SearchCriteria.Op.NEQ); - + if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); + SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); + for (int count=0; count < tags.size(); count++) { + tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); + tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); + tagSearch.cp(); + } + tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.groupBy(sb.entity().getId()); + sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); - } SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -960,7 +965,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (volumeId != null) { sc.setParameters("volumeId", volumeId); } - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Snapshot.toString()); @@ -986,9 +991,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } if (snapshotTypeStr != null) { - Type snapshotType = SnapshotVO.getSnapshotType((String) snapshotTypeStr); + Type snapshotType = SnapshotVO.getSnapshotType(snapshotTypeStr); if (snapshotType == null) { - throw new InvalidParameterValueException("Unsupported snapshot type " + snapshotTypeStr); + throw new InvalidParameterValueException("Unsupported snapshot type " + snapshotTypeStr, null); } if (snapshotType == Type.RECURRING) { sc.setParameters("snapshotTypeEQ", Type.HOURLY.ordinal(), Type.DAILY.ordinal(), Type.WEEKLY.ordinal(), Type.MONTHLY.ordinal()); @@ -996,9 +1001,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma sc.setParameters("snapshotTypeEQ", snapshotType.ordinal()); } } else if (intervalTypeStr != null && volumeId != null) { - Type type = SnapshotVO.getSnapshotType((String) intervalTypeStr); + Type type = SnapshotVO.getSnapshotType(intervalTypeStr); if (type == null) { - throw new InvalidParameterValueException("Unsupported snapstho interval type " + intervalTypeStr); + throw new InvalidParameterValueException("Unsupported snapstho interval type " + intervalTypeStr, null); } sc.setParameters("snapshotTypeEQ", type.ordinal()); } else { @@ -1092,19 +1097,23 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma Long volumeId = cmd.getVolumeId(); VolumeVO volume = _volsDao.findById(cmd.getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Failed to create snapshot policy, unable to find a volume with id " + volumeId); + throw new InvalidParameterValueException("Failed to create snapshot policy, unable to find volume by id", null); } - + _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume); - + if (volume.getState() != Volume.State.Ready) { - throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot."); + List idList = new ArrayList(); + idList.add(new IdentityProxy(volume, volumeId, "volumeId")); + throw new InvalidParameterValueException("Specified VolumeId is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.", idList); } if (volume.getTemplateId() != null ) { VMTemplateVO template = _templateDao.findById(volume.getTemplateId()); if( template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM ) { - throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(volume, volumeId, "volumeId")); + throw new InvalidParameterValueException("Specified VolumeId is for System VM , Creating snapshot against System VM volumes is not supported", idList); } } @@ -1114,12 +1123,12 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma // It is not detached, but attached to a VM if (_vmDao.findById(instanceId) == null) { // It is not a UserVM but a SystemVM or DomR - throw new InvalidParameterValueException("Failed to create snapshot policy, snapshots of volumes attached to System or router VM are not allowed"); + throw new InvalidParameterValueException("Failed to create snapshot policy, snapshots of volumes attached to System or router VM are not allowed", null); } } IntervalType intvType = DateUtil.IntervalType.getIntervalType(cmd.getIntervalType()); if (intvType == null) { - throw new InvalidParameterValueException("Unsupported interval type " + cmd.getIntervalType()); + throw new InvalidParameterValueException("Unsupported interval type " + cmd.getIntervalType(), null); } Type type = getSnapshotType(intvType); @@ -1131,16 +1140,16 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma try { DateUtil.getNextRunTime(intvType, cmd.getSchedule(), timezoneId, null); } catch (Exception e) { - throw new InvalidParameterValueException("Invalid schedule: " + cmd.getSchedule() + " for interval type: " + cmd.getIntervalType()); + throw new InvalidParameterValueException("Invalid schedule: " + cmd.getSchedule() + " for interval type: " + cmd.getIntervalType(), null); } if (cmd.getMaxSnaps() <= 0) { - throw new InvalidParameterValueException("maxSnaps should be greater than 0"); + throw new InvalidParameterValueException("maxSnaps should be greater than 0", null); } int intervalMaxSnaps = type.getMax(); if (cmd.getMaxSnaps() > intervalMaxSnaps) { - throw new InvalidParameterValueException("maxSnaps exceeds limit: " + intervalMaxSnaps + " for interval type: " + cmd.getIntervalType()); + throw new InvalidParameterValueException("maxSnaps exceeds limit: " + intervalMaxSnaps + " for interval type: " + cmd.getIntervalType(), null); } // Verify that max doesn't exceed domain and account snapshot limits @@ -1148,12 +1157,12 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma long domainLimit = _resourceLimitMgr.findCorrectResourceLimitForDomain(_domainMgr.getDomain(owner.getDomainId()), ResourceType.snapshot); int max = cmd.getMaxSnaps().intValue(); if (owner.getType() != Account.ACCOUNT_TYPE_ADMIN && ((accountLimit != -1 && max > accountLimit) || (domainLimit != -1 && max > domainLimit))) { - String message = "domain/account"; - if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) { - message = "domain/project"; - } - - throw new InvalidParameterValueException("Max number of snapshots shouldn't exceed the " + message + " level snapshot limit"); + String message = "domain/account"; + if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) { + message = "domain/project"; + } + + throw new InvalidParameterValueException("Max number of snapshots shouldn't exceed the " + message + " level snapshot limit", null); } SnapshotPolicyVO policy = _snapshotPolicyDao.findOneByVolumeInterval(volumeId, intvType); @@ -1192,7 +1201,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma Long volumeId = cmd.getVolumeId(); VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { - throw new InvalidParameterValueException("Unable to find a volume with id " + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id", null); } _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume); return listPoliciesforVolume(cmd.getVolumeId()); @@ -1253,7 +1262,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma // Verify parameters VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { - throw new InvalidParameterValueException("Failed to list snapshot schedule, unable to find a volume with id " + volumeId); + throw new InvalidParameterValueException("Failed to list snapshot schedule, unable to find volume by id", null); } if (account != null) { @@ -1313,41 +1322,48 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma @Override public SnapshotVO allocSnapshot(Long volumeId, Long policyId) throws ResourceAllocationException { Account caller = UserContext.current().getCaller(); - + VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { - throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist"); + throw new InvalidParameterValueException("Creating snapshot failed due to volume:volume doesn't exist", null); } DataCenter zone = _dcDao.findById(volume.getDataCenterId()); if (zone == null) { - throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId()); + throw new InvalidParameterValueException("Can't find zone by id ", null); } - + if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName()); } - + if (volume.getState() != Volume.State.Ready) { - throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot."); + List idList = new ArrayList(); + idList.add(new IdentityProxy(volume, volumeId, "volumeId")); + throw new InvalidParameterValueException("Specified VolumeId is not in " + Volume.State.Ready + " state, but " + + " in state " + volume.getState() + ". Cannot take snapshot.", idList); } if ( volume.getTemplateId() != null ) { VMTemplateVO template = _templateDao.findById(volume.getTemplateId()); if( template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM ) { - throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(volume, volumeId, "volumeId")); + throw new InvalidParameterValueException("Specified VolumeId is for System VM , Creating snapshot against System VM volumes is not supported", idList); } } - + StoragePoolVO storagePoolVO = _storagePoolDao.findById(volume.getPoolId()); if (storagePoolVO == null) { - throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(volume, volumeId, "volumeId")); + throw new InvalidParameterValueException("Please attach volume of specified ID to a VM before create snapshot for it", idList); } ClusterVO cluster = _clusterDao.findById(storagePoolVO.getClusterId()); if (cluster != null && cluster.getHypervisorType() == HypervisorType.Ovm) { - throw new InvalidParameterValueException("Ovm won't support taking snapshot"); + throw new InvalidParameterValueException("Ovm won't support taking snapshot", null); } - + // Verify permissions _accountMgr.checkAccess(caller, null, true, volume); Type snapshotType = getSnapshotType(policyId); @@ -1355,17 +1371,17 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma try{ //synchronize the resource count synchronized (this) { - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot); - //Increment the resourceCount - _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.snapshot); - s_logger.debug("Incrementing the snapshot resource count for account : " + owner.getAccountName()); + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot); + //Increment the resourceCount + _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.snapshot); + s_logger.debug("Incrementing the snapshot resource count for account : " + owner.getAccountName()); } } catch (ResourceAllocationException e){ if (snapshotType != Type.MANUAL){ String msg = "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots"; s_logger.warn(msg); _alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg, - "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit"); + "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit"); } throw e; } @@ -1407,7 +1423,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (configDao == null) { throw new ConfigurationException("Unable to get the configuration dao."); } - + String value = configDao.getValue(Config.BackupSnapshotWait.toString()); _backupsnapshotwait = NumbersUtil.parseInt(value, Integer.parseInt(Config.BackupSnapshotWait.getDefaultValue())); @@ -1446,7 +1462,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma Long userId = getSnapshotUserId(); if ((policyId == null) && (policyIds == null)) { - throw new InvalidParameterValueException("No policy id (or list of ids) specified."); + throw new InvalidParameterValueException("No policy id (or list of ids) specified.", null); } if (policyIds == null) { @@ -1454,17 +1470,17 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma policyIds.add(policyId); } else if (policyIds.size() <= 0) { // Not even sure how this is even possible - throw new InvalidParameterValueException("There are no policy ids"); + throw new InvalidParameterValueException("There are no policy ids", null); } for (Long policy : policyIds) { SnapshotPolicyVO snapshotPolicyVO = _snapshotPolicyDao.findById(policy); if (snapshotPolicyVO == null) { - throw new InvalidParameterValueException("Policy id given: " + policy + " does not exist"); + throw new InvalidParameterValueException("Couldn't find policy by id", null); } VolumeVO volume = _volsDao.findById(snapshotPolicyVO.getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Policy id given: " + policy + " does not belong to a valid volume"); + throw new InvalidParameterValueException("Policy id given: " + policy + " does not belong to a valid volume", null); } _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume); @@ -1473,7 +1489,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma boolean success = true; if (policyIds.contains(Snapshot.MANUAL_POLICY_ID)) { - throw new InvalidParameterValueException("Invalid Policy id given: " + Snapshot.MANUAL_POLICY_ID); + throw new InvalidParameterValueException("Invalid Policy id given: " + Snapshot.MANUAL_POLICY_ID, null); } for (Long pId : policyIds) { @@ -1504,14 +1520,14 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } return false; } - + @Override public boolean canOperateOnVolume(VolumeVO volume) { - List snapshots = _snapshotDao.listByStatus(volume.getId(), Status.Creating, Status.CreatedOnPrimary, Status.BackingUp); - if (snapshots.size() > 0) { - return false; - } - return true; + List snapshots = _snapshotDao.listByStatus(volume.getId(), Status.Creating, Status.CreatedOnPrimary, Status.BackingUp); + if (snapshots.size() > 0) { + return false; + } + return true; } } diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java index 14a67dd5fbd..4db68a3d032 100644 --- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java +++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java @@ -72,10 +72,10 @@ import com.cloud.vm.dao.UserVmDao; public class TaggedResourceManagerImpl implements TaggedResourceService, Manager{ public static final Logger s_logger = Logger.getLogger(TaggedResourceManagerImpl.class); private String _name; - + private static Map> _daoMap= new HashMap>(); - + @Inject AccountManager _accountMgr; @Inject @@ -150,21 +150,21 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager return _name; } - + private Long getResourceId(String resourceId, TaggedResourceType resourceType) { GenericDao dao = _daoMap.get(resourceType); if (dao == null) { throw new CloudRuntimeException("Dao is not loaded for the resource type " + resourceType); } Class claz = DbUtil.getEntityBeanType(dao); - + Long identityId = null; - + while (claz != null && claz != Object.class) { try { String tableName = DbUtil.getTableName(claz); if (tableName == null) { - throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); + throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database", null); } identityId = _identityDao.getIdentityId(tableName, resourceId); if (identityId != null) { @@ -175,9 +175,9 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager } claz = claz.getSuperclass(); } - + if (identityId == null) { - throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + " and type " + resourceType); + throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + " and type " + resourceType, null); } return identityId; } @@ -187,9 +187,9 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager Class claz = DbUtil.getEntityBeanType(dao); return DbUtil.getTableName(claz); } - + private Pair getAccountDomain(long resourceId, TaggedResourceType resourceType) { - + Pair pair = null; GenericDao dao = _daoMap.get(resourceType); Class claz = DbUtil.getEntityBeanType(dao); @@ -197,7 +197,7 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager try { String tableName = DbUtil.getTableName(claz); if (tableName == null) { - throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); + throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database", null); } pair = _identityDao.getAccountDomainInfo(tableName, resourceId, resourceType); if (pair.first() != null || pair.second() != null) { @@ -211,27 +211,27 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager Long accountId = pair.first(); Long domainId = pair.second(); - + if (accountId == null) { accountId = Account.ACCOUNT_ID_SYSTEM; } - + if (domainId == null) { domainId = Domain.ROOT_DOMAIN; } - + return new Pair(accountId, domainId); } @Override public TaggedResourceType getResourceType(String resourceTypeStr) { - + for (TaggedResourceType type : ResourceTag.TaggedResourceType.values()) { if (type.toString().equalsIgnoreCase(resourceTypeStr)) { return type; } } - throw new InvalidParameterValueException("Invalid resource type " + resourceTypeStr); + throw new InvalidParameterValueException("Invalid resource type " + resourceTypeStr, null); } @Override @@ -240,23 +240,23 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager public List createTags(List resourceIds, TaggedResourceType resourceType, Map tags, String customer) { Account caller = UserContext.current().getCaller(); - + List resourceTags = new ArrayList(tags.size()); - + Transaction txn = Transaction.currentTxn(); txn.start(); - + for (String key : tags.keySet()) { for (String resourceId : resourceIds) { Long id = getResourceId(resourceId, resourceType); String resourceUuid = getUuid(resourceId, resourceType); - + //check if object exists if (_daoMap.get(resourceType).findById(id) == null) { throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + - " and type " + resourceType); + " and type " + resourceType, null); } - + Pair accountDomainPair = getAccountDomain(id, resourceType); Long domainId = accountDomainPair.second(); Long accountId = accountDomainPair.first(); @@ -267,15 +267,15 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager _accountMgr.checkAccess(caller, _domainMgr.getDomain(domainId)); } else { throw new PermissionDeniedException("Account " + caller + " doesn't have permissions to create tags" + - " for resource " + key); + " for resource " + key); } - + String value = tags.get(key); - + if (value == null || value.isEmpty()) { - throw new InvalidParameterValueException("Value for the key " + key + " is either null or empty"); + throw new InvalidParameterValueException("Value for the key " + key + " is either null or empty", null); } - + ResourceTagVO resourceTag = new ResourceTagVO(key, value, accountDomainPair.first(), accountDomainPair.second(), id, resourceType, customer, resourceUuid); @@ -283,40 +283,40 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager resourceTags.add(resourceTag); } } - + txn.commit(); - + return resourceTags; } - + @Override public String getUuid(String resourceId, TaggedResourceType resourceType) { GenericDao dao = _daoMap.get(resourceType); Class claz = DbUtil.getEntityBeanType(dao); - - String identiyUUId = null; - - while (claz != null && claz != Object.class) { - try { - String tableName = DbUtil.getTableName(claz); - if (tableName == null) { - throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); - } - - claz = claz.getSuperclass(); - if (claz == Object.class) { - identiyUUId = _identityDao.getIdentityUuid(tableName, resourceId); - } - } catch (Exception ex) { - //do nothing here, it might mean uuid field is missing and we have to search further - } - } - - if (identiyUUId == null) { - return resourceId; - } - - return identiyUUId; + + String identiyUUId = null; + + while (claz != null && claz != Object.class) { + try { + String tableName = DbUtil.getTableName(claz); + if (tableName == null) { + throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database", null); + } + + claz = claz.getSuperclass(); + if (claz == Object.class) { + identiyUUId = _identityDao.getIdentityUuid(tableName, resourceId); + } + } catch (Exception ex) { + //do nothing here, it might mean uuid field is missing and we have to search further + } + } + + if (identiyUUId == null) { + return resourceId; + } + + return identiyUUId; } @Override @@ -332,54 +332,54 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), - cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - Filter searchFilter = new Filter(ResourceTagVO.class, "resourceType", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - - SearchBuilder sb = _resourceTagDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), + cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(ResourceTagVO.class, "resourceType", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ); - sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ); - - if (resourceId != null) { - sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ); - sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.EQ); - sb.cp(); - } - - sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.and("customer", sb.entity().getCustomer(), SearchCriteria.Op.EQ); - - // now set the SC criteria... - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (key != null) { - sc.setParameters("key", key); - } - - if (value != null) { - sc.setParameters("value", value); - } - - if (resourceId != null) { - sc.setParameters("resourceId", resourceId); - sc.setParameters("resourceUuid", resourceId); - } - - if (resourceType != null) { - sc.setParameters("resourceType", resourceType); - } - - if (customerName != null) { - sc.setParameters("customer", customerName); - } - - return _resourceTagDao.search(sc, searchFilter); + SearchBuilder sb = _resourceTagDao.createSearchBuilder(); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ); + sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ); + + if (resourceId != null) { + sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ); + sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.EQ); + sb.cp(); + } + + sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.and("customer", sb.entity().getCustomer(), SearchCriteria.Op.EQ); + + // now set the SC criteria... + SearchCriteria sc = sb.create(); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (key != null) { + sc.setParameters("key", key); + } + + if (value != null) { + sc.setParameters("value", value); + } + + if (resourceId != null) { + sc.setParameters("resourceId", resourceId); + sc.setParameters("resourceUuid", resourceId); + } + + if (resourceType != null) { + sc.setParameters("resourceType", resourceType); + } + + if (customerName != null) { + sc.setParameters("customer", customerName); + } + + return _resourceTagDao.search(sc, searchFilter); } @Override @@ -387,21 +387,21 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager @ActionEvent(eventType = EventTypes.EVENT_TAGS_DELETE, eventDescription = "deleting resource tags") public boolean deleteTags(List resourceIds, TaggedResourceType resourceType, Map tags) { Account caller = UserContext.current().getCaller(); - + SearchBuilder sb = _resourceTagDao.createSearchBuilder(); sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.IN); sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.IN); sb.cp(); sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); - + SearchCriteria sc = sb.create(); sc.setParameters("resourceId", resourceIds.toArray()); sc.setParameters("resourceUuid", resourceIds.toArray()); sc.setParameters("resourceType", resourceType); - + List resourceTags = _resourceTagDao.search(sc, null);; List tagsToRemove = new ArrayList(); - + // Finalize which tags should be removed for (ResourceTag resourceTag : resourceTags) { //1) validate the permissions @@ -430,11 +430,11 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager tagsToRemove.add(resourceTag); } } - + if (tagsToRemove.isEmpty()) { - throw new InvalidParameterValueException("Unable to find tags by parameters specified"); + throw new InvalidParameterValueException("Unable to find tags by parameters specified", null); } - + //Remove the tags Transaction txn = Transaction.currentTxn(); txn.start();