From f1ec4fddd3cbf1c6e4de540bbef1855cf2816f9b Mon Sep 17 00:00:00 2001 From: Vijayendra Bhamidipati Date: Thu, 5 Jul 2012 16:22:44 -0700 Subject: [PATCH] CS-15217: Security: Malicious user is able to get the size of the cloud by enumerating IDs Description: As part of the fix for Bug CS-13127, a new overloaded function, addProxyObject() was added to facilitate transparent db id to uuid conversions when db IDs were added to exceptions that were thrown in the Cloudstack mgmt server code. However, it turns out that there are quite many db IDs still in the code that are being directly embedded in the String message that is passed during exception creation. In this commit, we modify the default constructor of InvalidParameterValueException so that it takes a second argument of type List. This will help developers see that there is a second parameter required, and make them look into what that parameter is about. Hopefully, this will stop db IDs from being embedded into the exception message. The parameter can be set to null though, since there are many places in the code that don't embed any DB IDs in the exception. This is still a WIP, so the older default constructor for InvalidParameterValueException has not been removed yet. When all instances of throw new InvalidParameterValueException() have been moved over to the new default constructor, the old one will be removed, else compilation will break. The reason for having to do this in batches is that there are way too many places in the code that throw exceptions, and they all cannot be covered in a single commit without it taking much time. In following commits, all other exceptions will be changed in the same way as InvalidParameterValueException. --- api/src/com/cloud/api/BaseCmd.java | 22 +- api/src/com/cloud/api/BaseListCmd.java | 4 +- .../cloud/api/BaseListTaggedResourcesCmd.java | 4 +- .../api/commands/ActivateProjectCmd.java | 15 +- .../api/commands/AddAccountToProjectCmd.java | 23 +- .../commands/AssignToLoadBalancerRuleCmd.java | 12 +- .../api/commands/AssociateIPAddrCmd.java | 97 +- .../com/cloud/api/commands/AttachIsoCmd.java | 10 +- .../AuthorizeSecurityGroupEgressCmd.java | 28 +- .../AuthorizeSecurityGroupIngressCmd.java | 24 +- .../api/commands/CreateFirewallRuleCmd.java | 56 +- .../commands/CreateIpForwardingRuleCmd.java | 79 +- .../commands/CreateLoadBalancerRuleCmd.java | 135 ++- .../api/commands/CreateNetworkACLCmd.java | 48 +- .../cloud/api/commands/CreateNetworkCmd.java | 78 +- .../commands/CreateNetworkOfferingCmd.java | 64 +- .../commands/CreatePortForwardingRuleCmd.java | 32 +- .../api/commands/CreatePrivateGatewayCmd.java | 40 +- .../cloud/api/commands/CreateProjectCmd.java | 3 +- .../commands/CreateRemoteAccessVpnCmd.java | 113 +- .../cloud/api/commands/CreateSnapshotCmd.java | 15 +- .../api/commands/CreateSnapshotPolicyCmd.java | 24 +- .../api/commands/CreateStaticRouteCmd.java | 25 +- .../cloud/api/commands/CreateTemplateCmd.java | 41 +- .../api/commands/CreateVpnConnectionCmd.java | 38 +- .../api/commands/CreateVpnGatewayCmd.java | 44 +- .../commands/DeleteAccountFromProjectCmd.java | 16 +- .../api/commands/DeleteFirewallRuleCmd.java | 18 +- .../commands/DeleteIpForwardingRuleCmd.java | 12 +- .../commands/DeleteLBStickinessPolicyCmd.java | 6 +- .../commands/DeleteLoadBalancerRuleCmd.java | 16 +- .../api/commands/DeleteNetworkACLCmd.java | 18 +- .../cloud/api/commands/DeleteNetworkCmd.java | 14 +- .../commands/DeletePortForwardingRuleCmd.java | 20 +- .../api/commands/DeletePrivateGatewayCmd.java | 18 +- .../cloud/api/commands/DeleteProjectCmd.java | 12 +- .../commands/DeleteRemoteAccessVpnCmd.java | 46 +- .../api/commands/DeleteSecurityGroupCmd.java | 48 +- .../api/commands/DeleteStaticRouteCmd.java | 20 +- .../com/cloud/api/commands/DeployVMCmd.java | 79 +- .../com/cloud/api/commands/DetachIsoCmd.java | 4 +- .../api/commands/DisableStaticNatCmd.java | 18 +- .../api/commands/DisassociateIPAddrCmd.java | 22 +- .../api/commands/EnableStaticNatCmd.java | 14 +- .../cloud/api/commands/ListCapacityCmd.java | 52 +- .../com/cloud/api/commands/ListHostsCmd.java | 37 +- .../ListSupportedNetworkServicesCmd.java | 22 +- .../com/cloud/api/commands/ListVMsCmd.java | 43 +- .../api/commands/MigrateSystemVMCmd.java | 32 +- .../com/cloud/api/commands/MigrateVMCmd.java | 78 +- .../RemoveFromLoadBalancerRuleCmd.java | 12 +- .../cloud/api/commands/RestartNetworkCmd.java | 21 +- .../cloud/api/commands/SuspendProjectCmd.java | 12 +- .../cloud/api/commands/UpdateClusterCmd.java | 68 +- .../cloud/api/commands/UpdateNetworkCmd.java | 32 +- .../cloud/api/commands/UpdateProjectCmd.java | 16 +- .../UpdateTemplateOrIsoPermissionsCmd.java | 16 +- .../api/commands/UpgradeSystemVMCmd.java | 16 +- .../com/cloud/api/commands/UpgradeVMCmd.java | 16 +- .../InvalidParameterValueException.java | 12 + .../com/cloud/network/NetworkManagerImpl.java | 1054 +++++++++-------- .../cloud/template/TemplateAdapterBase.java | 469 ++++---- .../com/cloud/user/AccountManagerImpl.java | 220 ++-- .../src/com/cloud/vm/UserVmManagerImpl.java | 553 ++++----- utils/src/com/cloud/utils/IdentityProxy.java | 34 +- 65 files changed, 2207 insertions(+), 2083 deletions(-) diff --git a/api/src/com/cloud/api/BaseCmd.java b/api/src/com/cloud/api/BaseCmd.java index 5899354207b..8895bf0a173 100755 --- a/api/src/com/cloud/api/BaseCmd.java +++ b/api/src/com/cloud/api/BaseCmd.java @@ -14,6 +14,7 @@ package com.cloud.api; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -56,6 +57,7 @@ import com.cloud.user.Account; import com.cloud.user.AccountService; import com.cloud.user.DomainService; import com.cloud.user.ResourceLimitService; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; import com.cloud.vm.BareMetalVmService; @@ -196,9 +198,9 @@ public abstract class BaseCmd { } public ManagementService getMgmtServiceRef() { - return _mgr; + return _mgr; } - + public static String getDateString(Date date) { if (date == null) { return ""; @@ -482,12 +484,12 @@ public abstract class BaseCmd { public Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly) { if (accountName != null) { if (domainId == null) { - throw new InvalidParameterValueException("Account must be specified with domainId parameter"); + throw new InvalidParameterValueException("Account must be specified with domainId parameter", null); } Domain domain = _domainService.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } Account account = _accountService.getActiveAccountByName(accountName, domainId); @@ -498,7 +500,9 @@ public abstract class BaseCmd { throw new PermissionDeniedException("Can't add resources to the account id=" + account.getId() + " in state=" + account.getState() + " as it's no longer active"); } } else { - throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain id=" + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain with specified id", idList); } } @@ -508,14 +512,12 @@ public abstract class BaseCmd { if (!enabledOnly || project.getState() == Project.State.Active) { return project.getProjectAccountId(); } else { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active"); - ex.addProxyObject(project, projectId, "projectId"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } } else { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified projectId"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + throw new InvalidParameterValueException("Unable to find project by id", null); } } return null; diff --git a/api/src/com/cloud/api/BaseListCmd.java b/api/src/com/cloud/api/BaseListCmd.java index 0bf288051d0..d3455c49e24 100755 --- a/api/src/com/cloud/api/BaseListCmd.java +++ b/api/src/com/cloud/api/BaseListCmd.java @@ -48,11 +48,11 @@ public abstract class BaseListCmd extends BaseCmd { public Integer getPageSize() { if (pageSize != null && MAX_PAGESIZE != null && pageSize.longValue() > MAX_PAGESIZE.longValue()) { - throw new InvalidParameterValueException("Page size can't exceed max allowed page size value: " + MAX_PAGESIZE.longValue()); + throw new InvalidParameterValueException("Page size can't exceed max allowed page size value: " + MAX_PAGESIZE.longValue(), null); } if (pageSize != null && pageSize.longValue() == PAGESIZE_UNLIMITED && page != null) { - throw new InvalidParameterValueException("Can't specify page parameter when pagesize is -1 (Unlimited)"); + throw new InvalidParameterValueException("Can't specify page parameter when pagesize is -1 (Unlimited)", null); } return pageSize; diff --git a/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java b/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java index 9a70b107089..fb50f0cd692 100644 --- a/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java +++ b/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java @@ -25,7 +25,7 @@ import com.cloud.exception.InvalidParameterValueException; public abstract class BaseListTaggedResourcesCmd extends BaseListProjectAndAccountResourcesCmd{ @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "List resources by tags (key/value pairs)") private Map tags; - + public Map getTags() { Map tagsMap = null; if (tags != null && !tags.isEmpty()) { @@ -37,7 +37,7 @@ public abstract class BaseListTaggedResourcesCmd extends BaseListProjectAndAccou String key = services.get("key"); String value = services.get("value"); if (value == null) { - throw new InvalidParameterValueException("No value is passed in for key " + key); + throw new InvalidParameterValueException("No value is passed in for key " + key, null); } tagsMap.put(key, value); } diff --git a/api/src/com/cloud/api/commands/ActivateProjectCmd.java b/api/src/com/cloud/api/commands/ActivateProjectCmd.java index 24df6491478..6af996492cb 100644 --- a/api/src/com/cloud/api/commands/ActivateProjectCmd.java +++ b/api/src/com/cloud/api/commands/ActivateProjectCmd.java @@ -18,7 +18,6 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; import com.cloud.api.IdentityMapper; -import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; @@ -37,7 +36,7 @@ public class ActivateProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be modified") private Long id; @@ -54,18 +53,18 @@ public class ActivateProjectCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + return _projectService.getProjectOwner(id).getId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -83,12 +82,12 @@ public class ActivateProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to activate a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACTIVATE; } - + @Override public String getEventDescription() { return "Activating project: " + id; diff --git a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java b/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java index b430a706c2b..c9db4791431 100644 --- a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java +++ b/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java @@ -26,7 +26,6 @@ import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -import com.cloud.utils.AnnotationHelper; @Implementation(description="Adds acoount to a project", responseObject=SuccessResponse.class, since="3.0.0") @@ -42,10 +41,10 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project to add the account to") private Long projectId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="name of the account to be added to the project") private String accountName; - + @Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, description="email to which invitation to the project is going to be sent") private String email; @@ -62,7 +61,7 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { return projectId; } - + public String getEmail() { return email; } @@ -79,9 +78,9 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { @Override public void execute(){ if (accountName == null && email == null) { - throw new InvalidParameterValueException("Either accountName or email is required"); + throw new InvalidParameterValueException("Either accountName or email is required", null); } - + UserContext.current().setEventDetails("Project id: "+ projectId + "; accountName " + accountName); boolean result = _projectService.addAccountToProject(getProjectId(), getAccountName(), getEmail()); if (result) { @@ -91,25 +90,25 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add account to the project"); } } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(projectId); //verify input parameters if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id", null); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + return _projectService.getProjectOwner(projectId).getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACCOUNT_ADD; } - + @Override public String getEventDescription() { if (accountName != null) { diff --git a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java index 9224613cdd3..364ab51a93a 100644 --- a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java +++ b/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java @@ -88,7 +88,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "applying instances for load balancer: " + getLoadBalancerId() + " (ids: " + StringUtils.join(getVirtualMachineIds(), ",") + ")"; } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getLoadBalancerId()+" VmIds: "+StringUtils.join(getVirtualMachineIds(), ",")); @@ -100,7 +100,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign load balancer rule"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -108,10 +108,10 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule by id", null); + } return lb.getNetworkId(); } } diff --git a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java index e87548765cd..625793d1a4f 100644 --- a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java +++ b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java @@ -56,37 +56,38 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, - description="the ID of the domain to associate with this IP address") + description="the ID of the domain to associate with this IP address") private Long domainId; @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, - description="the ID of the availability zone you want to acquire an public IP address from") + description="the ID of the availability zone you want to acquire an public IP address from") private Long zoneId; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, - description="The network this ip address should be associated to.") + description="The network this ip address should be associated to.") private Long networkId; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, - description="Deploy vm for the project") + description="Deploy vm for the project") private Long projectId; @IdentityMapper(entityTableName="vpc") @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="the VPC you want the ip address to " + - "be associated with") + "be associated with") private Long vpcId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + @Override public String getEntityTable() { - return "user_ip_address"; + return "user_ip_address"; } - + public String getAccountName() { if (accountName != null) { return accountName; @@ -103,7 +104,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { private long getZoneId() { if (zoneId != null) { - return zoneId; + return zoneId; } else if (vpcId != null) { Vpc vpc = _entityMgr.findById(Vpc.class, vpcId); if (vpc != null) { @@ -115,28 +116,28 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { return ntwk.getDataCenterId(); } } - - throw new InvalidParameterValueException("Unable to figure out zone to assign ip to"); + + throw new InvalidParameterValueException("Unable to figure out zone to assign ip to", null); } - + public Long getVpcId() { return vpcId; } - + public Long getNetworkId() { if (vpcId != null) { return null; } - + if (networkId != null) { return networkId; } Long zoneId = getZoneId(); - + if (zoneId == null) { return null; } - + DataCenter zone = _configService.getZone(zoneId); if (zone.getNetworkType() == NetworkType.Advanced) { List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), @@ -144,52 +145,52 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + - " doesn't have virtual networks in zone=" + zone.getName()); + " doesn't have virtual networks in zone=" + zone.getName(), null); } - + if (networks.size() < 1) { - throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); + throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone", null); } else if (networks.size() > 1) { - throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); + throw new InvalidParameterValueException("Account has more than one Isolated network in the zone", null); } - + return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); if (defaultGuestNetwork == null) { throw new InvalidParameterValueException("Unable to find a default Guest network for account " + - getAccountName() + " in domain id=" + getDomainId()); + getAccountName() + " in domain id=" + getDomainId(), null); } else { return defaultGuestNetwork.getId(); } } } - + @Override public long getEntityOwnerId() { - Account caller = UserContext.current().getCaller(); - if (accountName != null && domainId != null) { - Account account = _accountService.finalizeOwner(caller, accountName, domainId, projectId); - return account.getId(); - } else if (getNetworkId() != null){ - Network network = _networkService.getNetwork(getNetworkId()); + Account caller = UserContext.current().getCaller(); + if (accountName != null && domainId != null) { + Account account = _accountService.finalizeOwner(caller, accountName, domainId, projectId); + return account.getId(); + } else if (getNetworkId() != null){ + Network network = _networkService.getNetwork(getNetworkId()); return network.getAccountId(); - } else if (vpcId != null) { - Vpc vpc = _vpcService.getVpc(getVpcId()); - if (vpc == null) { - throw new InvalidParameterValueException("Can't find Enabled vpc by id specified"); - } - return vpc.getAccountId(); - } - - throw new InvalidParameterValueException("Failed to determine ip owner"); + } else if (vpcId != null) { + Vpc vpc = _vpcService.getVpc(getVpcId()); + if (vpc == null) { + throw new InvalidParameterValueException("Can't find Enabled vpc by id specified", null); + } + return vpc.getAccountId(); + } + + throw new InvalidParameterValueException("Failed to determine ip owner", null); } @Override public String getEventType() { return EventTypes.EVENT_NET_IP_ASSIGN; } - + @Override public String getEventDescription() { return "associating ip to network id: " + getNetworkId() + " in zone " + getZoneId(); @@ -206,9 +207,9 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { } public static String getResultObjectName() { - return "addressinfo"; + return "addressinfo"; } - + @Override public void create() throws ResourceAllocationException{ try { @@ -227,14 +228,14 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } - + @Override public void execute() throws ResourceUnavailableException, ResourceAllocationException, - ConcurrentOperationException, InsufficientCapacityException { + ConcurrentOperationException, InsufficientCapacityException { UserContext.current().setEventDetails("Ip Id: " + getEntityId()); IpAddress result = null; - + result = _networkService.associateIP(getEntityId(), getNetworkId(), getVpcId()); if (result != null) { @@ -245,8 +246,8 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign ip address"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -256,7 +257,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public Long getSyncObjId() { return getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; diff --git a/api/src/com/cloud/api/commands/AttachIsoCmd.java b/api/src/com/cloud/api/commands/AttachIsoCmd.java index 690f17b8093..1e5a27a8347 100755 --- a/api/src/com/cloud/api/commands/AttachIsoCmd.java +++ b/api/src/com/cloud/api/commands/AttachIsoCmd.java @@ -67,14 +67,14 @@ public class AttachIsoCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm vm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); if (vm == null) { - throw new InvalidParameterValueException("Unable to find virtual machine by id " + getVirtualMachineId()); + throw new InvalidParameterValueException("Unable to find virtual machine by id " + getVirtualMachineId(), null); } - + return vm.getAccountId(); } @@ -87,10 +87,10 @@ public class AttachIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "attaching ISO: " + getId() + " to vm: " + getVirtualMachineId(); } - + @Override public void execute(){ - UserContext.current().setEventDetails("Vm Id: " +getVirtualMachineId()+ " ISO Id: "+getId()); + UserContext.current().setEventDetails("Vm Id: " +getVirtualMachineId()+ " ISO Id: "+getId()); boolean result = _templateService.attachIso(id, virtualMachineId); if (result) { UserVm userVm = _responseGenerator.findUserVmById(virtualMachineId); diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java index a56a8e0d200..1c8bce8ba31 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java +++ b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java @@ -17,7 +17,9 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; + import org.apache.log4j.Logger; + import com.cloud.api.ApiConstants; import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; @@ -25,8 +27,8 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; -import com.cloud.api.response.SecurityGroupRuleResponse; import com.cloud.api.response.SecurityGroupResponse; +import com.cloud.api.response.SecurityGroupRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -65,22 +67,22 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping") private Map userSecurityGroupList; - + @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") private Long domainId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group") private Long projectId; - + @IdentityMapper(entityTableName="security_group") @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter") private Long securityGroupId; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter") private String securityGroupName; @@ -110,21 +112,21 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { public Long getSecurityGroupId() { if (securityGroupId != null && securityGroupName != null) { - throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive"); + throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive", null); } - + if (securityGroupName != null) { securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId()); if (securityGroupId == null) { - throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId()); + throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId(), null); } securityGroupName = null; } - + if (securityGroupId == null) { - throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command"); + throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command", null); } - + return securityGroupId; } @@ -162,7 +164,7 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java index 33fc240d17c..f5e010a94c4 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java +++ b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java @@ -68,22 +68,22 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping") private Map userSecurityGroupList; - + @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") private Long domainId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group") private Long projectId; - + @IdentityMapper(entityTableName="security_group") @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter") private Long securityGroupId; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter") private String securityGroupName; @@ -113,21 +113,21 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { public Long getSecurityGroupId() { if (securityGroupId != null && securityGroupName != null) { - throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive"); + throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive", null); } - + if (securityGroupName != null) { securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId()); if (securityGroupId == null) { - throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId()); + throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId(), null); } securityGroupName = null; } - + if (securityGroupId == null) { - throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command"); + throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command", null); } - + return securityGroupId; } @@ -165,7 +165,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } diff --git a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java b/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java index abeaa15ebac..c940add63f6 100644 --- a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java @@ -59,25 +59,26 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of firewall rule") private Integer publicEndPort; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; - + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent") private Integer icmpType; @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message") private Integer icmpCode; - + @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "type of firewallrule: system/user") private String type; - + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + + @Override public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } public Long getIpAddressId() { @@ -89,6 +90,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return protocol.trim(); } + @Override public List getSourceCidrList() { if (cidrlist != null) { return cidrlist; @@ -97,7 +99,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal oneCidrList.add(NetUtils.ALL_CIDRS); return oneCidrList; } - + } // /////////////////////////////////////////////////// @@ -108,7 +110,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public String getCommandName() { return s_name; } - + public void setSourceCidrList(List cidrs){ cidrlist = cidrs; } @@ -171,7 +173,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } else { return publicEndPort.intValue(); } - + return null; } @@ -189,14 +191,14 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } - + if (ntwkId == null) { throw new InvalidParameterValueException("Unable to create firewall rule for the ipAddress id=" + ipAddressId + - " as ip is not associated with any network and no networkId is passed in"); + " as ip is not associated with any network and no networkId is passed in", null); } return ntwkId; } @@ -268,11 +270,11 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal private IpAddress getIp() { IpAddress ip = _networkService.getIp(ipAddressId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } - + @Override public Integer getIcmpCode() { if (icmpCode != null) { @@ -282,14 +284,14 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } return null; } - + @Override public Integer getIcmpType() { if (icmpType != null) { return icmpType; } else if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO)) { - return -1; - + return -1; + } return null; } @@ -299,20 +301,20 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return null; } - @Override - public FirewallRuleType getType() { - if (type != null && type.equalsIgnoreCase("system")) { - return FirewallRuleType.System; - } else { - return FirewallRuleType.User; - } - } - + @Override + public FirewallRuleType getType() { + if (type != null && type.equalsIgnoreCase("system")) { + return FirewallRuleType.System; + } else { + return FirewallRuleType.User; + } + } + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java index 4e65a0ffbf4..97a83b650d4 100644 --- a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java @@ -50,19 +50,19 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP address id of the forwarding rule, already associated via associateIp") private Long ipAddressId; - + @Parameter(name=ApiConstants.START_PORT, type=CommandType.INTEGER, required=true, description="the start port for the rule") private Integer startPort; @Parameter(name=ApiConstants.END_PORT, type=CommandType.INTEGER, description="the end port for the rule") private Integer endPort; - + @Parameter(name=ApiConstants.PROTOCOL, type=CommandType.STRING, required=true, description="the protocol for the rule. Valid values are TCP or UDP.") private String protocol; - + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default") private Boolean openFirewall; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; @@ -70,23 +70,24 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + + @Override public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } - + public Long getIpAddressId() { return ipAddressId; } - + public int getStartPort() { return startPort; } - + public int getEndPort() { return endPort; } - + public Boolean getOpenFirewall() { if (openFirewall != null) { return openFirewall; @@ -111,11 +112,11 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta FirewallRule rule = null; try { UserContext.current().setEventDetails("Rule Id: "+ getEntityId()); - + if (getOpenFirewall()) { result = result && _firewallService.applyFirewallRules(ipAddressId, UserContext.current().getCaller()); } - + result = result && _rulesService.applyStaticNatRules(ipAddressId, UserContext.current().getCaller()); rule = _entityMgr.findById(FirewallRule.class, getEntityId()); StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false); @@ -124,26 +125,26 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta this.setResponseObject(fwResponse); } finally { if (!result || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } - + _rulesService.revokeStaticNatRule(getEntityId(), true); - + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr"); } } } - @Override - public void create() { - - //cidr list parameter is deprecated + @Override + public void create() { + + //cidr list parameter is deprecated if (cidrlist != null) { - throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); + throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command", null); } - + try { StaticNatRule rule = _rulesService.createStaticNatRule(this, getOpenFirewall()); this.setEntityId(rule.getId()); @@ -151,7 +152,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta s_logger.info("Unable to create Static Nat Rule due to ", e); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } - } + } @Override public long getEntityOwnerId() { @@ -174,16 +175,16 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta IpAddress ip = _networkService.getIp(ipAddressId); return ("Applying an ipforwarding 1:1 NAT rule for Ip: "+ip.getAddress()+" with virtual machine:"+ this.getVirtualMachineId()); } - + private long getVirtualMachineId() { Long vmId = _networkService.getIp(ipAddressId).getAssociatedWithVmId(); - + if (vmId == null) { - throw new InvalidParameterValueException("Ip address is not associated with any network, unable to create static nat rule"); + throw new InvalidParameterValueException("Ip address is not associated with any network, unable to create static nat rule", null); } return vmId; } - + @Override public String getDestIpAddress(){ return null; @@ -244,13 +245,13 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta IpAddress ip = _networkService.getIp(ipAddressId); return ip.getAccountId(); } - + @Override public String getXid() { // FIXME: We should allow for end user to specify Xid. return null; } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -264,16 +265,16 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta private IpAddress getIp() { IpAddress ip = _networkService.getIp(ipAddressId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } - + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; @@ -283,22 +284,22 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta public List getSourceCidrList() { return null; } - + @Override public Long getRelated() { return null; } - @Override - public FirewallRuleType getType() { - return FirewallRuleType.User; - } - - @Override + @Override + public FirewallRuleType getType() { + return FirewallRuleType.User; + } + + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java index c2ff39665f7..dbad001b8f0 100644 --- a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java @@ -12,6 +12,7 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.commands; +import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; @@ -38,6 +39,7 @@ import com.cloud.network.Network; import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.net.NetUtils; @Implementation(description="Creates a load balancer rule", responseObject=LoadBalancerResponse.class) @@ -65,7 +67,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, description="public ip address id from where the network traffic will be load balanced from") private Long publicIpId; - + @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="zone where the load balancer is going to be created. This parameter is required when LB service provider is ElasticLoadBalancerVm") private Long zoneId; @@ -74,8 +76,8 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements private Integer publicPort; @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for" + - " source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when LB" + - " rule is being created for VPC guest network 2) in all other cases defaulted to true") + " source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when LB" + + " rule is being created for VPC guest network 2) in all other cases defaulted to true") private Boolean openFirewall; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the load balancer. Must be used with the domainId parameter.") @@ -84,15 +86,15 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the load balancer") private Long domainId; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="The guest network this " + - "rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)") + "rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -113,97 +115,100 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements return privatePort; } + @Override public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } - + public Long getSourceIpAddressId() { - if (publicIpId != null) { - IpAddress ipAddr = _networkService.getIp(publicIpId); - if (ipAddr == null || !ipAddr.readyToUse()) { - throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); - } - } else if (getEntityId() != null) { - LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); - return rule.getSourceIpAddressId(); - } - - return publicIpId; + if (publicIpId != null) { + IpAddress ipAddr = _networkService.getIp(publicIpId); + if (ipAddr == null || !ipAddr.readyToUse()) { + throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id provided", null); + } + } else if (getEntityId() != null) { + LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); + return rule.getSourceIpAddressId(); + } + + return publicIpId; } - + private Long getVpcId() { if (publicIpId != null) { IpAddress ipAddr = _networkService.getIp(publicIpId); if (ipAddr == null || !ipAddr.readyToUse()) { - throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); + throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id povided", null); } else { return ipAddr.getVpcId(); } } return null; } - - + + public Long getNetworkId() { if (networkId != null) { return networkId; } Long zoneId = getZoneId(); - + if (zoneId == null) { - Long ipId = getSourceIpAddressId(); - if (ipId == null) { - throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified"); - } + Long ipId = getSourceIpAddressId(); + if (ipId == null) { + throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified", null); + } } - + if (zoneId != null) { - DataCenter zone = _configService.getZone(zoneId); - if (zone.getNetworkType() == NetworkType.Advanced) { + DataCenter zone = _configService.getZone(zoneId); + if (zone.getNetworkType() == NetworkType.Advanced) { List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); - throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName()); + throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName(), null); } - + if (networks.size() < 1) { - throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); + throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone", null); } else if (networks.size() > 1) { - throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); + throw new InvalidParameterValueException("Account has more than one Isolated network in the zone", null); } - + return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); if (defaultGuestNetwork == null) { - throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain id=" + getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", getDomainId(), "domainId")); + throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain with specified id", idList); } else { return defaultGuestNetwork.getId(); } } } else { - IpAddress ipAddr = _networkService.getIp(publicIpId); - if (ipAddr.getAssociatedWithNetworkId() != null) { + IpAddress ipAddr = _networkService.getIp(publicIpId); + if (ipAddr.getAssociatedWithNetworkId() != null) { return ipAddr.getAssociatedWithNetworkId(); - } else { - throw new InvalidParameterValueException("Ip address id=" + publicIpId + " is not associated with any network"); - } + } else { + throw new InvalidParameterValueException("Ip address id=" + publicIpId + " is not associated with any network", null); + } } } public Integer getPublicPort() { return publicPort; } - + public String getName() { return loadBalancerRuleName; } - + public Boolean getOpenFirewall() { boolean isVpc = getVpcId() == null ? false : true; if (openFirewall != null) { if (isVpc && openFirewall) { - throw new InvalidParameterValueException("Can't have openFirewall=true when IP address belongs to VPC"); + throw new InvalidParameterValueException("Can't have openFirewall=true when IP address belongs to VPC", null); } return openFirewall; } else { @@ -213,10 +218,10 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements return true; } } - + public List getSourceCidrList() { if (cidrlist != null) { - throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); + throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command", null); } return null; } @@ -229,16 +234,16 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public String getCommandName() { return s_name; } - + @Override public void execute() throws ResourceAllocationException, ResourceUnavailableException { - + UserContext callerContext = UserContext.current(); boolean success = true; LoadBalancer rule = null; try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); - + if (getOpenFirewall()) { success = success && _firewallService.applyFirewallRules(getSourceIpAddressId(), callerContext.getCaller()); } @@ -252,10 +257,10 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } lbResponse.setResponseName(getCommandName()); } catch (Exception ex) { - s_logger.warn("Failed to create LB rule due to exception ", ex); + s_logger.warn("Failed to create LB rule due to exception ", ex); }finally { if (!success || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } @@ -266,12 +271,12 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } } } - + @Override public void create() { //cidr list parameter is deprecated if (cidrlist != null) { - throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); + throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command", null); } try { LoadBalancer result = _lbService.createLoadBalancerRule(this, getOpenFirewall()); @@ -296,21 +301,23 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public String getProtocol() { return NetUtils.TCP_PROTO; } - + public long getAccountId() { if (publicIpId != null) return _networkService.getIp(getSourceIpAddressId()).getAccountId(); - + Account account = null; if ((domainId != null) && (accountName != null)) { account = _responseGenerator.findAccountByNameDomain(accountName, domainId); if (account != null) { return account.getId(); } else { - throw new InvalidParameterValueException("Unable to find account " + account + " in domain id=" + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", getDomainId(), "domainId")); + throw new InvalidParameterValueException("Unable to find account " + account + " in domain with specified id", idList); } } else { - throw new InvalidParameterValueException("Can't define IP owner. Either specify account/domainId or ipAddressId"); + throw new InvalidParameterValueException("Can't define IP owner. Either specify account/domainId or ipAddressId", null); } } @@ -330,16 +337,16 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public int getDefaultPortEnd() { return privatePort.intValue(); } - + @Override public long getEntityOwnerId() { - return getAccountId(); + return getAccountId(); } - + public String getAccountName() { return accountName; } - + public Long getZoneId() { return zoneId; } @@ -367,7 +374,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public void setSourceIpAddressId(Long ipId) { this.publicIpId = ipId; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java b/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java index 68d996a2ea7..0efc57004c6 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java @@ -47,30 +47,31 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of ACL") private Integer publicEndPort; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to allow traffic from/to") private List cidrlist; - + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent") private Integer icmpType; @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message") private Integer icmpCode; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, required=true, - description="The network of the vm the ACL will be created for") + description="The network of the vm the ACL will be created for") private Long networkId; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="the traffic type for the ACL," + - "can be Ingress or Egress, defaulted to Ingress if not specified") + "can be Ingress or Egress, defaulted to Ingress if not specified") private String trafficType; - + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + + @Override public String getEntityTable() { return "firewall_rules"; } @@ -84,6 +85,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return protocol.trim(); } + @Override public List getSourceCidrList() { if (cidrlist != null) { return cidrlist; @@ -93,21 +95,21 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return oneCidrList; } } - + public long getVpcId() { Network network = _networkService.getNetwork(getNetworkId()); if (network == null) { - throw new InvalidParameterValueException("Invalid networkId is given"); + throw new InvalidParameterValueException("Invalid networkId is given", null); } - + Long vpcId = network.getVpcId(); if (vpcId == null) { - throw new InvalidParameterValueException("Can create network ACL only for the network belonging to the VPC"); + throw new InvalidParameterValueException("Can create network ACL only for the network belonging to the VPC", null); } - + return vpcId; } - + @Override public FirewallRule.TrafficType getTrafficType() { if (trafficType == null) { @@ -118,7 +120,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return type; } } - throw new InvalidParameterValueException("Invalid traffic type " + trafficType); + throw new InvalidParameterValueException("Invalid traffic type " + trafficType, null); } // /////////////////////////////////////////////////// @@ -129,7 +131,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public String getCommandName() { return s_name; } - + public void setSourceCidrList(List cidrs){ cidrlist = cidrs; } @@ -191,7 +193,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } else { return publicEndPort.intValue(); } - + return null; } @@ -214,7 +216,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public long getEntityOwnerId() { Vpc vpc = _vpcService.getVpc(getVpcId()); if (vpc == null) { - throw new InvalidParameterValueException("Invalid vpcId is given"); + throw new InvalidParameterValueException("Invalid vpcId is given", null); } Account account = _accountService.getAccount(vpc.getAccountId()); @@ -273,7 +275,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public Long getSyncObjId() { return getNetworkId(); } - + @Override public Integer getIcmpCode() { if (icmpCode != null) { @@ -283,14 +285,14 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } return null; } - + @Override public Integer getIcmpType() { if (icmpType != null) { return icmpType; } else if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO)) { - return -1; - + return -1; + } return null; } @@ -304,7 +306,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public FirewallRuleType getType() { return FirewallRuleType.User; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/com/cloud/api/commands/CreateNetworkCmd.java index a9e1291a782..a1d01c7bcc3 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkCmd.java @@ -39,54 +39,54 @@ public class CreateNetworkCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network") private String displayText; - + @IdentityMapper(entityTableName="network_offerings") @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, required=true, description="the network offering id") private Long networkOfferingId; - + @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the network") private Long zoneId; - + @IdentityMapper(entityTableName="physical_network") @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway of the network. Required " + - "for Shared networks and Isolated networks when it belongs to VPC") + "for Shared networks and Isolated networks when it belongs to VPC") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask of the network. Required " + "for Shared networks and Isolated networks when it belongs to VPC") private String netmask; - + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, description="the beginning IP address in the network IP range") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the network IP" + - " range. If not specified, will be defaulted to startIP") + " range. If not specified, will be defaulted to startIP") private String endIp; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the network") private String vlan; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - + @Parameter(name=ApiConstants.ACL_TYPE, type=CommandType.STRING, description="Access control type; supported values" + - " are account and domain. In 3.0 all shared networks should have aclType=Domain, and all Isolated networks" + - " - Account. Account means that only the account owner can use the network, domain - all accouns in the domain can use the network") + " are account and domain. In 3.0 all shared networks should have aclType=Domain, and all Isolated networks" + + " - Account. Account means that only the account owner can use the network, domain - all accouns in the domain can use the network") private String aclType; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the network") private String accountName; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") private Long projectId; @@ -94,11 +94,11 @@ public class CreateNetworkCmd extends BaseCmd { @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a network") private Long domainId; - + @Parameter(name=ApiConstants.SUBDOMAIN_ACCESS, type=CommandType.BOOLEAN, description="Defines whether to allow" + - " subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified") + " subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified") private Boolean subdomainAccess; - + @IdentityMapper(entityTableName="vpc") @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="the VPC network belongs to") private Long vpcId; @@ -126,7 +126,7 @@ public class CreateNetworkCmd extends BaseCmd { public Long getDomainId() { return domainId; } - + public String getNetmask() { return netmask; } @@ -138,11 +138,11 @@ public class CreateNetworkCmd extends BaseCmd { public String getEndIp() { return endIp; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } @@ -150,48 +150,48 @@ public class CreateNetworkCmd extends BaseCmd { public String getNetworkDomain() { return networkDomain; } - + public Long getProjectId() { return projectId; } public String getAclType() { - return aclType; - } + return aclType; + } - public Boolean getSubdomainAccess() { - return subdomainAccess; - } + public Boolean getSubdomainAccess() { + return subdomainAccess; + } - public Long getVpcId() { + public Long getVpcId() { return vpcId; } public Long getZoneId() { Long physicalNetworkId = getPhysicalNetworkId(); - + if (physicalNetworkId == null && zoneId == null) { - throw new InvalidParameterValueException("Zone id is required"); + throw new InvalidParameterValueException("Zone id is required", null); } - + return zoneId; } - + public Long getPhysicalNetworkId() { NetworkOffering offering = _configService.getNetworkOffering(networkOfferingId); if (offering == null) { - throw new InvalidParameterValueException("Unable to find network offering by id " + networkOfferingId); + throw new InvalidParameterValueException("Unable to find network offering by id", null); } - + if (physicalNetworkId != null) { if (offering.getGuestType() == GuestType.Shared) { return physicalNetworkId; } else { - throw new InvalidParameterValueException("Physical network id can be specified for networks of guest ip type " + GuestType.Shared + " only."); + throw new InvalidParameterValueException("Physical network id can be specified for networks of guest ip type " + GuestType.Shared + " only.", null); } } else { if (zoneId == null) { - throw new InvalidParameterValueException("ZoneId is required as physicalNetworkId is null"); + throw new InvalidParameterValueException("ZoneId is required as physicalNetworkId is null", null); } return _networkService.findPhysicalNetworkId(zoneId, offering.getTags(), offering.getTrafficType()); } @@ -204,17 +204,17 @@ public class CreateNetworkCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException{ Network result = _networkService.createGuestNetwork(this); diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index 80120c888cc..8b69aec1261 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -46,55 +46,55 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network offering") private String networkOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network offering") private String displayText; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the traffic type for the network offering. Supported type in current release is GUEST only") private String traffictype; - + @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="the tags for the network offering.", length=4096) private String tags; - + @Parameter(name=ApiConstants.SPECIFY_VLAN, type=CommandType.BOOLEAN, description="true if network offering supports vlans") private Boolean specifyVlan; - + @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering. Default value is Optional") private String availability; - + @Parameter(name=ApiConstants.NETWORKRATE, type=CommandType.INTEGER, description="data transfer rate in megabits per second allowed") private Integer networkRate; - + @Parameter(name=ApiConstants.CONSERVE_MODE, type=CommandType.BOOLEAN, description="true if the network offering is IP conserve mode enabled") private Boolean conserveMode; - + @IdentityMapper(entityTableName="disk_offering") @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, description="the service offering ID used by virtual router provider") private Long serviceOfferingId; - + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, required=true, description="guest type of the network offering: Shared or Isolated") private String guestIptype; - + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="services supported by the network offering") private List supportedServices; - + @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network") private Map serviceProviderList; @Parameter(name = ApiConstants.SERVICE_CAPABILITY_LIST, type = CommandType.MAP, description = "desired service capabilities as part of network offering") private Map serviceCapabilitystList; - + @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if network offering supports specifying ip ranges; defaulted to false if not specified") private Boolean specifyIpRanges; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getNetworkOfferingName() { return networkOfferingName; } - + public String getDisplayText() { return displayText; } @@ -106,7 +106,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getTraffictype() { return traffictype; } - + public Boolean getSpecifyVlan() { return specifyVlan == null ? false : specifyVlan; } @@ -114,7 +114,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getAvailability() { return availability == null ? Availability.Optional.toString() : availability; } - + public Integer getNetworkRate() { return networkRate; } @@ -126,18 +126,18 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public Long getServiceOfferingId() { return serviceOfferingId; } - - public List getSupportedServices() { - return supportedServices; - } - public String getGuestIpType() { + public List getSupportedServices() { + return supportedServices; + } + + public String getGuestIpType() { return guestIptype; } - - public Boolean getSpecifyIpRanges() { - return specifyIpRanges == null ? false : specifyIpRanges; - } + + public Boolean getSpecifyIpRanges() { + return specifyIpRanges == null ? false : specifyIpRanges; + } public Boolean getConserveMode() { if (conserveMode == null) { @@ -166,7 +166,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { serviceProviderMap.put(service, providerList); } } - + return serviceProviderMap; } @@ -180,22 +180,22 @@ public class CreateNetworkOfferingCmd extends BaseCmd { while (iter.hasNext()) { HashMap svcCapabilityMap = (HashMap) iter.next(); Capability capability = null; - String svc = (String) svcCapabilityMap.get("service"); - String capabilityName = (String) svcCapabilityMap.get("capabilitytype"); - String capabilityValue = (String) svcCapabilityMap.get("capabilityvalue"); + String svc = svcCapabilityMap.get("service"); + String capabilityName = svcCapabilityMap.get("capabilitytype"); + String capabilityValue = svcCapabilityMap.get("capabilityvalue"); if (capabilityName != null) { capability = Capability.getCapability(capabilityName); } if ((capability == null) || (capabilityName == null) || (capabilityValue == null) ) { - throw new InvalidParameterValueException("Invalid capability:" + capabilityName + " capability value:" + capabilityValue); + throw new InvalidParameterValueException("Invalid capability:" + capabilityName + " capability value:" + capabilityValue, null); } if (svc.equalsIgnoreCase(service.getName())) { capabilityMap.put(capability, capabilityValue); } else { - //throw new InvalidParameterValueException("Service is not equal ") + //throw new InvalidParameterValueException("Service is not equal ") } } } @@ -210,7 +210,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java index 2c5a0739094..324ab07a387 100644 --- a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java @@ -65,7 +65,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P @IdentityMapper(entityTableName = "vm_instance") @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.LONG, required = true, - description = "the ID of the virtual machine for the port forwarding rule") + description = "the ID of the virtual machine for the port forwarding rule") private Long virtualMachineId; @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, @@ -74,20 +74,21 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; " + - "if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when PF" + - " rule is being created for VPC guest network 2) in all other cases defaulted to true") + "if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when PF" + + " rule is being created for VPC guest network 2) in all other cases defaulted to true") private Boolean openFirewall; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, - description="The network of the vm the Port Forwarding rule will be created for. " + - "Required when public Ip address is not associated with any Guest network yet (VPC case)") + description="The network of the vm the Port Forwarding rule will be created for. " + + "Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// + @Override public String getEntityTable() { return "firewall_rules"; } @@ -106,10 +107,11 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return virtualMachineId; } + @Override public List getSourceCidrList() { if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall " + - "rule for the specific cidr, please refer to createFirewallRule command"); + "rule for the specific cidr, please refer to createFirewallRule command", null); } return null; } @@ -118,7 +120,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P boolean isVpc = getVpcId() == null ? false : true; if (openFirewall != null) { if (isVpc && openFirewall) { - throw new InvalidParameterValueException("Can't have openFirewall=true when IP address belongs to VPC"); + throw new InvalidParameterValueException("Can't have openFirewall=true when IP address belongs to VPC", null); } return openFirewall; } else { @@ -128,12 +130,12 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return true; } } - + private Long getVpcId() { if (ipAddressId != null) { IpAddress ipAddr = _networkService.getIp(ipAddressId); if (ipAddr == null || !ipAddr.readyToUse()) { - throw new InvalidParameterValueException("Unable to create PF rule, invalid IP address id " + ipAddr.getId()); + throw new InvalidParameterValueException("Unable to create PF rule, invalid IP address id " + ipAddr.getId(), null); } else { return ipAddr.getVpcId(); } @@ -226,7 +228,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } else { @@ -234,7 +236,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P } if (ntwkId == null) { throw new InvalidParameterValueException("Unable to create port forwarding rule for the ipAddress id=" + ipAddressId + - " as ip is not associated with any network and no networkId is passed in"); + " as ip is not associated with any network and no networkId is passed in", null); } return ntwkId; } @@ -281,7 +283,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public void create() { // cidr list parameter is deprecated if (cidrlist != null) { - throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); + throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command", null); } try { @@ -324,7 +326,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P private IpAddress getIp() { IpAddress ip = _networkService.getIp(ipAddressId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } @@ -348,7 +350,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public FirewallRuleType getType() { return FirewallRuleType.User; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java b/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java index d493b8bc291..daeb9dd40d3 100644 --- a/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java +++ b/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java @@ -46,27 +46,27 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="physical_network") @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway of the Private gateway") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask of the Private gateway") private String netmask; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, required=true, description="the IP address of the Private gateaway") private String ipAddress; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, required=true, description="the Vlan for the private gateway") private String vlan; - + @IdentityMapper(entityTableName="vpc") @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, required=true, description="the VPC network belongs to") private Long vpcId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -78,7 +78,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getVlan() { return vlan; } - + public String getNetmask() { return netmask; } @@ -86,11 +86,11 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getStartIp() { return ipAddress; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } - + public Long getVpcId() { return vpcId; } @@ -102,8 +102,8 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - - + + @Override public void create() throws ResourceAllocationException { PrivateGateway result = null; @@ -118,17 +118,17 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } - + if (result != null) { this.setEntityId(result.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); } } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException, - ResourceAllocationException, ResourceUnavailableException { + ResourceAllocationException, ResourceUnavailableException { PrivateGateway result = _vpcService.applyVpcPrivateGateway(getEntityId()); if (result != null) { PrivateGatewayResponse response = _responseGenerator.createPrivateGatewayResponse(result); @@ -138,7 +138,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); } } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -153,13 +153,13 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getEventDescription() { return "creating private gateway"; } - + @Override public String getEntityTable() { return "vpc_gateways"; } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -169,11 +169,11 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public Long getSyncObjId() { Vpc vpc = _vpcService.getVpc(vpcId); if (vpc == null) { - throw new InvalidParameterValueException("Invalid id is specified for the vpc"); + throw new InvalidParameterValueException("Invalid id is specified for the vpc", null); } return vpc.getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PrivateGateway; diff --git a/api/src/com/cloud/api/commands/CreateProjectCmd.java b/api/src/com/cloud/api/commands/CreateProjectCmd.java index 1880793443e..d584b569ab3 100644 --- a/api/src/com/cloud/api/commands/CreateProjectCmd.java +++ b/api/src/com/cloud/api/commands/CreateProjectCmd.java @@ -56,6 +56,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// + @Override public String getEntityTable() { return "projects"; } @@ -95,7 +96,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { Account caller = UserContext.current().getCaller(); if ((accountName != null && domainId == null) || (domainId != null && accountName == null)) { - throw new InvalidParameterValueException("Account name and domain id must be specified together"); + throw new InvalidParameterValueException("Account name and domain id must be specified together", null); } if (accountName != null) { diff --git a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java b/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java index 7964166b009..70c99cb013a 100644 --- a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java +++ b/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java @@ -45,7 +45,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { @Parameter(name="iprange", type=CommandType.STRING, required=false, description="the range of ip addresses to allocate to vpn clients. The first ip in the range will be taken by the vpn server") private String ipRange; - + @Deprecated @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the VPN. Must be used with domainId.") private String accountName; @@ -54,46 +54,47 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the VPN. If the account parameter is used, domainId must also be used.") private Long domainId; - + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default") private Boolean openFirewall; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + @Override public String getEntityTable() { - return "user_ip_address"; + return "user_ip_address"; } - + public Long getPublicIpId() { - return publicIpId; - } - - public String getAccountName() { - return accountName; - } - - public Long getDomainId() { - return domainId; - } - - public String getIpRange() { - return ipRange; - } - - public void setIpRange(String ipRange) { - this.ipRange = ipRange; - } - - public Boolean getOpenFirewall() { - if (openFirewall != null) { - return openFirewall; - } else { - return true; - } + return publicIpId; } - + + public String getAccountName() { + return accountName; + } + + public Long getDomainId() { + return domainId; + } + + public String getIpRange() { + return ipRange; + } + + public void setIpRange(String ipRange) { + this.ipRange = ipRange; + } + + public Boolean getOpenFirewall() { + if (openFirewall != null) { + return openFirewall; + } else { + return true; + } + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -104,42 +105,42 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { return s_name; } - @Override - public long getEntityOwnerId() { - IpAddress ip = _networkService.getIp(publicIpId); - - if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + publicIpId); - } - - return ip.getAccountId(); + @Override + public long getEntityOwnerId() { + IpAddress ip = _networkService.getIp(publicIpId); + + if (ip == null) { + throw new InvalidParameterValueException("Unable to find ip address by id", null); + } + + return ip.getAccountId(); } - @Override - public String getEventDescription() { - return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE; - } - public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getPublicIpId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } - + if (ntwkId == null) { throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress id=" + getPublicIpId() + - " as ip is not associated with any network and no networkId is passed in"); + " as ip is not associated with any network and no networkId is passed in", null); } return ntwkId; } - + @Override public void create() { try { @@ -172,8 +173,8 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -187,7 +188,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { private IpAddress getIp() { IpAddress ip = _networkService.getIp(publicIpId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + publicIpId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } diff --git a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java b/api/src/com/cloud/api/commands/CreateSnapshotCmd.java index ce2962fd4bf..9a78007f274 100755 --- a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java +++ b/api/src/com/cloud/api/commands/CreateSnapshotCmd.java @@ -60,9 +60,10 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + + @Override public String getEntityTable() { - return "snapshots"; + return "snapshots"; } public String getAccountName() { @@ -100,23 +101,23 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { @Override public long getEntityOwnerId() { - + Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id", null); } - + Account account = _accountService.getAccount(volume.getAccountId()); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); if (project.getState() != Project.State.Active) { throw new PermissionDeniedException("Can't add resources to the project id=" + project.getId() + " in state=" + project.getState() + " as it's no longer active"); } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return volume.getAccountId(); } diff --git a/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java b/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java index 890c66c9121..a6a7212a08e 100644 --- a/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java +++ b/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java @@ -45,11 +45,11 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { private Integer maxSnaps; @Parameter(name=ApiConstants.SCHEDULE, type=CommandType.STRING, required=true, description="time the snapshot is scheduled to be taken. " + - "Format is:" + - "* if HOURLY, MM" + - "* if DAILY, MM:HH" + - "* if WEEKLY, MM:HH:DD (1-7)" + - "* if MONTHLY, MM:HH:DD (1-28)") + "Format is:" + + "* if HOURLY, MM" + + "* if DAILY, MM:HH" + + "* if WEEKLY, MM:HH:DD (1-7)" + + "* if MONTHLY, MM:HH:DD (1-28)") private String schedule; @Parameter(name=ApiConstants.TIMEZONE, type=CommandType.STRING, required=true, description="Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") @@ -93,30 +93,30 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id", null); } - + Account account = _accountService.getAccount(volume.getAccountId()); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); if (project.getState() != Project.State.Active) { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); ex.addProxyObject(project, project.getId(), "projectId"); throw ex; } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return volume.getAccountId(); } - + @Override public void execute(){ SnapshotPolicy result = _snapshotService.createPolicy(this, _accountService.getAccount(getEntityOwnerId())); diff --git a/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java b/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java index 4be141b3cd3..78c789fd247 100644 --- a/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java +++ b/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java @@ -29,7 +29,6 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.StaticRoute; import com.cloud.network.vpc.VpcGateway; import com.cloud.user.UserContext; @@ -42,12 +41,12 @@ import com.cloud.user.UserContext; public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ private static final String s_name = "createstaticrouteresponse"; public static final Logger s_logger = Logger.getLogger(CreateStaticRouteCmd.class.getName()); - + @IdentityMapper(entityTableName="vpc_gateways") @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.LONG, required=true, - description="the gateway id we are creating static route for") + description="the gateway id we are creating static route for") private Long gatewayId; - + @Parameter(name = ApiConstants.CIDR, required = true, type = CommandType.STRING, description = "static route cidr") private String cidr; @@ -115,7 +114,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } } } - + @Override public String getCommandName() { return s_name; @@ -123,13 +122,13 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ @Override public long getEntityOwnerId() { - VpcGateway gateway = _vpcService.getVpcGateway(gatewayId); - if (gateway == null) { - throw new InvalidParameterValueException("Invalid gateway id is specified"); - } - return _vpcService.getVpc(gateway.getVpcId()).getAccountId(); + VpcGateway gateway = _vpcService.getVpcGateway(gatewayId); + if (gateway == null) { + throw new InvalidParameterValueException("Invalid gateway id is specified", null); + } + return _vpcService.getVpc(gateway.getVpcId()).getAccountId(); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -139,11 +138,11 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ public Long getSyncObjId() { VpcGateway gateway = _vpcService.getVpcGateway(gatewayId); if (gateway == null) { - throw new InvalidParameterValueException("Invalid id is specified for the gateway"); + throw new InvalidParameterValueException("Invalid id is specified for the gateway", null); } return gateway.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StaticRoute; diff --git a/api/src/com/cloud/api/commands/CreateTemplateCmd.java b/api/src/com/cloud/api/commands/CreateTemplateCmd.java index 10c8b6ac6b8..33683951253 100755 --- a/api/src/com/cloud/api/commands/CreateTemplateCmd.java +++ b/api/src/com/cloud/api/commands/CreateTemplateCmd.java @@ -41,7 +41,7 @@ import com.cloud.user.UserContext; @Implementation(responseObject = StoragePoolResponse.class, description = "Creates a template of a virtual machine. " + "The virtual machine must be in a STOPPED state. " + "A template created from this command is automatically designated as a private template visible to the account that created it.") - public class CreateTemplateCmd extends BaseAsyncCreateCmd { +public class CreateTemplateCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateTemplateCmd.class.getName()); private static final String s_name = "createtemplateresponse"; @@ -91,16 +91,17 @@ import com.cloud.user.UserContext; @Parameter(name=ApiConstants.TEMPLATE_TAG, type=CommandType.STRING, description="the tag for this template.") private String templateTag; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="Template details in key/value pairs.") protected Map details; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + + @Override public String getEntityTable() { - return "vm_template"; + return "vm_template"; } public Integer getBits() { @@ -154,17 +155,17 @@ import com.cloud.user.UserContext; public String getTemplateTag() { return templateTag; } - + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } - + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -188,29 +189,29 @@ import com.cloud.user.UserContext; if (volume != null) { accountId = volume.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId, null); } } else { Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId); if (snapshot != null) { accountId = snapshot.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId); + throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId, null); } } - + Account account = _accountService.getAccount(accountId); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(accountId); + Project project = _projectService.findByProjectAccountId(accountId); if (project.getState() != Project.State.Active) { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); ex.addProxyObject(project, project.getId(), "projectId"); } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return accountId; } @@ -246,7 +247,7 @@ import com.cloud.user.UserContext; this.setEntityId(template.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, - "Failed to create a template"); + "Failed to create a template"); } } } diff --git a/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java b/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java index 228b70b3d42..9ec62226280 100644 --- a/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java +++ b/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java @@ -30,7 +30,6 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.user.Account; -import com.cloud.user.UserContext; @Implementation(description="Create site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { @@ -53,18 +52,19 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + @Override public String getEntityTable() { - return "s2s_vpn_connection"; + return "s2s_vpn_connection"; } - + public Long getVpnGatewayId() { return vpnGatewayId; } - + public Long getCustomerGatewayId() { return customerGatewayId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -75,21 +75,21 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Create site-to-site VPN connection"; - } + @Override + public String getEventDescription() { + return "Create site-to-site VPN connection"; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_CONNECTION_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_CONNECTION_CREATE; - } - @Override public void create() { try { @@ -122,8 +122,8 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -137,7 +137,7 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { private IpAddress getIp() { IpAddress ip = _s2sVpnService.getVpnGatewayIp(vpnGatewayId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by vpn gateway id " + vpnGatewayId); + throw new InvalidParameterValueException("Unable to find ip address by vpn gateway id " + vpnGatewayId, null); } return ip; } diff --git a/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java b/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java index 050dbdaf2ff..defb60ac312 100644 --- a/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java +++ b/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java @@ -45,9 +45,9 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// public String getEntityTable() { - return "user_ip_address"; + return "user_ip_address"; } - + public Long getPublicIpId() { return publicIpId; } @@ -62,27 +62,27 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { - IpAddress ip = _networkService.getIp(publicIpId); - - if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + publicIpId); - } - - return ip.getAccountId(); + @Override + public long getEntityOwnerId() { + IpAddress ip = _networkService.getIp(publicIpId); + + if (ip == null) { + throw new InvalidParameterValueException("Unable to find ip address by id", null); + } + + return ip.getAccountId(); } - @Override - public String getEventDescription() { - return "Create site-to-site VPN gateway for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Create site-to-site VPN gateway for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_GATEWAY_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_GATEWAY_CREATE; - } - @Override public void execute(){ Site2SiteVpnGateway result = _s2sVpnService.createVpnGateway(this); @@ -94,7 +94,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create VPN gateway"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -108,7 +108,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { private IpAddress getIp() { IpAddress ip = _networkService.getIp(publicIpId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + publicIpId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } diff --git a/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java b/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java index 41bac89273a..395f7de12db 100644 --- a/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java +++ b/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java @@ -39,7 +39,7 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project to remove the account from") private Long projectId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="name of the account to be removed from the project") private String accountName; @@ -48,7 +48,7 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// - + @Override public String getCommandName() { @@ -78,24 +78,24 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete account from the project"); } } - - + + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(projectId); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + return _projectService.getProjectOwner(projectId).getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACCOUNT_REMOVE; } - + @Override public String getEventDescription() { return "Removing account " + accountName + " from project: " + projectId; diff --git a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java b/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java index 7d8f0e71174..9dc2bb3ccea 100644 --- a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java @@ -53,7 +53,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -61,7 +61,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_FIREWALL_CLOSE; @@ -71,25 +71,25 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting firewall rule id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { FirewallRule rule = _entityMgr.findById(FirewallRule.class, id); if (rule == null) { - throw new InvalidParameterValueException("Unable to find firewall rule by id=" + id); + throw new InvalidParameterValueException("Unable to find firewall rule by id", null); } else { ownerId = _entityMgr.findById(FirewallRule.class, id).getAccountId(); } } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Rule Id: " + id); boolean result = _firewallService.revokeFirewallRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -97,8 +97,8 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete firewall rule"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -108,7 +108,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _firewallService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java index 98a4f226a8e..3914465bd8c 100644 --- a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java @@ -42,7 +42,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the forwarding rule") private Long id; - + // unexposed parameter needed for events logging @IdentityMapper(entityTableName="account") @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) @@ -67,8 +67,8 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Rule Id: "+id); - boolean result = _firewallService.revokeRelatedFirewallRule(id, true); - result = result && _rulesService.revokeStaticNatRule(id, true); + boolean result = _firewallService.revokeRelatedFirewallRule(id, true); + result = result && _rulesService.revokeStaticNatRule(id, true); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); @@ -83,7 +83,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { if (ownerId == null) { FirewallRule rule = _entityMgr.findById(FirewallRule.class, id); if (rule == null) { - throw new InvalidParameterValueException("Unable to find static nat rule by id: " + id); + throw new InvalidParameterValueException("Unable to find static nat rule by id", null); } else { ownerId = rule.getAccountId(); } @@ -100,7 +100,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting an ipforwarding 1:1 NAT rule id:"+id); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -110,7 +110,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _rulesService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java b/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java index b39c15dc3d7..a3e5c113219 100644 --- a/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java +++ b/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java @@ -24,8 +24,8 @@ import com.cloud.api.ServerApiException; import com.cloud.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.network.rules.StickinessPolicy; import com.cloud.network.rules.LoadBalancer; +import com.cloud.network.rules.StickinessPolicy; import com.cloud.user.Account; import com.cloud.user.UserContext; @@ -101,11 +101,11 @@ public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { StickinessPolicy policy = _entityMgr.findById(StickinessPolicy.class, getId()); if (policy == null) { - throw new InvalidParameterValueException("Unable to find LB stickiness rule: " + id); + throw new InvalidParameterValueException("Unable to find LB stickiness rule by id", null); } LoadBalancer lb = _lbService.findById(policy.getLoadBalancerId()); if (lb == null) { - throw new InvalidParameterValueException("Unable to find load balancer rule for stickiness rule: " + id); + throw new InvalidParameterValueException("Unable to find load balancer rule for stickiness rule by id", null); } return lb.getNetworkId(); } diff --git a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java index 050d7908fc7..7a180679ff5 100644 --- a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java @@ -78,13 +78,13 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "deleting load balancer: " + getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getId()); boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _lbService.deleteLoadBalancerRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -92,7 +92,7 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete load balancer"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -100,13 +100,13 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule by id", null); + } return lb.getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java b/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java index 9c0846544dd..84dee72f412 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java +++ b/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java @@ -56,7 +56,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -64,7 +64,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_FIREWALL_CLOSE; @@ -74,25 +74,25 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting Network ACL id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { FirewallRule rule = _networkACLService.getNetworkACL(id); if (rule == null) { - throw new InvalidParameterValueException("Unable to find network ACL by id=" + id); + throw new InvalidParameterValueException("Unable to find network ACL by id", null); } else { ownerId = rule.getAccountId(); } } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Network ACL Id: " + id); boolean result = _networkACLService.revokeNetworkACL(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -100,8 +100,8 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network ACL"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -111,7 +111,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _firewallService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteNetworkCmd.java b/api/src/com/cloud/api/commands/DeleteNetworkCmd.java index 63ad1f996ec..90e240e9db2 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkCmd.java +++ b/api/src/com/cloud/api/commands/DeleteNetworkCmd.java @@ -58,7 +58,7 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public void execute(){ UserContext.current().setEventDetails("Network Id: " + id); @@ -70,8 +70,8 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -81,22 +81,22 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ public Long getSyncObjId() { return id; } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_DELETE; } - + @Override public String getEventDescription() { return "Deleting network: " + id; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { - throw new InvalidParameterValueException("Networkd id=" + id + " doesn't exist"); + throw new InvalidParameterValueException("Couldn't find network by id", null); } else { return _networkService.getNetwork(id).getAccountId(); } diff --git a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java index a9e9d6fb4d5..ad87908da89 100644 --- a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java @@ -52,7 +52,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,7 +60,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_NET_RULE_DELETE; @@ -70,28 +70,28 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting port forwarding rule for id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { PortForwardingRule rule = _entityMgr.findById(PortForwardingRule.class, id); if (rule == null) { - throw new InvalidParameterValueException("Unable to find port forwarding rule by id=" + id); + throw new InvalidParameterValueException("Unable to find port forwarding rule by id", null); } else { ownerId = _entityMgr.findById(PortForwardingRule.class, id).getAccountId(); } - + } return ownerId; } - + @Override public void execute(){ UserContext.current().setEventDetails("Rule Id: "+id); //revoke corresponding firewall rule first boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _rulesService.revokePortForwardingRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -99,8 +99,8 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete port forwarding rule"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -110,7 +110,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _rulesService.getPortForwardigRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java b/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java index 83714582b1d..87a009652b6 100644 --- a/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java +++ b/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java @@ -54,7 +54,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -62,7 +62,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_PRIVATE_GATEWAY_DELETE; @@ -72,12 +72,12 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting private gateway id=" + id); } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute() throws ResourceUnavailableException, ConcurrentOperationException { UserContext.current().setEventDetails("Network ACL Id: " + id); @@ -89,8 +89,8 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete private gateway"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -100,14 +100,14 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public Long getSyncObjId() { VpcGateway gateway = _vpcService.getVpcPrivateGateway(getId()); if (gateway == null) { - throw new InvalidParameterValueException("Invalid private gateway id"); + throw new InvalidParameterValueException("Invalid private gateway id", null); } return gateway.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PrivateGateway; } - + } \ No newline at end of file diff --git a/api/src/com/cloud/api/commands/DeleteProjectCmd.java b/api/src/com/cloud/api/commands/DeleteProjectCmd.java index dc2505a0b80..cd892f65490 100644 --- a/api/src/com/cloud/api/commands/DeleteProjectCmd.java +++ b/api/src/com/cloud/api/commands/DeleteProjectCmd.java @@ -70,26 +70,26 @@ public class DeleteProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_DELETE; } - + @Override public String getEventDescription() { return "Deleting project: " + id; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + return _projectService.getProjectOwner(id).getId(); } - + } \ No newline at end of file diff --git a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java b/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java index dae85b488af..471d376d2e0 100644 --- a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java +++ b/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java @@ -37,7 +37,7 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn server") private Long publicIpId; - + // unexposed parameter needed for events logging @IdentityMapper(entityTableName="account") @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) @@ -45,43 +45,43 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { - if (ownerId == null) { - RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); - if(vpnEntity != null) - return vpnEntity.getAccountId(); - - throw new InvalidParameterValueException("The specified public ip is not allocated to any account"); - } - return ownerId; + @Override + public long getEntityOwnerId() { + if (ownerId == null) { + RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); + if(vpnEntity != null) + return vpnEntity.getAccountId(); + + throw new InvalidParameterValueException("The specified public ip is not allocated to any account", null); + } + return ownerId; } - @Override - public String getEventDescription() { - return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for ip id=" + publicIpId; + } - @Override - public String getEventType() { - return EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY; - } + @Override + public String getEventType() { + return EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY; + } @Override public void execute() throws ResourceUnavailableException { _ravService.destroyRemoteAccessVpn(publicIpId); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -91,5 +91,5 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _ravService.getRemoteAccessVpn(publicIpId).getNetworkId(); } - + } diff --git a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java b/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java index 3ffd1dc6fd7..9ee743021c8 100644 --- a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java +++ b/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java @@ -12,18 +12,18 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.commands; -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceInUseException; -import com.cloud.user.UserContext; +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.IdentityMapper; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.SuccessResponse; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceInUseException; +import com.cloud.user.UserContext; @Implementation(description="Deletes security group", responseObject=SuccessResponse.class) public class DeleteSecurityGroupCmd extends BaseCmd { @@ -40,7 +40,7 @@ public class DeleteSecurityGroupCmd extends BaseCmd { @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of account owning the security group") private Long domainId; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="the project of the security group") private Long projectId; @@ -48,7 +48,7 @@ public class DeleteSecurityGroupCmd extends BaseCmd { @IdentityMapper(entityTableName="security_group") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with name parameter") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="The ID of the security group. Mutually exclusive with id parameter") private String name; @@ -64,27 +64,27 @@ public class DeleteSecurityGroupCmd extends BaseCmd { public Long getDomainId() { return domainId; } - + public Long getProjectId() { return projectId; } public Long getId() { if (id != null && name != null) { - throw new InvalidParameterValueException("name and id parameters are mutually exclusive"); + throw new InvalidParameterValueException("name and id parameters are mutually exclusive", null); } - + if (name != null) { id = _responseGenerator.getSecurityGroupId(name, getEntityOwnerId()); if (id == null) { - throw new InvalidParameterValueException("Unable to find security group by name " + name + " for the account id=" + getEntityOwnerId()); + throw new InvalidParameterValueException("Unable to find security group by name " + name + " for the account id=" + getEntityOwnerId(), null); } } - + if (id == null) { - throw new InvalidParameterValueException("Either id or name parameter is requred by deleteSecurityGroup command"); + throw new InvalidParameterValueException("Either id or name parameter is requred by deleteSecurityGroup command", null); } - + return id; } @@ -98,17 +98,17 @@ public class DeleteSecurityGroupCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + @Override public void execute(){ try{ diff --git a/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java b/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java index a6fc85b798b..ae95d2ca4d3 100644 --- a/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java +++ b/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java @@ -57,7 +57,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +65,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_STATIC_ROUTE_DELETE; @@ -75,25 +75,25 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public String getEventDescription() { return ("Deleting static route id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { StaticRoute route = _entityMgr.findById(StaticRoute.class, id); if (route == null) { - throw new InvalidParameterValueException("Unable to find static route by id=" + id); + throw new InvalidParameterValueException("Unable to find static route by id", null); } else { ownerId = route.getAccountId(); } } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Route Id: " + id); boolean result = _vpcService.revokeStaticRoute(id); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -101,8 +101,8 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete static route"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -112,11 +112,11 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public Long getSyncObjId() { StaticRoute route = _vpcService.getStaticRoute(id); if (route == null) { - throw new InvalidParameterValueException("Invalid id is specified for the static route"); + throw new InvalidParameterValueException("Invalid id is specified for the static route", null); } return route.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StaticRoute; diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/com/cloud/api/commands/DeployVMCmd.java index a88449c7909..29eb9063b89 100644 --- a/api/src/com/cloud/api/commands/DeployVMCmd.java +++ b/api/src/com/cloud/api/commands/DeployVMCmd.java @@ -111,39 +111,40 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @IdentityMapper(entityTableName="host") @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="destination Host ID to deploy the VM to - parameter available for root admin only") private Long hostId; - + @IdentityMapper(entityTableName="security_group") @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter") private List securityGroupIdList; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAMES, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of security groups names that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter") private List securityGroupNameList; - + @Parameter(name = ApiConstants.IP_NETWORK_LIST, type = CommandType.MAP, description = "ip to network mapping. Can't be specified with networkIds parameter. Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].networkid=204 - requests to use ip 10.10.10.11 in network id=204") private Map ipToNetworkList; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="the ip address for default vm's network") private String ipAddress; - + @Parameter(name=ApiConstants.KEYBOARD, type=CommandType.STRING, description="an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us") private String keyboard; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Deploy vm for the project") private Long projectId; - + @Parameter(name=ApiConstants.START_VM, type=CommandType.BOOLEAN, description="true if network offering supports specifying ip ranges; defaulted to true if not specified") private Boolean startVm; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + @Override public String getEntityTable() { - return "vm_instance"; + return "vm_instance"; } - + public String getAccountName() { if (accountName == null) { return UserContext.current().getCaller().getAccountName(); @@ -176,16 +177,16 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { public List getSecurityGroupIdList() { if (securityGroupNameList != null && securityGroupIdList != null) { - throw new InvalidParameterValueException("securitygroupids parameter is mutually exclusive with securitygroupnames parameter"); + throw new InvalidParameterValueException("securitygroupids parameter is mutually exclusive with securitygroupnames parameter", null); } - - //transform group names to ids here - if (securityGroupNameList != null) { + + //transform group names to ids here + if (securityGroupNameList != null) { List securityGroupIds = new ArrayList(); for (String groupName : securityGroupNameList) { Long groupId = _responseGenerator.getSecurityGroupId(groupName, getEntityOwnerId()); if (groupId == null) { - throw new InvalidParameterValueException("Unable to find group by name " + groupName + " for account " + getEntityOwnerId()); + throw new InvalidParameterValueException("Unable to find group by name " + groupName + " for account " + getEntityOwnerId(), null); } else { securityGroupIds.add(groupId); } @@ -217,15 +218,15 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } public List getNetworkIds() { - if (ipToNetworkList != null) { - if (networkIds != null || ipAddress != null) { - throw new InvalidParameterValueException("ipToNetworkMap can't be specified along with networkIds or ipAddress"); - } else { - List networks = new ArrayList(); - networks.addAll(getIpToNetworkMap().keySet()); - return networks; - } - } + if (ipToNetworkList != null) { + if (networkIds != null || ipAddress != null) { + throw new InvalidParameterValueException("ipToNetworkMap can't be specified along with networkIds or ipAddress", null); + } else { + List networks = new ArrayList(); + networks.addAll(getIpToNetworkMap().keySet()); + return networks; + } + } return networkIds; } @@ -240,14 +241,14 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { public Long getHostId() { return hostId; } - + public boolean getStartVm() { return startVm == null ? true : startVm; } - + private Map getIpToNetworkMap() { if ((networkIds != null || ipAddress != null) && ipToNetworkList != null) { - throw new InvalidParameterValueException("NetworkIds and ipAddress can't be specified along with ipToNetworkMap parameter"); + throw new InvalidParameterValueException("NetworkIds and ipAddress can't be specified along with ipToNetworkMap parameter", null); } Map ipToNetworkMap = null; if (ipToNetworkList != null && !ipToNetworkList.isEmpty()) { @@ -257,11 +258,11 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { while (iter.hasNext()) { HashMap ips = (HashMap) iter.next(); Long networkId = Long.valueOf(_responseGenerator.getIdentiyId("networks", ips.get("networkid"))); - String requestedIp = (String) ips.get("ip"); + String requestedIp = ips.get("ip"); ipToNetworkMap.put(networkId, requestedIp); } } - + return ipToNetworkMap; } @@ -284,7 +285,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } @@ -316,7 +317,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @Override public void execute(){ UserVm result; - + if (getStartVm()) { try { UserContext.current().setEventDetails("Vm Id: "+getEntityId()); @@ -339,7 +340,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } else { result = _userVmService.getUserVm(getEntityId()); } - + if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); @@ -357,24 +358,24 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { DataCenter zone = _configService.getZone(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Unable to find zone by id=" + zoneId); + throw new InvalidParameterValueException("Unable to find zone by id", null); } ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find service offering by id", null); } VirtualMachineTemplate template = _templateService.getTemplate(templateId); // Make sure a valid template ID was specified if (template == null) { - throw new InvalidParameterValueException("Unable to use template " + templateId); + throw new InvalidParameterValueException("Unable to use template " + templateId, null); } - + if (diskOfferingId != null) { DiskOffering diskOffering = _configService.getDiskOffering(diskOfferingId); if (diskOffering == null) { - throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId); + throw new InvalidParameterValueException("Unable to find disk offering by id", null); } } @@ -384,7 +385,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } else { if (zone.getNetworkType() == NetworkType.Basic) { if (getNetworkIds() != null) { - throw new InvalidParameterValueException("Can't specify network Ids in Basic zone"); + throw new InvalidParameterValueException("Can't specify network Ids in Basic zone", null); } else { vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(), owner, name, displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); @@ -395,7 +396,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { owner, name, displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); } else { if (getSecurityGroupIdList() != null && !getSecurityGroupIdList().isEmpty()) { - throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone"); + throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone", null); } vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, getNetworkIds(), owner, name, displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); diff --git a/api/src/com/cloud/api/commands/DetachIsoCmd.java b/api/src/com/cloud/api/commands/DetachIsoCmd.java index 68d3e9123b7..70d68c1f79d 100755 --- a/api/src/com/cloud/api/commands/DetachIsoCmd.java +++ b/api/src/com/cloud/api/commands/DetachIsoCmd.java @@ -63,7 +63,7 @@ public class DetachIsoCmd extends BaseAsyncCmd { if (vm != null) { return vm.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find vm by id " + getVirtualMachineId()); + throw new InvalidParameterValueException("Unable to find vm by id", null); } } @@ -76,7 +76,7 @@ public class DetachIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "detaching ISO from vm: " + getVirtualMachineId(); } - + @Override public void execute(){ boolean result = _templateService.detachIso(virtualMachineId); diff --git a/api/src/com/cloud/api/commands/DisableStaticNatCmd.java b/api/src/com/cloud/api/commands/DisableStaticNatCmd.java index 020e1214ad2..9291e229044 100644 --- a/api/src/com/cloud/api/commands/DisableStaticNatCmd.java +++ b/api/src/com/cloud/api/commands/DisableStaticNatCmd.java @@ -41,7 +41,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP address id for which static nat feature is being disableed") private Long ipAddressId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -49,7 +49,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public Long getIpAddress() { return ipAddressId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -57,7 +57,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_DISABLE_STATIC_NAT; @@ -67,16 +67,16 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Disabling static nat for ip id=" + ipAddressId); } - + @Override public long getEntityOwnerId() { return _entityMgr.findById(IpAddress.class, ipAddressId).getAccountId(); } - + @Override public void execute() throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException { boolean result = _rulesService.disableStaticNat(ipAddressId); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -84,8 +84,8 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable static nat"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -99,7 +99,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { private IpAddress getIp() { IpAddress ip = _networkService.getIp(ipAddressId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } diff --git a/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java b/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java index ea19ea319c6..cfa31810ef3 100644 --- a/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java +++ b/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java @@ -42,7 +42,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the public ip address" + - " to disassociate") + " to disassociate") private Long id; // unexposed parameter needed for events logging @@ -77,7 +77,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disassociate ip address"); } } - + @Override public String getEventType() { return EventTypes.EVENT_NET_IP_RELEASE; @@ -87,23 +87,23 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Disassociating ip address with id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { IpAddress ip = getIpAddress(id); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + id); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } ownerId = ip.getAccountId(); } - + if (ownerId == null) { return Account.ACCOUNT_ID_SYSTEM; } return ownerId; } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -114,22 +114,22 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { IpAddress ip = getIpAddress(id); return ip.getAssociatedWithNetworkId(); } - + private IpAddress getIpAddress(long id) { IpAddress ip = _entityMgr.findById(IpAddress.class, id); - + if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + id); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } else { return ip; } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; } - + @Override public Long getInstanceId() { return getIpAddressId(); diff --git a/api/src/com/cloud/api/commands/EnableStaticNatCmd.java b/api/src/com/cloud/api/commands/EnableStaticNatCmd.java index a8cd131f1c2..5b269fb7321 100644 --- a/api/src/com/cloud/api/commands/EnableStaticNatCmd.java +++ b/api/src/com/cloud/api/commands/EnableStaticNatCmd.java @@ -40,18 +40,18 @@ public class EnableStaticNatCmd extends BaseCmd{ @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP " + - "address id for which static nat feature is being enabled") + "address id for which static nat feature is being enabled") private Long ipAddressId; @IdentityMapper(entityTableName="vm_instance") @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of " + - "the virtual machine for enabling static nat feature") + "the virtual machine for enabling static nat feature") private Long virtualMachineId; @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, - description="The network of the vm the static nat will be enabled for." + - " Required when public Ip address is not associated with any Guest network yet (VPC case)") + description="The network of the vm the static nat will be enabled for." + + " Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; ///////////////////////////////////////////////////// @@ -69,7 +69,7 @@ public class EnableStaticNatCmd extends BaseCmd{ public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } else { @@ -77,7 +77,7 @@ public class EnableStaticNatCmd extends BaseCmd{ } if (ntwkId == null) { throw new InvalidParameterValueException("Unable to enable static nat for the ipAddress id=" + ipAddressId + - " as ip is not associated with any network and no networkId is passed in"); + " as ip is not associated with any network and no networkId is passed in", null); } return ntwkId; } @@ -90,7 +90,7 @@ public class EnableStaticNatCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); diff --git a/api/src/com/cloud/api/commands/ListCapacityCmd.java b/api/src/com/cloud/api/commands/ListCapacityCmd.java index 61a859d9128..63ddeab8303 100755 --- a/api/src/com/cloud/api/commands/ListCapacityCmd.java +++ b/api/src/com/cloud/api/commands/ListCapacityCmd.java @@ -38,7 +38,7 @@ public class ListCapacityCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="lists capacity by the Zone ID") private Long zoneId; @@ -46,28 +46,28 @@ public class ListCapacityCmd extends BaseListCmd { @IdentityMapper(entityTableName="host_pod_ref") @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="lists capacity by the Pod ID") private Long podId; - + @IdentityMapper(entityTableName="cluster") @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, since="3.0.0", description="lists capacity by the Cluster ID") private Long clusterId; @Parameter(name=ApiConstants.FETCH_LATEST, type=CommandType.BOOLEAN, since="3.0.0", description="recalculate capacities and fetch the latest") private Boolean fetchLatest; - + @Parameter(name=ApiConstants.TYPE, type=CommandType.INTEGER, description="lists capacity by type" + - "* CAPACITY_TYPE_MEMORY = 0" + - "* CAPACITY_TYPE_CPU = 1" + - "* CAPACITY_TYPE_STORAGE = 2" + - "* CAPACITY_TYPE_STORAGE_ALLOCATED = 3" + - "* CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4" + - "* CAPACITY_TYPE_PRIVATE_IP = 5" + - "* CAPACITY_TYPE_SECONDARY_STORAGE = 6" + - "* CAPACITY_TYPE_VLAN = 7" + - "* CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8" + - "* CAPACITY_TYPE_LOCAL_STORAGE = 9.") + "* CAPACITY_TYPE_MEMORY = 0" + + "* CAPACITY_TYPE_CPU = 1" + + "* CAPACITY_TYPE_STORAGE = 2" + + "* CAPACITY_TYPE_STORAGE_ALLOCATED = 3" + + "* CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4" + + "* CAPACITY_TYPE_PRIVATE_IP = 5" + + "* CAPACITY_TYPE_SECONDARY_STORAGE = 6" + + "* CAPACITY_TYPE_VLAN = 7" + + "* CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8" + + "* CAPACITY_TYPE_LOCAL_STORAGE = 9.") private Integer type; - + @Parameter(name=ApiConstants.SORT_BY, type=CommandType.STRING, since="3.0.0", description="Sort the results. Available values: Usage") private String sortBy; @@ -78,32 +78,32 @@ public class ListCapacityCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public Long getPodId() { return podId; } public Long getClusterId() { - return clusterId; - } + return clusterId; + } - public Boolean getFetchLatest() { - return fetchLatest; - } + public Boolean getFetchLatest() { + return fetchLatest; + } - public Integer getType() { + public Integer getType() { return type; } - + public String getSortBy() { if (sortBy != null) { if (sortBy.equalsIgnoreCase("usage")) { return sortBy; } else { - throw new InvalidParameterValueException("Only value supported for sortBy parameter is : usage"); + throw new InvalidParameterValueException("Only value supported for sortBy parameter is : usage", null); } } - + return null; } @@ -115,7 +115,7 @@ public class ListCapacityCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List result = null; @@ -124,7 +124,7 @@ public class ListCapacityCmd extends BaseListCmd { } else { result = _mgr.listCapacities(this); } - + ListResponse response = new ListResponse(); List capacityResponses = _responseGenerator.createCapacityResponse(result, s_percentFormat); response.setResponses(capacityResponses); diff --git a/api/src/com/cloud/api/commands/ListHostsCmd.java b/api/src/com/cloud/api/commands/ListHostsCmd.java index a9d272ddddd..027585e7728 100755 --- a/api/src/com/cloud/api/commands/ListHostsCmd.java +++ b/api/src/com/cloud/api/commands/ListHostsCmd.java @@ -69,16 +69,16 @@ public class ListHostsCmd extends BaseListCmd { @IdentityMapper(entityTableName="vm_instance") @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=false, description="lists hosts in the same cluster as this VM and flag hosts with enough CPU/RAm to host this VM") private Long virtualMachineId; - + @Parameter(name=ApiConstants.RESOURCE_STATE, type=CommandType.STRING, description="list hosts by resource state. Resource state represents current state determined by admin of host, valule can be one of [Enabled, Disabled, Unmanaged, PrepareForMaintenance, ErrorInMaintenance, Maintenance, Error]") private String resourceState; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of host details requested, value can be a list of [ min, all, capacity, events, stats]" ) private List viewDetails; - + @Parameter(name=ApiConstants.HA_HOST, type=CommandType.BOOLEAN, description="if true, list only hosts dedicated to HA") private Boolean haHost; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -106,7 +106,7 @@ public class ListHostsCmd extends BaseListCmd { public String getType() { return type; } - + public Boolean getHaHost() { return haHost; } @@ -118,7 +118,7 @@ public class ListHostsCmd extends BaseListCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public EnumSet getDetails() throws InvalidParameterValueException { EnumSet dv; if (viewDetails==null || viewDetails.size() <=0){ @@ -133,14 +133,14 @@ public class ListHostsCmd extends BaseListCmd { dv = EnumSet.copyOf(dc); } catch (IllegalArgumentException e){ - throw new InvalidParameterValueException("The details parameter contains a non permitted value. The allowed values are " + EnumSet.allOf(HostDetails.class)); + throw new InvalidParameterValueException("The details parameter contains a non permitted value. The allowed values are " + EnumSet.allOf(HostDetails.class), null); } } return dv; } - + public String getResourceState() { - return resourceState; + return resourceState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -150,23 +150,24 @@ public class ListHostsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } @Override public void execute(){ - List result = new ArrayList(); - List hostsWithCapacity = new ArrayList(); - - if(getVirtualMachineId() != null){ + List result = new ArrayList(); + List hostsWithCapacity = new ArrayList(); + + if(getVirtualMachineId() != null){ Pair, List> hostsForMigration = _mgr.listHostsForMigrationOfVM(getVirtualMachineId(), this.getStartIndex(), this.getPageSizeVal()); result = hostsForMigration.first(); hostsWithCapacity = hostsForMigration.second(); - }else{ - result = _mgr.searchForServers(this); - } + }else{ + result = _mgr.searchForServers(this); + } ListResponse response = new ListResponse(); List hostResponses = new ArrayList(); diff --git a/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java b/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java index fe74691aad4..22b1c202193 100644 --- a/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java +++ b/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java @@ -33,21 +33,21 @@ import com.cloud.user.Account; public class ListSupportedNetworkServicesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSupportedNetworkServicesCmd.class.getName()); private static final String _name = "listsupportednetworkservicesresponse"; - + @Parameter(name=ApiConstants.PROVIDER, type=CommandType.STRING, description="network service provider name") private String providerName; - + @Parameter(name=ApiConstants.SERVICE, type=CommandType.STRING, description="network service name to list providers and capabilities of") private String serviceName; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setProviderName(String providerName) { this.providerName = providerName; @@ -74,7 +74,7 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ List services; @@ -83,7 +83,7 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { if(serviceName != null){ service = Network.Service.getService(serviceName); if(service == null){ - throw new InvalidParameterValueException("Invalid Network Service=" + serviceName); + throw new InvalidParameterValueException("Invalid Network Service=" + serviceName, null); } } List serviceList = new ArrayList(); @@ -92,14 +92,14 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { }else{ services = _networkService.listNetworkServices(getProviderName()); } - + ListResponse response = new ListResponse(); List servicesResponses = new ArrayList(); for (Network.Service service : services) { - //skip gateway service - if (service == Service.Gateway) { - continue; - } + //skip gateway service + if (service == Service.Gateway) { + continue; + } ServiceResponse serviceResponse = _responseGenerator.createNetworkServiceResponse(service); servicesResponses.add(serviceResponse); } diff --git a/api/src/com/cloud/api/commands/ListVMsCmd.java b/api/src/com/cloud/api/commands/ListVMsCmd.java index e1e527930c5..8919a2a26b2 100755 --- a/api/src/com/cloud/api/commands/ListVMsCmd.java +++ b/api/src/com/cloud/api/commands/ListVMsCmd.java @@ -65,25 +65,25 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the availability zone ID") private Long zoneId; - + @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="list by network type; true if need to list vms using Virtual Network, false otherwise") private Boolean forVirtualNetwork; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list by network id") private Long networkId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the target hypervisor for the template") private String hypervisor; - + @IdentityMapper(entityTableName="storage_pool") @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, description="the storage ID where vm's volumes belong to") private Long storageId; @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of host details requested, " + - "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min]. If no parameter is passed in, the details will be defaulted to all" ) + "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min]. If no parameter is passed in, the details will be defaulted to all" ) private List viewDetails; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -116,7 +116,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public Boolean getForVirtualNetwork() { return forVirtualNetwork; } @@ -124,19 +124,19 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public void setForVirtualNetwork(Boolean forVirtualNetwork) { this.forVirtualNetwork = forVirtualNetwork; } - + public Long getNetworkId() { return networkId; } - + public String getHypervisor() { - return hypervisor; - } - + return hypervisor; + } + public Long getStorageId() { return storageId; } - + public EnumSet getDetails() throws InvalidParameterValueException { EnumSet dv; if (viewDetails==null || viewDetails.size() <=0){ @@ -151,39 +151,40 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { dv = EnumSet.copyOf(dc); } catch (IllegalArgumentException e){ - throw new InvalidParameterValueException("The details parameter contains a non permitted value. The allowed values are " + EnumSet.allOf(VMDetails.class)); + throw new InvalidParameterValueException("The details parameter contains a non permitted value. The allowed values are " + EnumSet.allOf(VMDetails.class), null); } } return dv; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override - public String getCommandName() { + public String getCommandName() { return s_name; } - + + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - @Override + @Override public void execute(){ List result = _userVmService.searchForUserVMs(this); ListResponse response = new ListResponse(); EnumSet details = getDetails(); List vmResponses; if (details.contains(VMDetails.all)){ // for all use optimized version - vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", result.toArray(new UserVm[result.size()])); + vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", result.toArray(new UserVm[result.size()])); } else { - vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", getDetails(), result.toArray(new UserVm[result.size()])); + vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", getDetails(), result.toArray(new UserVm[result.size()])); } response.setResponses(vmResponses); response.setResponseName(getCommandName()); this.setResponseObject(response); } - + } diff --git a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java b/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java index e85070eef28..f55eb24e0f1 100644 --- a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java +++ b/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java @@ -73,7 +73,7 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -93,38 +93,38 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId(); } - + @Override public void execute(){ - + Host destinationHost = _resourceService.getHost(getHostId()); if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); + throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId(), null); } try{ - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); - //FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer - VirtualMachine migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); - if (migratedVm != null) { - // return the generic system VM instance response - SystemVmInstanceResponse response = _responseGenerator.createSystemVmInstanceResponse(migratedVm); + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); + //FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer + VirtualMachine migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); + if (migratedVm != null) { + // return the generic system VM instance response + SystemVmInstanceResponse response = _responseGenerator.createSystemVmInstanceResponse(migratedVm); response.setResponseName(getCommandName()); this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); - } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (ManagementServerException e) { + } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (VirtualMachineMigrationException e) { + } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/MigrateVMCmd.java b/api/src/com/cloud/api/commands/MigrateVMCmd.java index 942d1fec41f..d63698cb904 100644 --- a/api/src/com/cloud/api/commands/MigrateVMCmd.java +++ b/api/src/com/cloud/api/commands/MigrateVMCmd.java @@ -68,9 +68,9 @@ public class MigrateVMCmd extends BaseAsyncCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public Long getStoragePoolId() { - return storageId; + return storageId; } @@ -82,7 +82,7 @@ public class MigrateVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); @@ -102,66 +102,66 @@ public class MigrateVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId(); } - + @Override public void execute(){ - if (getHostId() == null && getStoragePoolId() == null) { - throw new InvalidParameterValueException("either hostId or storageId must be specified"); - } - - if (getHostId() != null && getStoragePoolId() != null) { - throw new InvalidParameterValueException("only one of hostId and storageId can be specified"); - } - + if (getHostId() == null && getStoragePoolId() == null) { + throw new InvalidParameterValueException("either hostId or storageId must be specified", null); + } + + if (getHostId() != null && getStoragePoolId() != null) { + throw new InvalidParameterValueException("only one of hostId and storageId can be specified", null); + } + UserVm userVm = _userVmService.getUserVm(getVirtualMachineId()); if (userVm == null) { - throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId()); + throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId(), null); } - + Host destinationHost = null; if (getHostId() != null) { - destinationHost = _resourceService.getHost(getHostId()); - if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); - } - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); + destinationHost = _resourceService.getHost(getHostId()); + if (destinationHost == null) { + throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId(), null); + } + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); } - + StoragePool destStoragePool = null; if (getStoragePoolId() != null) { - destStoragePool = _storageService.getStoragePool(getStoragePoolId()); - if (destStoragePool == null) { - throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM"); - } - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: "+ getStoragePoolId()); + destStoragePool = _storageService.getStoragePool(getStoragePoolId()); + if (destStoragePool == null) { + throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM", null); + } + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: "+ getStoragePoolId()); } - + try{ - VirtualMachine migratedVm = null; - if (getHostId() != null) { - migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); - } else if (getStoragePoolId() != null) { - migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool); - } - if (migratedVm != null) { + VirtualMachine migratedVm = null; + if (getHostId() != null) { + migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); + } else if (getStoragePoolId() != null) { + migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool); + } + if (migratedVm != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", (UserVm)migratedVm).get(0); response.setResponseName(getCommandName()); this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); - } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (ManagementServerException e) { + } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (VirtualMachineMigrationException e) { + } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java index 6c99ccb3730..74b0c536797 100644 --- a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java +++ b/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java @@ -36,7 +36,7 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RemoveFromLoadBalancerRuleCmd.class.getName()); private static final String s_name = "removefromloadbalancerruleresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -100,7 +100,7 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove instance from load balancer rule"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -108,10 +108,10 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule by id", null); + } return lb.getNetworkId(); } } diff --git a/api/src/com/cloud/api/commands/RestartNetworkCmd.java b/api/src/com/cloud/api/commands/RestartNetworkCmd.java index 552c4fbe2f8..8c3e8c05f04 100644 --- a/api/src/com/cloud/api/commands/RestartNetworkCmd.java +++ b/api/src/com/cloud/api/commands/RestartNetworkCmd.java @@ -40,7 +40,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The id of the network to restart.") private Long id; @@ -52,16 +52,16 @@ public class RestartNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getNetworkId() { Network network = _networkService.getNetwork(id); if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + id); + throw new InvalidParameterValueException("Unable to find network by id", null); } else { return network.getId(); } } - + public Boolean getCleanup() { if (cleanup != null) { return cleanup; @@ -83,7 +83,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { public static String getResultObjectName() { return "addressinfo"; } - + @Override public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { boolean result = _networkService.restartNetwork(this, getCleanup()); @@ -94,7 +94,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restart network"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -104,21 +104,22 @@ public class RestartNetworkCmd extends BaseAsyncCmd { public Long getSyncObjId() { return id; } - + + @Override public String getEventDescription() { return "Restarting network: " + getNetworkId(); } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_RESTART; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { - throw new InvalidParameterValueException("Networkd id=" + id + " doesn't exist"); + throw new InvalidParameterValueException("Couldn't find network by id", null); } else { return _networkService.getNetwork(id).getAccountId(); } diff --git a/api/src/com/cloud/api/commands/SuspendProjectCmd.java b/api/src/com/cloud/api/commands/SuspendProjectCmd.java index c3d9a69c48f..177f801bf80 100644 --- a/api/src/com/cloud/api/commands/SuspendProjectCmd.java +++ b/api/src/com/cloud/api/commands/SuspendProjectCmd.java @@ -73,26 +73,26 @@ public class SuspendProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to suspend a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_SUSPEND; } - + @Override public String getEventDescription() { return "Suspending project: " + id; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + return _projectService.getProjectOwner(id).getId(); } - + } \ No newline at end of file diff --git a/api/src/com/cloud/api/commands/UpdateClusterCmd.java b/api/src/com/cloud/api/commands/UpdateClusterCmd.java index 5de22567a61..459c884ef43 100755 --- a/api/src/com/cloud/api/commands/UpdateClusterCmd.java +++ b/api/src/com/cloud/api/commands/UpdateClusterCmd.java @@ -12,18 +12,18 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.commands; -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ClusterResponse; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.org.Cluster; -import com.cloud.user.Account; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.ClusterResponse; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.org.Cluster; +import com.cloud.user.Account; @Implementation(description="Updates an existing cluster", responseObject=ClusterResponse.class) public class UpdateClusterCmd extends BaseCmd { @@ -34,22 +34,22 @@ public class UpdateClusterCmd extends BaseCmd { @IdentityMapper(entityTableName="cluster") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Cluster") private Long id; - + @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name") private String clusterName; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="hypervisor type of the cluster") private String hypervisor; - + @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, description="hypervisor type of the cluster") private String clusterType; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; - + @Parameter(name=ApiConstants.MANAGED_STATE, type=CommandType.STRING, description="whether this cluster is managed by cloudstack") private String managedState; - + public String getClusterName() { return clusterName; } @@ -59,33 +59,33 @@ public class UpdateClusterCmd extends BaseCmd { } public String getHypervisor() { - return hypervisor; + return hypervisor; } - + @Override public String getCommandName() { - return s_name; + return s_name; } - + public String getClusterType() { - return clusterType; + return clusterType; } - + public void setClusterType(String type) { - this.clusterType = type; + this.clusterType = type; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } public String getManagedstate() { @@ -98,16 +98,16 @@ public class UpdateClusterCmd extends BaseCmd { @Override public void execute(){ - Cluster cluster = _resourceService.getCluster(getId()); + Cluster cluster = _resourceService.getCluster(getId()); if (cluster == null) { - throw new InvalidParameterValueException("Unable to find the cluster by id=" + getId()); + throw new InvalidParameterValueException("Unable to find the cluster by id", null); } - + Cluster result = _resourceService.updateCluster(cluster, getClusterType(), getHypervisor(), getAllocationState(), getManagedstate()); if (result != null) { - ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); - clusterResponse.setResponseName(getCommandName()); - this.setResponseObject(clusterResponse); + ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); + clusterResponse.setResponseName(getCommandName()); + this.setResponseObject(clusterResponse); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update cluster"); } diff --git a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkCmd.java index 22d111d33ac..f104b5ca9ae 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/UpdateNetworkCmd.java @@ -43,43 +43,43 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the new name for the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the new display text for the network") private String displayText; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - + @Parameter(name=ApiConstants.CHANGE_CIDR, type=CommandType.BOOLEAN, description="Force update even if cidr type is different") private Boolean changeCidr; - + @IdentityMapper(entityTableName="network_offerings") @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, description="network offering ID") private Long networkOfferingId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } - + private String getNetworkDomain() { return networkDomain; } - + private Long getNetworkOfferingId() { return networkOfferingId; } @@ -98,17 +98,17 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { - throw new InvalidParameterValueException("Networkd id=" + id + " doesn't exist"); + throw new InvalidParameterValueException("Couldn't find network by id", null); } else { return _networkService.getNetwork(id).getAccountId(); } } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException{ User callerUser = _accountService.getActiveUser(UserContext.current().getCallerUserId()); @@ -123,12 +123,12 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update network"); } } - + @Override public String getEventDescription() { return "Updating network: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; diff --git a/api/src/com/cloud/api/commands/UpdateProjectCmd.java b/api/src/com/cloud/api/commands/UpdateProjectCmd.java index 156f2afe5e3..f35b16ebc38 100644 --- a/api/src/com/cloud/api/commands/UpdateProjectCmd.java +++ b/api/src/com/cloud/api/commands/UpdateProjectCmd.java @@ -37,14 +37,14 @@ public class UpdateProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be modified") private Long id; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="new Admin account for the project") private String accountName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="display text of the project") private String displayText; @@ -68,18 +68,18 @@ public class UpdateProjectCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); + throw new InvalidParameterValueException("Unable to find project by id ", null); } - + return _projectService.getProjectOwner(id).getId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -97,12 +97,12 @@ public class UpdateProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_UPDATE; } - + @Override public String getEventDescription() { return "Updating project: " + id; diff --git a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java b/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java index 8223228d58f..53d6fa2e0c5 100755 --- a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java +++ b/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java @@ -44,13 +44,13 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { @Parameter(name = ApiConstants.IS_PUBLIC, type = CommandType.BOOLEAN, description = "true for public template/iso, false for private templates/isos") private Boolean isPublic; - + @Parameter(name = ApiConstants.IS_EXTRACTABLE, type = CommandType.BOOLEAN, description = "true if the template/iso is extractable, false other wise. Can be set only by root admin") private Boolean isExtractable; @Parameter(name = ApiConstants.OP, type = CommandType.STRING, description = "permission operator (add, remove, reset)") private String operation; - + @IdentityMapper(entityTableName="projects") @Parameter(name = ApiConstants.PROJECT_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, description = "a comma delimited list of projects. If specified, \"op\" parameter has to be passed in.") private List projectIds; @@ -61,9 +61,9 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public List getAccountNames() { if (accountNames != null && projectIds != null) { - throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); + throw new InvalidParameterValueException("Accounts and projectIds can't be specified together", null); } - + return accountNames; } @@ -78,18 +78,18 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public Boolean isPublic() { return isPublic; } - + public Boolean isExtractable() { return isExtractable; } - + public String getOperation() { return operation; } - + public List getProjectIds() { if (accountNames != null && projectIds != null) { - throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); + throw new InvalidParameterValueException("Accounts and projectIds can't be specified together", null); } return projectIds; } diff --git a/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java b/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java index b690ab23d0a..4d2c6971bb4 100644 --- a/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java +++ b/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java @@ -33,8 +33,8 @@ import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; @Implementation(responseObject=SystemVmResponse.class, description="Changes the service offering for a system vm (console proxy or secondary storage). " + - "The system vm must be in a \"Stopped\" state for " + - "this command to take effect.") + "The system vm must be in a \"Stopped\" state for " + + "this command to take effect.") public class UpgradeSystemVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforsystemvmresponse"; @@ -49,7 +49,7 @@ public class UpgradeSystemVMCmd extends BaseCmd { @IdentityMapper(entityTableName="disk_offering") @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, - description="the service offering ID to apply to the system vm") + description="the service offering ID to apply to the system vm") private Long serviceOfferingId; ///////////////////////////////////////////////////// @@ -72,7 +72,7 @@ public class UpgradeSystemVMCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -82,16 +82,16 @@ public class UpgradeSystemVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); - + ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find service offering by id", null); } - + VirtualMachine result = _mgr.upgradeSystemVM(this); if (result != null) { SystemVmResponse response = _responseGenerator.createSystemVmResponse(result); diff --git a/api/src/com/cloud/api/commands/UpgradeVMCmd.java b/api/src/com/cloud/api/commands/UpgradeVMCmd.java index 4ab43a1bfcf..a492b624afe 100644 --- a/api/src/com/cloud/api/commands/UpgradeVMCmd.java +++ b/api/src/com/cloud/api/commands/UpgradeVMCmd.java @@ -28,8 +28,8 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; @Implementation(responseObject=UserVmResponse.class, description="Changes the service offering for a virtual machine. " + - "The virtual machine must be in a \"Stopped\" state for " + - "this command to take effect.") + "The virtual machine must be in a \"Stopped\" state for " + + "this command to take effect.") public class UpgradeVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforvirtualmachineresponse"; @@ -68,9 +68,9 @@ public class UpgradeVMCmd extends BaseCmd { } public static String getResultObjectName() { - return "virtualmachine"; + return "virtualmachine"; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -80,16 +80,16 @@ public class UpgradeVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); - + ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find service offering by id", null); } - + UserVm result = _userVmService.upgradeVirtualMachine(this); if (result != null){ UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); diff --git a/api/src/com/cloud/exception/InvalidParameterValueException.java b/api/src/com/cloud/exception/InvalidParameterValueException.java index 2b3122f667e..30b774b1163 100644 --- a/api/src/com/cloud/exception/InvalidParameterValueException.java +++ b/api/src/com/cloud/exception/InvalidParameterValueException.java @@ -12,6 +12,9 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.exception; +import java.util.List; + +import com.cloud.utils.IdentityProxy; import com.cloud.utils.exception.CloudRuntimeException; /** @@ -26,4 +29,13 @@ public class InvalidParameterValueException extends CloudRuntimeException { super(message); } + public InvalidParameterValueException(String message, List idProxyList) { + super(message); + if (idProxyList != null) { + for (IdentityProxy id : idProxyList) { + this.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); + } + } + } + } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index e135264d3a4..dea6f5f6b86 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -179,6 +179,7 @@ import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserStatisticsDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; @@ -353,7 +354,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List getElementServices(Provider provider) { NetworkElement element = getElementImplementingProvider(provider.getName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'", null); } return new ArrayList(element.getCapabilities().keySet()); } @@ -362,7 +363,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean canElementEnableIndividualServices(Provider provider) { NetworkElement element = getElementImplementingProvider(provider.getName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'", null); } return element.canEnableIndividualServices(); } @@ -375,7 +376,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @DB public PublicIp fetchNewPublicIp(long dcId, Long podId, Long vlanDbId, Account owner, VlanType vlanUse, Long guestNetworkId, boolean sourceNat, boolean assign, String requestedIp, boolean isSystem, Long vpcId) - throws InsufficientAddressCapacityException { + throws InsufficientAddressCapacityException { StringBuilder errorMessage = new StringBuilder("Unable to get ip adress in "); Transaction txn = Transaction.currentTxn(); txn.start(); @@ -418,15 +419,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (podId != null) { InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Insufficient address capacity", Pod.class, podId); - // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object. - ex.addProxyObject("Pod", podId, "podId"); - throw ex; + // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object. + ex.addProxyObject("Pod", podId, "podId"); + throw ex; } s_logger.warn(errorMessage.toString()); InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Insufficient address capacity", DataCenter.class, dcId); ex.addProxyObject("data_center", dcId, "dcId"); - throw ex; + throw ex; } assert (addrs.size() == 1) : "Return size is incorrect: " + addrs.size(); @@ -482,7 +483,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag VlanVO vlan = _vlanDao.findById(addr.getVlanId()); String guestType = vlan.getVlanType().toString(); - + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), addr.isSourceNat(), guestType, addr.getSystem()); @@ -496,34 +497,34 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.commit(); } - + @Override public PublicIp assignSourceNatIpAddressToVpc(Account owner, Vpc vpc) throws InsufficientAddressCapacityException, ConcurrentOperationException { long dcId = vpc.getZoneId(); - + IPAddressVO sourceNatIp = getExistingSourceNat(owner.getId(), null, vpc.getId()); - + PublicIp ipToReturn = null; - + if (sourceNatIp != null) { ipToReturn = new PublicIp(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(sourceNatIp.getMacAddress())); } else { ipToReturn = assignSourceNatIpAddress(owner, null, vpc.getId(), dcId); } - + return ipToReturn; } - + @Override public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException { assert (guestNetwork.getTrafficType() != null) : "You're asking for a source nat but your network " + - "can't participate in source nat. What do you have to say for yourself?"; + "can't participate in source nat. What do you have to say for yourself?"; long dcId = guestNetwork.getDataCenterId(); - + IPAddressVO sourceNatIp = getExistingSourceNat(owner.getId(), guestNetwork.getId(), guestNetwork.getVpcId()); - + PublicIp ipToReturn = null; if (sourceNatIp != null) { ipToReturn = new PublicIp(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()), @@ -531,7 +532,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { ipToReturn = assignSourceNatIpAddress(owner, guestNetwork.getId(), null, dcId); } - + return ipToReturn; } @@ -557,24 +558,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag owner = _accountDao.acquireInLockTable(ownerId); if (owner == null) { - // this ownerId comes from owner or type Account. See the class "AccountVO" and the annotations in that class - // to get the table name and field name that is queried to fill this ownerid. - ConcurrentOperationException ex = new ConcurrentOperationException("Unable to lock account"); + // this ownerId comes from owner or type Account. See the class "AccountVO" and the annotations in that class + // to get the table name and field name that is queried to fill this ownerid. + ConcurrentOperationException ex = new ConcurrentOperationException("Unable to lock account"); } if (s_logger.isDebugEnabled()) { s_logger.debug("lock account " + ownerId + " is acquired"); } - // If account has Account specific ip ranges, try to allocate ip from there - Long vlanId = null; - List maps = _accountVlanMapDao.listAccountVlanMapsByAccount(ownerId); - if (maps != null && !maps.isEmpty()) { - //check if the ips from this vlan are associated with this network - List ips = _ipAddressDao.listByVlanId(maps.get(0).getVlanDbId()); - if (ips != null && !ips.isEmpty() && ips.get(0).getAssociatedWithNetworkId() == guestNtwkId) { - vlanId = maps.get(0).getVlanDbId(); - } + // If account has Account specific ip ranges, try to allocate ip from there + Long vlanId = null; + List maps = _accountVlanMapDao.listAccountVlanMapsByAccount(ownerId); + if (maps != null && !maps.isEmpty()) { + //check if the ips from this vlan are associated with this network + List ips = _ipAddressDao.listByVlanId(maps.get(0).getVlanDbId()); + if (ips != null && !ips.isEmpty() && ips.get(0).getAssociatedWithNetworkId() == guestNtwkId) { + vlanId = maps.get(0).getVlanDbId(); } + } ip = fetchNewPublicIp(dcId, null, vlanId, owner, VlanType.VirtualNetwork, guestNtwkId, true, false, null, false, vpcId); @@ -616,7 +617,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // The admin is making the call, determine if it is for someone else or for himself if (domainId != null) { if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { - // TBD: Check if call to addProxyObject() needs correction. + // TBD: Check if call to addProxyObject() needs correction. PermissionDeniedException ex = new PermissionDeniedException("Invalid domain id given, permission denied"); ex.addProxyObject("domain", domainId, "domainId"); throw ex; @@ -626,10 +627,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (userAccount != null) { account = userAccount; } else { - // TBD: Check if call to addProxyObject() needs correction. - PermissionDeniedException ex = new PermissionDeniedException("Unable to find account " + accountName + " in specified domain, permission denied"); - ex.addProxyObject("domain", domainId, "domainId"); - throw ex; + // TBD: Check if call to addProxyObject() needs correction. + PermissionDeniedException ex = new PermissionDeniedException("Unable to find account " + accountName + " in specified domain, permission denied"); + ex.addProxyObject("domain", domainId, "domainId"); + throw ex; } } } else { @@ -720,10 +721,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag services.add(Service.SourceNat); networkSNAT.add(ip.getAssociatedWithNetworkId()); } else { - CloudRuntimeException ex = new CloudRuntimeException("Multiple generic soure NAT IPs provided for network"); - // see the IPAddressVO.java class. - ex.addProxyObject("user_ip_address", ip.getAssociatedWithNetworkId(), "networkId"); - throw ex; + CloudRuntimeException ex = new CloudRuntimeException("Multiple generic soure NAT IPs provided for network"); + // see the IPAddressVO.java class. + ex.addProxyObject("user_ip_address", ip.getAssociatedWithNetworkId(), "networkId"); + throw ex; } } ipToServices.put(ip, services); @@ -747,7 +748,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (purposes == null || purposes.isEmpty()) { // since no active rules are there check if any rules are applied on the public IP but are in // revoking state - + purposes = getPublicIpPurposeInRules(ip, true, includingFirewall); if (ip.isOneToOneNat()) { if (purposes == null) { @@ -863,7 +864,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // We only support one provider for one service now Map> serviceToProviders = getServiceProvidersMap(publicIp.getAssociatedWithNetworkId()); - Set oldProviders = serviceToProviders.get((Service) services.toArray()[0]); + Set oldProviders = serviceToProviders.get(services.toArray()[0]); Provider oldProvider = (Provider) oldProviders.toArray()[0]; // Since IP already has service to bind with, the oldProvider can't be null Set newProviders = serviceToProviders.get(service); @@ -1014,7 +1015,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _networksDao.listBy(owner.getId(), zoneId, Network.GuestType.Isolated); } - + @Override public List getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner) { @@ -1079,10 +1080,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag false, assign, null, isSystem, null); if (ip == null) { - InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException - ("Unable to find available public IP addresses", DataCenter.class, zone.getId()); - ex.addProxyObject("data_center", zone.getId(), "zoneId"); - throw ex; + InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException + ("Unable to find available public IP addresses", DataCenter.class, zone.getId()); + ex.addProxyObject("data_center", zone.getId(), "zoneId"); + throw ex; } UserContext.current().setEventDetails("Ip Id: " + ip.getId()); Ip ipAddress = ip.getAddress(); @@ -1104,14 +1105,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag protected IPAddressVO getExistingSourceNat(long ownerId, Long networkId, Long vpcId) { - + List addrs = null; if (vpcId != null) { addrs = listPublicIpsAssignedToVpc(ownerId, true, vpcId); } else if (networkId != null) { addrs = listPublicIpsAssignedToGuestNtwk(ownerId, networkId, true); } - + IPAddressVO sourceNatIp = null; if (addrs.isEmpty()) { return null; @@ -1125,16 +1126,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } assert (sourceNatIp != null) : "How do we get a bunch of ip addresses but none of them are source nat? " + - "account=" + ownerId + "; networkId=" + networkId + "; vpcId=" + vpcId; + "account=" + ownerId + "; networkId=" + networkId + "; vpcId=" + vpcId; } - + return sourceNatIp; } @DB @Override public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId) throws ResourceAllocationException, ResourceUnavailableException, - InsufficientAddressCapacityException, ConcurrentOperationException { + InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = UserContext.current().getCaller(); Account owner = null; @@ -1151,7 +1152,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("IP " + ipToAssoc + " is already assocaited with network id" + networkId); return ipToAssoc; } - + Network network = _networksDao.findById(networkId); if (network != null) { _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network); @@ -1159,30 +1160,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Unable to find ip address by id: " + ipId); return null; } - + DataCenter zone = _configMgr.getZone(network.getDataCenterId()); // allow associating IP addresses to guest network only if (network.getTrafficType() != TrafficType.Guest) { throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + - TrafficType.Guest); + TrafficType.Guest, null); } // Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network, // and it belongs to the system if (zone.getNetworkType() != NetworkType.Basic && network.getAccountId() != owner.getId()) { - throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); + throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP", null); } - + // In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled if (zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " - + Service.SourceNat.getName() + " enabled"); + + Service.SourceNat.getName() + " enabled", null); } - + NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); boolean sharedSourceNat = offering.getSharedSourceNat(); boolean isSourceNat = false; @@ -1193,7 +1194,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + s_logger.debug("Associating ip " + ipToAssoc + " to network " + network); IPAddressVO ip = _ipAddressDao.findById(ipId); @@ -1201,7 +1202,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ip.setAssociatedWithNetworkId(networkId); ip.setSourceNat(isSourceNat); _ipAddressDao.update(ipId, ip); - + boolean success = false; try { success = applyIpAssociations(network, false); @@ -1233,7 +1234,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - + @DB protected IpAddress associateIPToVpc(long ipId, long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException { @@ -1248,22 +1249,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Unable to find ip address by id: " + ipId); return null; } - + Vpc vpc = _vpcMgr.getVpc(vpcId); if (vpc == null) { - throw new InvalidParameterValueException("Invalid VPC id " + vpcId); + throw new InvalidParameterValueException("Invalid VPC id provided", null); } - + // check permissions _accountMgr.checkAccess(caller, null, true, owner, vpc); - + boolean isSourceNat = false; if (getExistingSourceNat(owner.getId(), null, vpcId) == null) { isSourceNat = true; } - + s_logger.debug("Associating ip " + ipToAssoc + " to vpc " + vpc); - + Transaction txn = Transaction.currentTxn(); txn.start(); IPAddressVO ip = _ipAddressDao.findById(ipId); @@ -1271,16 +1272,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ip.setVpcId(vpcId); ip.setSourceNat(isSourceNat); _ipAddressDao.update(ipId, ip); - + //mark ip as allocated markPublicIpAsAllocated(ip); txn.commit(); - + s_logger.debug("Successfully assigned ip " + ipToAssoc + " to vpc " + vpc); return _ipAddressDao.findById(ipId); } - + @Override @DB @@ -1397,8 +1398,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.StaticNat, defaultProviders); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, defaultProviders); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, defaultProviders); - - + + Map> defaultVPCOffProviders = new HashMap>(); defaultProviders.clear(); @@ -1455,7 +1456,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } - + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks) == null) { offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, "Offering for Isolated VPC networks with Source Nat service enabled", TrafficType.Guest, @@ -1473,7 +1474,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } - + Map> netscalerServiceProviders = new HashMap>(); Set vrProvider = new HashSet(); vrProvider.add(Provider.VirtualRouter); @@ -1487,7 +1488,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag netscalerServiceProviders.put(Service.SecurityGroup, sgProvider); netscalerServiceProviders.put(Service.StaticNat, nsProvider); netscalerServiceProviders.put(Service.Lb, nsProvider); - + Map> serviceCapabilityMap = new HashMap>(); Map elb = new HashMap(); elb.put(Capability.ElasticLb, "true"); @@ -1495,7 +1496,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag eip.put(Capability.ElasticIp, "true"); serviceCapabilityMap.put(Service.Lb, elb); serviceCapabilityMap.put(Service.StaticNat, eip); - + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedEIPandELBNetworkOffering) == null) { offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, null, true, Availability.Optional, null, netscalerServiceProviders, true, Network.GuestType.Shared, false, null, true, serviceCapabilityMap, true); @@ -1579,7 +1580,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (implementedProvider != null) { if (s_providerToNetworkElementMap.containsKey(implementedProvider.getName())) { s_logger.error("Cannot start NetworkManager: Provider <-> NetworkElement must be a one-to-one map, " + - "multiple NetworkElements found for Provider: " + implementedProvider.getName()); + "multiple NetworkElements found for Provider: " + implementedProvider.getName()); return false; } s_providerToNetworkElementMap.put(implementedProvider.getName(), element.getName()); @@ -1614,7 +1615,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List listPublicIpsAssignedToGuestNtwk(long accountId, long associatedNetworkId, Boolean sourceNat) { SearchCriteria sc = IpAddressSearch.create(); sc.setParameters("accountId", accountId); - sc.setParameters("associatedWithNetworkId", associatedNetworkId); + sc.setParameters("associatedWithNetworkId", associatedNetworkId); if (sourceNat != null) { sc.addAnd("sourceNat", SearchCriteria.Op.EQ, sourceNat); @@ -1623,7 +1624,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _ipAddressDao.search(sc, null); } - + @Override public List listPublicIpsAssignedToAccount(long accountId, long dcId, Boolean sourceNat) { SearchCriteria sc = IpAddressSearch.create(); @@ -1637,7 +1638,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _ipAddressDao.search(sc, null); } - + protected List listPublicIpsAssignedToVpc(long accountId, Boolean sourceNat, long vpcId) { SearchCriteria sc = IpAddressSearch.create(); sc.setParameters("accountId", accountId); @@ -1654,7 +1655,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) - throws ConcurrentOperationException { + throws ConcurrentOperationException { return setupNetwork(owner, offering, null, plan, name, displayText, false, null, null, null, null); } @@ -1663,7 +1664,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean errorIfAlreadySetup, Long domainId, ACLType aclType, Boolean subdomainAccess, Long vpcId) throws ConcurrentOperationException { - + Account locked = _accountDao.acquireInLockTable(owner.getId()); if (locked == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + owner); @@ -1680,10 +1681,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (errorIfAlreadySetup) { - InvalidParameterValueException ex = new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)"); - ex.addProxyObject(offering, offering.getId(), "offeringId"); - ex.addProxyObject(configs.get(0), configs.get(0).getId(), "networkConfigId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(offering, offering.getId(), "offeringId")); + idList.add(new IdentityProxy(configs.get(0), configs.get(0).getId(), "networkConfigId")); + throw new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)", idList); } else { return configs; } @@ -1697,10 +1698,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (errorIfAlreadySetup) { - InvalidParameterValueException ex = new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)"); - ex.addProxyObject(offering, offering.getId(), "offeringId"); - ex.addProxyObject(configs.get(0), configs.get(0).getId(), "networkConfigId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(offering, offering.getId(), "offeringId")); + idList.add(new IdentityProxy(configs.get(0), configs.get(0).getId(), "networkConfigId")); + throw new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)", idList); } else { return configs; } @@ -1748,9 +1749,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (networks.size() < 1) { - // see networkOfferingVO.java - CloudRuntimeException ex = new CloudRuntimeException("Unable to convert network offering with specified id to network profile"); - ex.addProxyObject(offering, offering.getId(), "offeringId"); + // see networkOfferingVO.java + CloudRuntimeException ex = new CloudRuntimeException("Unable to convert network offering with specified id to network profile"); + ex.addProxyObject(offering, offering.getId(), "offeringId"); throw ex; } @@ -1811,7 +1812,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } deviceId = vmNicPair.second(); - + int devId = vmNic.getDeviceId(); if (devId > deviceIds.length) { throw new IllegalArgumentException("Device id for nic is too large: " + vmNic); @@ -1825,14 +1826,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vmNic.isDefaultNic()) { if (defaultNic != null) { throw new IllegalArgumentException("You cannot specify two nics as default nics: nic 1 = " + - defaultNic + "; nic 2 = " + vmNic); + defaultNic + "; nic 2 = " + vmNic); } defaultNic = vmNic; } - + nics.add(vmNic); vm.addNic(vmNic); - + } if (nics.size() != networks.size()) { @@ -1847,13 +1848,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.commit(); } - + @DB @Override public Pair allocateNic(NicProfile requested, Network network, Boolean isDefaultNic, int deviceId, VirtualMachineProfile vm) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException{ - + NetworkVO ntwkVO = _networksDao.findById(network.getId()); s_logger.debug("Allocating nic for vm " + vm.getVirtualMachine() + " in network " + network); NetworkGuru guru = _networkGurus.get(ntwkVO.getGuruName()); @@ -1881,12 +1882,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag deviceId = applyProfileToNic(vo, profile, deviceId); vo = _nicDao.persist(vo); - + Integer networkRate = getNetworkRate(network.getId(), vm.getId()); NicProfile vmNic = new NicProfile(vo, network, vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), - network)); - + network)); + return new Pair(vmNic, Integer.valueOf(deviceId)); } @@ -1988,10 +1989,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkVO network = _networksDao.acquireInLockTable(networkId, _networkLockTimeout); if (network == null) { - // see NetworkVO.java - ConcurrentOperationException ex = new ConcurrentOperationException("Unable to acquire network configuration"); - ex.addProxyObject("networks", networkId, "networkId"); - throw ex; + // see NetworkVO.java + ConcurrentOperationException ex = new ConcurrentOperationException("Unable to acquire network configuration"); + ex.addProxyObject("networks", networkId, "networkId"); + throw ex; } try { @@ -2047,7 +2048,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag private void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, NetworkVO network, NetworkOfferingVO offering) - throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { + throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a // Shared source NAT rule, // associate a source NAT IP (if one isn't already associated with the network) @@ -2057,7 +2058,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (network.getGuestType() == Network.GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), Service.SourceNat) && !sharedSourceNat) { - + List ips = null; Vpc vpc = null; if (network.getVpcId() != null) { @@ -2066,7 +2067,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { ips = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); } - + if (ips.isEmpty()) { String target = vpc != null ? vpc.toString() : network.toString(); @@ -2085,18 +2086,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NetworkElement element : _networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { - // The physicalNetworkId will not get translated into a uuid by the reponse serializer, - // because the serializer would look up the NetworkVO class's table and retrieve the - // network id instead of the physical network id. - // So just throw this exception as is. We may need to TBD by changing the serializer. - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + "either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + // The physicalNetworkId will not get translated into a uuid by the reponse serializer, + // because the serializer would look up the NetworkVO class's table and retrieve the + // network id instead of the physical network id. + // So just throw this exception as is. We may need to TBD by changing the serializer. + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + "either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to implemenet " + network); } if (!element.implement(network, offering, dest, context)) { - CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); - ex.addProxyObject(network, network.getId(), "networkId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); + ex.addProxyObject(network, network.getId(), "networkId"); throw ex; } } @@ -2148,13 +2149,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (nic.getVmType() == VirtualMachine.Type.User || (nic.getVmType() == VirtualMachine.Type.DomainRouter && getNetwork(networkId).getTrafficType() == TrafficType.Guest)) { _networksDao.setCheckForGc(networkId); } - + txn.commit(); } @Override public void prepare(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException { + ConcurrentOperationException, ResourceUnavailableException { List nics = _nicDao.listByVmId(vmProfile.getId()); // we have to implement default nics first - to ensure that default network elements start up first in multiple @@ -2172,7 +2173,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NicVO nic : nics) { Pair implemented = implementNetwork(nic.getNetworkId(), dest, context); - + NetworkVO network = implemented.second(); NicProfile profile = prepareNic(vmProfile, dest, context, nic.getId(), network); vmProfile.addNic(profile); @@ -2182,13 +2183,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public NicProfile prepareNic(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context, long nicId, NetworkVO network) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, - ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - - Integer networkRate = getNetworkRate(network.getId(), vmProfile.getId()); + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, + ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { + + Integer networkRate = getNetworkRate(network.getId(), vmProfile.getId()); NetworkGuru guru = _networkGurus.get(network.getGuruName()); NicVO nic = _nicDao.findById(nicId); - + NicProfile profile = null; if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { nic.setState(Nic.State.Reserving); @@ -2202,7 +2203,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag URI isolationUri = nic.getIsolationUri(); profile = new NicProfile(nic, network, broadcastUri, isolationUri, - networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); + networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); guru.reserve(profile, network, vmProfile, dest, context); nic.setIp4Address(profile.getIp4Address()); nic.setAddressFormat(profile.getFormat()); @@ -2222,7 +2223,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag updateNic(nic, network.getId(), 1); } else { profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), - networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); + networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); guru.updateNicProfile(profile, network); nic.setState(Nic.State.Reserved); updateNic(nic, network.getId(), 1); @@ -2257,26 +2258,26 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public void release(VirtualMachineProfile vmProfile, boolean forced) throws - ConcurrentOperationException, ResourceUnavailableException { + ConcurrentOperationException, ResourceUnavailableException { List nics = _nicDao.listByVmId(vmProfile.getId()); for (NicVO nic : nics) { NetworkVO network = _networksDao.findById(nic.getNetworkId()); releaseNic(vmProfile, nic, network); } } - + @Override public NicProfile releaseNic(VirtualMachineProfile vmProfile, NetworkVO network) throws ConcurrentOperationException, ResourceUnavailableException { NicVO nic = _nicDao.findByInstanceIdAndNetworkId(network.getId(), vmProfile.getId()); releaseNic(vmProfile, nic, network); - + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network)); return profile; } - - + + @Override public NicProfile releaseNic(VirtualMachineProfile vmProfile, NetworkVO network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException { @@ -2287,7 +2288,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag nic = _nicDao.findByInstanceIdAndNetworkId(network.getId(), vmProfile.getId()); } releaseNic(vmProfile, nic, network); - + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network)); return profile; @@ -2296,39 +2297,39 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag protected void releaseNic(VirtualMachineProfile vmProfile, NicVO nic, NetworkVO network) throws ConcurrentOperationException, ResourceUnavailableException { - if (nic.getState() == Nic.State.Reserved || nic.getState() == Nic.State.Reserving) { - Nic.State originalState = nic.getState(); - if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { - NetworkGuru guru = _networkGurus.get(network.getGuruName()); - nic.setState(Nic.State.Releasing); - _nicDao.update(nic.getId(), nic); + if (nic.getState() == Nic.State.Reserved || nic.getState() == Nic.State.Reserving) { + Nic.State originalState = nic.getState(); + if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { + NetworkGuru guru = _networkGurus.get(network.getGuruName()); + nic.setState(Nic.State.Releasing); + _nicDao.update(nic.getId(), nic); NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); - if (guru.release(profile, vmProfile, nic.getReservationId())) { - applyProfileToNicForRelease(nic, profile); - nic.setState(Nic.State.Allocated); - if (originalState == Nic.State.Reserved) { - updateNic(nic, network.getId(), -1); - } else { - _nicDao.update(nic.getId(), nic); - } - } - // Perform release on network elements - for (NetworkElement element : _networkElements) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Asking " + element.getName() + " to release " + nic); - } - //NOTE: Context appear to never be used in release method - //implementations. Consider removing it from interface Element - element.release(network, profile, vmProfile, null); - } - - } else { + if (guru.release(profile, vmProfile, nic.getReservationId())) { + applyProfileToNicForRelease(nic, profile); nic.setState(Nic.State.Allocated); - updateNic(nic, network.getId(), -1); + if (originalState == Nic.State.Reserved) { + updateNic(nic, network.getId(), -1); + } else { + _nicDao.update(nic.getId(), nic); + } } + // Perform release on network elements + for (NetworkElement element : _networkElements) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Asking " + element.getName() + " to release " + nic); + } + //NOTE: Context appear to never be used in release method + //implementations. Consider removing it from interface Element + element.release(network, profile, vmProfile, null); + } + + } else { + nic.setState(Nic.State.Allocated); + updateNic(nic, network.getId(), -1); } } + } @Override public List getNics(long vmId) { @@ -2360,12 +2361,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NicVO nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId()); NetworkVO network = _networksDao.findById(networkId); Integer networkRate = getNetworkRate(network.getId(), vm.getId()); - + NetworkGuru guru = _networkGurus.get(network.getGuruName()); NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network)); guru.updateNicProfile(profile, network); - + return profile; } @@ -2379,7 +2380,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Verify input parameters IPAddressVO ipVO = _ipAddressDao.findById(ipAddressId); if (ipVO == null) { - throw new InvalidParameterValueException("Unable to find ip address by id"); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } if (ipVO.getAllocatedTime() == null) { @@ -2403,21 +2404,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check for account wide pool. It will have an entry for account_vlan_map. if (_accountVlanMapDao.findAccountVlanMap(ipVO.getAllocatedToAccountId(), ipVO.getVlanId()) != null) { - //see IPaddressVO.java - InvalidParameterValueException ex = new InvalidParameterValueException("Sepcified IP address uuid belongs to Account wide IP pool and cannot be disassociated"); - ex.addProxyObject(ipVO, ipVO.getId(), "systemIpAddrId"); - throw ex; + //see IPaddressVO.java + List idList = new ArrayList(); + idList.add(new IdentityProxy(ipVO, ipVO.getId(), "systemIpAddrId")); + throw new InvalidParameterValueException("Sepcified IP address uuid belongs to Account wide IP pool and cannot be disassociated", idList); } // don't allow releasing system ip address if (ipVO.getSystem()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can't release system IP address with specified id"); - ex.addProxyObject(ipVO, ipVO.getId(), "systemIpAddrId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(ipVO, ipVO.getId(), "systemIpAddrId")); + throw new InvalidParameterValueException("Can't release system IP address with specified id", idList); } boolean success = disassociatePublicIpAddress(ipAddressId, userId, caller); - + Long networkId = ipVO.getAssociatedWithNetworkId(); if (success && networkId != null) { Network guestNetwork = getNetwork(networkId); @@ -2454,7 +2455,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public String getNextAvailableMacAddressInNetwork(long networkId) throws InsufficientAddressCapacityException { String mac = _networksDao.getNextAvailableMacAddress(networkId); if (mac == null) { - throw new InsufficientAddressCapacityException("Unable to create another mac address", Network.class, networkId); + throw new InsufficientAddressCapacityException("Unable to create another mac address", Network.class, networkId); } return mac; } @@ -2502,7 +2503,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag removeNic(vm, nic); } } - + @Override public void removeNic(VirtualMachineProfile vm, Network network) { NicVO nic = _nicDao.findByInstanceIdAndNetworkId(network.getId(), vm.getVirtualMachine().getId()); @@ -2510,14 +2511,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } protected void removeNic(VirtualMachineProfile vm, NicVO nic) { - nic.setState(Nic.State.Deallocating); - _nicDao.update(nic.getId(), nic); - NetworkVO network = _networksDao.findById(nic.getNetworkId()); + nic.setState(Nic.State.Deallocating); + _nicDao.update(nic.getId(), nic); + NetworkVO network = _networksDao.findById(nic.getNetworkId()); NicProfile profile = new NicProfile(nic, network, null, null, null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network)); - NetworkGuru guru = _networkGurus.get(network.getGuruName()); - guru.deallocate(network, profile, vm); - _nicDao.remove(nic.getId()); + NetworkGuru guru = _networkGurus.get(network.getGuruName()); + guru.deallocate(network, profile, vm); + _nicDao.remove(nic.getId()); s_logger.debug("Removed nic id=" + nic.getId()); } @@ -2547,7 +2548,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (cidr == null) { return; } - List networks = _networksDao.listByZone((long) zoneId); + List networks = _networksDao.listByZone(zoneId); Map networkToCidr = new HashMap(); for (NetworkVO network : networks) { if (network.getGuestType() != GuestType.Isolated) { @@ -2564,9 +2565,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (long networkId : networkToCidr.keySet()) { String ntwkCidr = networkToCidr.get(networkId); if (NetUtils.isNetworksOverlap(ntwkCidr, cidr)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Warning: The specified existing network has conflict CIDR subnets with new network!"); - ex.addProxyObject("networks", networkId, "networkId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy("networks", networkId, "networkId")); + throw new InvalidParameterValueException("Warning: The specified existing network has conflict CIDR subnets with new network!", idList); } } } @@ -2595,21 +2596,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Validate network offering NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId); - if (ntwkOff == null || ntwkOff.isSystemOnly()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id"); - if (ntwkOff != null) { - ex.addProxyObject(ntwkOff, networkOfferingId, "networkOfferingId"); - throw ex; - } - throw ex; + if (ntwkOff == null) { + throw new InvalidParameterValueException("Unable to find network offering by specified id", null); } + if (ntwkOff.isSystemOnly()) { + List idList = new ArrayList(); + idList.add(new IdentityProxy(ntwkOff, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("Network offering with specified id is System-only", idList); + } + // validate physical network and zone // Check if physical network exists PhysicalNetwork pNtwk = null; if (physicalNetworkId != null) { pNtwk = _physicalNetworkDao.findById(physicalNetworkId); if (pNtwk == null) { - throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id"); + throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id", null); } } @@ -2619,13 +2621,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag DataCenter zone = _dcDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Specified zone id was not found"); + throw new InvalidParameterValueException("Specified zone id was not found", null); } - + if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { - // See DataCenterVO.java - PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled"); - ex.addProxyObject(zone, zoneId, "zoneId"); + // See DataCenterVO.java + PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled"); + ex.addProxyObject(zone, zoneId, "zoneId"); throw ex; } @@ -2633,7 +2635,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vpcId != null) { Vpc vpc = _vpcMgr.getActiveVpc(vpcId); if (vpc == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC "); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC ", null); ex.addProxyObject("vpc", vpcId, "VPC"); throw ex; } @@ -2648,17 +2650,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) { aclType = ACLType.Domain; } else { - throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types"); + throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types", null); } // In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account if (ntwkOff.getGuestType() == GuestType.Isolated) { if (aclType != ACLType.Account) { - throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + Network.GuestType.Isolated); + throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + Network.GuestType.Isolated, null); } } else if (ntwkOff.getGuestType() == GuestType.Shared) { if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) { throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + - ACLType.Account + " for network of type " + Network.GuestType.Shared); + ACLType.Account + " for network of type " + Network.GuestType.Shared, null); } } } else { @@ -2671,7 +2673,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Only Admin can create Shared networks if (ntwkOff.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getType())) { - throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared); + throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared, null); } // Check if the network is domain specific @@ -2683,25 +2685,25 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // only shared networks can be Domain specific if (ntwkOff.getGuestType() != GuestType.Shared) { - throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain); + throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain, null); } if (domainId != null) { if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) { throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " - + TrafficType.Guest + " and guest type " + Network.GuestType.Shared); + + TrafficType.Guest + " and guest type " + Network.GuestType.Shared, null); } DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by specified id"); + throw new InvalidParameterValueException("Unable to find domain by specified id", null); } _accountMgr.checkAccess(caller, domain); } isDomainSpecific = true; } else if (subdomainAccess != null) { - throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain"); + throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain", null); } Account owner = null; if ((cmd.getAccountName() != null && domainId != null) || cmd.getProjectId() != null) { @@ -2716,28 +2718,28 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // if end ip is not specified, default it to startIp if (startIP != null) { if (!NetUtils.isValidIp(startIP)) { - throw new InvalidParameterValueException("Invalid format for the startIp parameter"); + throw new InvalidParameterValueException("Invalid format for the startIp parameter", null); } if (endIP == null) { endIP = startIP; } else if (!NetUtils.isValidIp(endIP)) { - throw new InvalidParameterValueException("Invalid format for the endIp parameter"); + throw new InvalidParameterValueException("Invalid format for the endIp parameter", null); } } if (startIP != null && endIP != null) { if (!(gateway != null && netmask != null)) { - throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in"); + throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in", null); } } String cidr = null; if (gateway != null && netmask != null) { if (!NetUtils.isValidIp(gateway)) { - throw new InvalidParameterValueException("Invalid gateway"); + throw new InvalidParameterValueException("Invalid gateway", null); } if (!NetUtils.isValidNetmask(netmask)) { - throw new InvalidParameterValueException("Invalid netmask"); + throw new InvalidParameterValueException("Invalid netmask", null); } cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); @@ -2746,15 +2748,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Regular user can create Guest Isolated Source Nat enabled network only if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated - && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { + && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("Regular user can create a network only from the network" + - " offering having traffic type " + TrafficType.Guest + " and network type " - + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled"); + " offering having traffic type " + TrafficType.Guest + " and network type " + + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled", null); } // Don't allow to specify vlan if the caller is a regular user if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (ntwkOff.getSpecifyVlan() || vlanId != null)) { - throw new InvalidParameterValueException("Regular user is not allowed to specify vlanId"); + throw new InvalidParameterValueException("Regular user is not allowed to specify vlanId", null); } // For non-root admins check cidr limit - if it's allowed by global config value @@ -2764,12 +2766,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag int cidrSize = Integer.valueOf(cidrPair[1]); if (cidrSize < _cidrLimit) { - throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit); + throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit, null); } } if (cidr != null && networkOfferingIsConfiguredForExternalNetworking(networkOfferingId)) { - throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!"); + throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!", null); } // Vlan is created in 2 cases - works in Advance zone only: @@ -2777,14 +2779,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // 2) GuestType is Isolated, but SourceNat service is disabled boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced && ((ntwkOff.getGuestType() == Network.GuestType.Shared) - || (ntwkOff.getGuestType() == GuestType.Isolated && - !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)))); + || (ntwkOff.getGuestType() == GuestType.Isolated && + !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)))); // Can add vlan range only to the network which allows it if (createVlan && !ntwkOff.getSpecifyIpRanges()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges"); - ex.addProxyObject(ntwkOff, ntwkOff.getId(), "networkOfferingId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(ntwkOff, ntwkOff.getId(), "networkOfferingId")); + throw new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges", idList); } Transaction txn = Transaction.currentTxn(); @@ -2809,13 +2811,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Network network = null; if (vpcId != null) { if (!_configMgr.isOfferingForVpc(ntwkOff)){ - throw new InvalidParameterValueException("Network offering can't be used for VPC networks"); + throw new InvalidParameterValueException("Network offering can't be used for VPC networks", null); } network = createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId); } else { if (_configMgr.isOfferingForVpc(ntwkOff)){ - throw new InvalidParameterValueException("Network offering can be used for VPC networks only"); + throw new InvalidParameterValueException("Network offering can be used for VPC networks only", null); } network = createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId); @@ -2837,18 +2839,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String cidr, String vlanId, String networkDomain, Account owner, Long domainId, PhysicalNetwork pNtwk, long zoneId, ACLType aclType, Boolean subdomainAccess, long vpcId) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException { - + Vpc vpc = _vpcMgr.getActiveVpc(vpcId); if (networkDomain == null) { networkDomain = vpc.getNetworkDomain(); } //1) Validate if network can be created for VPC _vpcMgr.validateGuestNtkwForVpc(_configMgr.getNetworkOffering(ntwkOffId), cidr, networkDomain, owner, vpc, null); - + //2) Create network Network guestNetwork = createGuestNetwork(ntwkOffId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, domainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId); - + return guestNetwork; } @@ -2865,7 +2867,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Only guest networks can be created using this method"); return null; } - + boolean updateResourceCount = (!ntwkOff.getSpecifyVlan() && aclType == ACLType.Account); //check resource limits if (updateResourceCount) { @@ -2874,19 +2876,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Validate network offering if (ntwkOff.getState() != NetworkOffering.State.Enabled) { - // see NetworkOfferingVO - InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its stat is not " + NetworkOffering.State.Enabled); - ex.addProxyObject(ntwkOff, ntwkOff.getId(), "networkOfferingId"); - throw ex; + // see NetworkOfferingVO + List idList = new ArrayList(); + idList.add(new IdentityProxy(ntwkOff, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("Can't use specified network offering id as its stat is not " + NetworkOffering.State.Enabled, idList); } // Validate physical network if (pNtwk.getState() != PhysicalNetwork.State.Enabled) { - // see PhysicalNetworkVO.java - InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + - " in incorrect state:" + pNtwk.getState()); - ex.addProxyObject("physical_network", pNtwk.getId(), "physicalNetworkId"); - throw ex; + // see PhysicalNetworkVO.java + List idList = new ArrayList(); + idList.add(new IdentityProxy("physical_network", pNtwk.getId(), "physicalNetworkId")); + throw new InvalidParameterValueException("Specified physical network id is" + + " in incorrect state:" + pNtwk.getState(), idList); } // Validate zone @@ -2894,33 +2896,33 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (zone.getNetworkType() == NetworkType.Basic) { // In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true if (aclType == null || aclType != ACLType.Domain) { - throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone"); + throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone", null); } - + // Only one guest network is supported in Basic zone List guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest); if (!guestNetworks.isEmpty()) { throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " - + NetworkType.Basic); + + NetworkType.Basic, null); } // if zone is basic, only Shared network offerings w/o source nat service are allowed if (!(ntwkOff.getGuestType() == GuestType.Shared && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + - "guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() - + " service are allowed"); + "guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + + " service are allowed", null); } if (domainId == null || domainId != Domain.ROOT_DOMAIN) { - throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain"); + throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain", null); } if (subdomainAccess == null) { subdomainAccess = true; } else if (!subdomainAccess) { throw new InvalidParameterValueException("Subdomain access should be set to true for the" + - " guest network in the Basic zone"); + " guest network in the Basic zone", null); } if (vlanId == null) { @@ -2928,7 +2930,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) { throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + - "the zone of type " + NetworkType.Basic); + "the zone of type " + NetworkType.Basic, null); } } @@ -2940,7 +2942,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)); if (!allowCreation) { throw new InvalidParameterValueException("Only Account specific Isolated network with sourceNat " + - "service disabled are allowed in security group enabled zone"); + "service disabled are allowed in security group enabled zone", null); } } } @@ -2949,9 +2951,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean vlanSpecified = (vlanId != null); if (vlanSpecified != ntwkOff.getSpecifyVlan()) { if (vlanSpecified) { - throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false"); + throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false", null); } else { - throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true"); + throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true", null); } } @@ -2960,17 +2962,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // For Isolated networks, don't allow to create network with vlan that already exists in the zone if (ntwkOff.getGuestType() == GuestType.Isolated) { if (_networksDao.countByZoneAndUri(zoneId, uri) > 0) { - throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists in zone " + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("vlan", Long.valueOf(vlanId), "vlanId")); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Network with vlan of specified id already exists in zone with specified id", idList); } } else { //don't allow to create Shared network with Vlan that already exists in the zone for Isolated networks + List idList = new ArrayList(); + idList.add(new IdentityProxy("vlan", Long.valueOf(vlanId), "vlanId")); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0) { - throw new InvalidParameterValueException("Isolated network with vlan " + vlanId + " already exists " + - "in zone " + zoneId); + throw new InvalidParameterValueException("Isolated network with vlan of specified id already exists " + + "in zone with specified id", idList); } } } - + // If networkDomain is not specified, take it from the global configuration if (areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) { Map dnsCapabilities = getNetworkOfferingServiceCapabilities @@ -2978,8 +2986,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { if (networkDomain != null) { - throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" - + networkOfferingId + " in zone id=" + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(ntwkOff, networkOfferingId, "networkOfferingId")); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Domain name change is not supported by network offering of specified id in zone with specified id", idList); } } else { if (networkDomain == null) { @@ -3000,8 +3010,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag 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 \"-\""); + "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 \"-\"", null); } } } @@ -3015,19 +3025,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))); if (cidr == null && cidrRequired) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + - " type " + Network.GuestType.Shared + " and network of type " + GuestType.Isolated + " with service " - + Service.SourceNat.getName() + " disabled"); + " type " + Network.GuestType.Shared + " and network of type " + GuestType.Isolated + " with service " + + Service.SourceNat.getName() + " disabled", null); } // No cidr can be specified in Basic zone if (zone.getNetworkType() == NetworkType.Basic && cidr != null) { - throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic); + throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic, null); } // Check if cidr is RFC1918 compliant if the network is Guest Isolated if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) { if (!NetUtils.validateGuestCidr(cidr)) { - throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC1918 compliant"); + throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC1918 compliant", null); } } @@ -3077,7 +3087,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network = networks.get(0); } } - + if (updateResourceCount) { _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network); } @@ -3120,22 +3130,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Account/domainId parameters and isSystem are mutually exclusive if (isSystem != null && isSystem && (accountName != null || domainId != null)) { - throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified"); + throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified", null); } if (domainId != null) { DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - // see DomainVO.java - throw new InvalidParameterValueException("Specified domain id doesn't exist in the system"); + // see DomainVO.java + throw new InvalidParameterValueException("Specified domain id doesn't exist in the system", null); } _accountMgr.checkAccess(caller, domain); if (accountName != null) { Account owner = _accountMgr.getActiveAccountByName(accountName, domainId); if (owner == null) { - // see DomainVO.java - throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain"); + // see DomainVO.java + throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain", null); } _accountMgr.checkAccess(caller, null, true, owner); @@ -3161,13 +3171,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag permittedAccounts.clear(); Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by specified id"); + throw new InvalidParameterValueException("Unable to find project by specified id", null); } if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { - // getProject() returns type ProjectVO. - InvalidParameterValueException ex = new InvalidParameterValueException("Account " + caller + " cannot access specified project id"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + // getProject() returns type ProjectVO. + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Account " + caller + " cannot access specified project id", idList); } permittedAccounts.add(project.getProjectAccountId()); } @@ -3194,7 +3204,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag zoneSearch.and("networkType", zoneSearch.entity().getNetworkType(), SearchCriteria.Op.EQ); sb.join("zoneSearch", zoneSearch, sb.entity().getDataCenterId(), zoneSearch.entity().getId(), JoinBuilder.JoinType.INNER); sb.and("removed", sb.entity().getRemoved(), Op.NULL); - + if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); for (int count=0; count < tags.size(); count++) { @@ -3225,9 +3235,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Get domain level networks if (domainId != null) { networksToReturn - .addAll(listDomainLevelNetworks( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, - physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, + .addAll(listDomainLevelNetworks( + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, + physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, domainId)); } @@ -3235,12 +3245,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networksToReturn.addAll(listAccountSpecificNetworks( buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, - permittedAccounts)); + permittedAccounts)); } else if (domainId == null || listAll) { networksToReturn.addAll(listAccountSpecificNetworksByDomainPath( buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, path, - isRecursive)); + isRecursive)); } } else { networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, @@ -3255,7 +3265,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (String supportedServiceStr : supportedServicesStr) { Service service = Service.getService(supportedServiceStr); if (service == null) { - throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr); + throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr, null); } else { suppportedServices[i] = service; } @@ -3270,7 +3280,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networksToReturn=supportedNetworks; } - + if (canUseForDeploy != null) { List networksForDeploy = new ArrayList(); for (NetworkVO network : networksToReturn) { @@ -3278,10 +3288,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networksForDeploy.add(network); } } - + networksToReturn=networksForDeploy; } - + return networksToReturn; } @@ -3296,7 +3306,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { hasFreeIps = (getAvailableIps(network, null)).size() > 0; } - + return hasFreeIps; } @@ -3354,7 +3364,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vpcId != null) { sc.addAnd("vpcId", SearchCriteria.Op.EQ, vpcId); } - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Network.toString()); @@ -3428,18 +3438,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Verify network id NetworkVO network = _networksDao.findById(networkId); if (network == null) { - // see NetworkVO.java - - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find network with specified id"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; + // see NetworkVO.java + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, networkId, "networkId")); + throw new InvalidParameterValueException("unable to find network with specified id", idList); } // don't allow to delete system network if (isNetworkSystem(network)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id is system and can't be removed"); - ex.addProxyObject(network, network.getId(), "networkId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, network.getId(), "networkId")); + throw new InvalidParameterValueException("Network with specified id is system and can't be removed", idList); } Account owner = _accountMgr.getAccount(network.getAccountId()); @@ -3457,7 +3466,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @DB public boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements) { boolean result = false; - + NetworkVO network = _networksDao.lockRow(networkId, true); if (network == null) { s_logger.debug("Unable to find network with id: " + networkId); @@ -3575,7 +3584,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } } - + //In Basic zone, make sure that there are no non-removed console proxies and SSVMs using the network DataCenter zone = _configMgr.getZone(network.getDataCenterId()); if (zone.getNetworkType() == NetworkType.Basic) { @@ -3659,7 +3668,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } protected boolean deleteVlansInNetwork(long networkId, long userId, Account callerAccount) { - + //cleanup Public vlans List publicVlans = _vlanDao.listVlansByNetworkId(networkId); boolean result = true; @@ -3669,7 +3678,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag result = false; } } - + //cleanup private vlans int privateIpAllocCount = _privateIpDao.countAllocatedByNetworkId(networkId); if (privateIpAllocCount > 0) { @@ -3735,7 +3744,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Provider provider = Network.Provider.getProvider(ne.getName()); if (provider == null) { if (ne.getName().equalsIgnoreCase("Ovs") || ne.getName().equalsIgnoreCase("BareMetal") - || ne.getName().equalsIgnoreCase("CiscoNexus1000vVSM")) { + || ne.getName().equalsIgnoreCase("CiscoNexus1000vVSM")) { continue; } throw new CloudRuntimeException("Unable to identify the provider by name " + ne.getName()); @@ -3860,21 +3869,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check if network exists NetworkVO network = _networksDao.findById(networkId); - if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id doesn't exist"); - ex.addProxyObject("networks", networkId, "networkId"); - throw ex; + if (network == null) { + throw new InvalidParameterValueException("Couldn't find network by id", null); } // Don't allow to restart network if it's not in Implemented/Setup state if (!(network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) { - throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + Network.State.Setup); + throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + Network.State.Setup, null); } // don't allow clenaup=true for the network in Basic zone DataCenter zone = _configMgr.getZone(network.getDataCenterId()); if (zone.getNetworkType() == NetworkType.Basic && cleanup) { - throw new InvalidParameterValueException("Cleanup can't be true when restart network in Basic zone"); + throw new InvalidParameterValueException("Cleanup can't be true when restart network in Basic zone", null); } _accountMgr.checkAccess(callerAccount, null, true, network); @@ -3896,9 +3903,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check if network exists NetworkVO network = _networksDao.findById(networkId); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id doesn't exist"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find network by id", null); } // implement the network @@ -4011,13 +4016,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + //apply network ACLs if (!_networkACLMgr.applyNetworkACLs(networkId, caller)) { s_logger.warn("Failed to reapply network ACLs as a part of of network id=" + networkId + " restart"); success = false; } - + return success; } @@ -4052,8 +4057,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public Map getNetworkServiceCapabilities(long networkId, Service service) { if (!areServicesSupportedInNetwork(networkId, service)) { - // TBD: networkId to uuid. No VO object being passed. So we will need to call - // addProxyObject with hardcoded tablename. Or we should probably look up the correct dao proxy object. + // TBD: networkId to uuid. No VO object being passed. So we will need to call + // addProxyObject with hardcoded tablename. Or we should probably look up the correct dao proxy object. throw new UnsupportedServiceException("Service " + service.getName() + " is not supported in the network id=" + networkId); } @@ -4080,7 +4085,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public Map getNetworkOfferingServiceCapabilities(NetworkOffering offering, Service service) { if (!areServicesSupportedByNetworkOffering(offering.getId(), service)) { - // TBD: We should be sending networkOfferingId and not the offering object itself. + // TBD: We should be sending networkOfferingId and not the offering object itself. throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the network offering " + offering); } @@ -4089,8 +4094,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // get the Provider for this Service for this offering List providers = _ntwkOfferingSrvcDao.listProvidersForServiceForNetworkOffering(offering.getId(), service); if (providers.isEmpty()) { - // TBD: We should be sending networkOfferingId and not the offering object itself. - throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering); + // TBD: We should be sending networkOfferingId and not the offering object itself. + throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering, null); } // FIXME - in post 3.0 we are going to support multiple providers for the same service per network offering, so @@ -4105,7 +4110,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ; if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { - // TBD: We should be sending providerId and not the offering object itself. + // TBD: We should be sending providerId and not the offering object itself. throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider); } serviceCapabilities = elementCapabilities.get(service); @@ -4127,13 +4132,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (networkOfferingId == null) { - throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType); + throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType, null); } List networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId); if (networks == null || networks.isEmpty()) { - // TBD: send uuid instead of zoneId. Hardcode tablename in call to addProxyObject(). - throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId); + // TBD: send uuid instead of zoneId. Hardcode tablename in call to addProxyObject(). + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone with specified id", idList); } return networks.get(0); } @@ -4194,7 +4201,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public String getIpInNetwork(long vmId, long networkId) { Nic guestNic = getNicInNetwork(vmId, networkId); assert (guestNic != null && guestNic.getIp4Address() != null) : "Vm doesn't belong to network associated with " + - "ipAddress or ip4 address is null"; + "ipAddress or ip4 address is null"; return guestNic.getIp4Address(); } @@ -4202,7 +4209,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public String getIpInNetworkIncludingRemoved(long vmId, long networkId) { Nic guestNic = getNicInNetworkIncludingRemoved(vmId, networkId); assert (guestNic != null && guestNic.getIp4Address() != null) : "Vm doesn't belong to network associated with " + - "ipAddress or ip4 address is null"; + "ipAddress or ip4 address is null"; return guestNic.getIp4Address(); } @@ -4217,9 +4224,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ResourceUnavailableException, ResourceAllocationException { Account owner = _accountMgr.getActiveAccountById(accountId); boolean createNetwork = false; - + if (guestNetwork != null && guestNetwork.getTrafficType() != TrafficType.Guest) { - throw new InvalidParameterValueException("Network " + guestNetwork + " is not of a type " + TrafficType.Guest); + throw new InvalidParameterValueException("Network " + guestNetwork + " is not of a type " + TrafficType.Guest, null); } Transaction txn = Transaction.currentTxn(); @@ -4233,7 +4240,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag guestNetwork = networks.get(0); } else { throw new InvalidParameterValueException("Error, more than 1 Guest Isolated Networks with SourceNAT " + - "service enabled found for this account, cannot assosiate the IP range, please provide the network ID"); + "service enabled found for this account, cannot assosiate the IP range, please provide the network ID", null); } } @@ -4242,13 +4249,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { throw new CloudRuntimeException("Unable to find network offering with availability=" + - Availability.Required + " to automatically create the network as part of createVlanIpRange"); + Availability.Required + " to automatically create the network as part of createVlanIpRange"); } PhysicalNetwork physicalNetwork = translateZoneIdToPhysicalNetwork(zoneId); - + if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { s_logger.debug("Creating network for account " + owner + " from the network offering id=" + - requiredOfferings.get(0).getId() + " as a part of createVlanIpRange process"); + requiredOfferings.get(0).getId() + " as a part of createVlanIpRange process"); guestNetwork = createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network" , owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, zoneId, ACLType.Account, @@ -4256,7 +4263,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (guestNetwork == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); throw new CloudRuntimeException("Failed to create a Guest Isolated Networks with SourceNAT " + - "service enabled as a part of createVlanIpRange, for the account " + accountId + "in zone " + zoneId); + "service enabled as a part of createVlanIpRange, for the account " + accountId + "in zone " + zoneId); } } else { throw new CloudRuntimeException("Required network offering id=" + requiredOfferings.get(0).getId() @@ -4492,15 +4499,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List listAllNetworksInAllZonesByType(Network.GuestType type) { - List networks = new ArrayList(); - for (NetworkVO network: _networksDao.listAll()) { - if (!isNetworkSystem(network)) { - networks.add(network); - } - } - return networks; + List networks = new ArrayList(); + for (NetworkVO network: _networksDao.listAll()) { + if (!isNetworkSystem(network)) { + networks.add(network); + } + } + return networks; } - + @DB @Override public IPAddressVO markIpAsUnavailable(long addrId) { @@ -4588,7 +4595,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag VirtualMachine.State.Running, VirtualMachine.State.Migrating, VirtualMachine.State.Stopping); return vms.isEmpty(); } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true) @@ -4599,28 +4606,29 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters NetworkVO network = _networksDao.findById(networkId); if (network == null) { - // see NetworkVO.java - InvalidParameterValueException ex = new InvalidParameterValueException("Specified network id doesn't exist in the system"); - ex.addProxyObject("networks", networkId, "networkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find network by id", null); } // don't allow to update network in Destroy state if (network.getState() == Network.State.Destroy) { - throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy); + throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy, null); } // Don't allow to update system network NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId()); + if (offering == null) { + throw new InvalidParameterValueException("Couldn't find networkOffering by id", null); + } + if (offering.isSystemOnly()) { - throw new InvalidParameterValueException("Can't update system networks"); + throw new InvalidParameterValueException("Can't update system networks", null); } // allow to upgrade only Guest networks if (network.getTrafficType() != Networks.TrafficType.Guest) { - throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest); + throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest, null); } - + _accountMgr.checkAccess(callerAccount, null, true, network); if (name != null) { @@ -4633,28 +4641,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // network offering and domain suffix can be updated for Isolated networks only in 3.0 if ((networkOfferingId != null || domainSuffix != null) && network.getGuestType() != GuestType.Isolated) { - throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only"); + throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only", null); } boolean networkOfferingChanged = false; long oldNetworkOfferingId = network.getNetworkOfferingId(); if (networkOfferingId != null) { - NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); - if (networkOffering == null || networkOffering.isSystemOnly()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering with specified id"); - ex.addProxyObject(networkOffering, networkOfferingId, "networkOfferingId"); - throw ex; + if (networkOffering == null) { + throw new InvalidParameterValueException("Couldn't find networkOffering by id", null); } - + if (networkOffering.isSystemOnly()) { + List idList = new ArrayList(); + idList.add(new IdentityProxy(networkOffering, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("NetworkOffering with specified id is System-only", idList); + } + // network offering should be in Enabled state if (networkOffering.getState() != NetworkOffering.State.Enabled) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it"); - ex.addProxyObject(networkOffering, networkOfferingId, "networkOfferingId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(networkOffering, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it", idList); } - + //perform below validation if the network is vpc network if (network.getVpcId() != null) { Vpc vpc = _vpcMgr.getVpc(network.getVpcId()); @@ -4664,18 +4674,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkOfferingId != oldNetworkOfferingId) { if (networkOfferingIsConfiguredForExternalNetworking(networkOfferingId) != networkOfferingIsConfiguredForExternalNetworking(oldNetworkOfferingId) && !changeCidr) { - throw new InvalidParameterValueException("Can't guarantee guest network CIDR is unchanged after updating network!"); + throw new InvalidParameterValueException("Can't guarantee guest network CIDR is unchanged after updating network!", null); } if (changeCidr) { if (!checkForNonStoppedVmInNetwork(network.getId())) { - InvalidParameterValueException ex = new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing CIDR!"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, networkId, "networkId")); + throw new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing CIDR!", idList); } } // check if the network is upgradable if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) { - throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNetworkOfferingId + " to " + networkOfferingId + "; check logs for more information"); + throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNetworkOfferingId + " to " + networkOfferingId + "; check logs for more information", null); } restartNetwork = true; networkOfferingChanged = true; @@ -4692,7 +4702,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (!NetUtils.verifyDomainName(domainSuffix)) { 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); } long offeringId = oldNetworkOfferingId; @@ -4703,8 +4713,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Map dnsCapabilities = getNetworkOfferingServiceCapabilities(_configMgr.getNetworkOffering(offeringId), Service.Dns); String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { - // TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject(). - throw new InvalidParameterValueException("Domain name change is not supported by the network offering id=" + networkOfferingId); + // TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject(). + List idList = new ArrayList(); + idList.add(new IdentityProxy(offering, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("Domain name change is not supported by network offering with specified id", idList); } network.setNetworkDomain(domainSuffix); @@ -4739,8 +4751,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } else { - CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState()); - ex.addProxyObject(network, networkId, "networkId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState()); + ex.addProxyObject(network, networkId, "networkId"); throw ex; } } @@ -4750,8 +4762,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Network.State networkState = _networksDao.findById(networkId).getState(); boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated); if (restartNetwork && !validStateToImplement) { - CloudRuntimeException ex = new CloudRuntimeException("Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState); - ex.addProxyObject(network, networkId, "networkId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState); + ex.addProxyObject(network, networkId, "networkId"); throw ex; } @@ -4850,7 +4862,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } Set availableIps = getAvailableIps(network, requestedIp); - + if (availableIps.isEmpty()) { return null; } @@ -4881,7 +4893,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List ips = _nicDao.listIpAddressInNetwork(network.getId()); Set allPossibleIps = NetUtils.getAllIpsFromCidr(cidr[0], Integer.parseInt(cidr[1])); Set usedIps = new TreeSet(); - + for (String ip : ips) { if (requestedIp != null && requestedIp.equals(ip)) { s_logger.warn("Requested ip address " + requestedIp + " is already in use in network" + network); @@ -4895,7 +4907,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return allPossibleIps; } - + private String getZoneNetworkDomain(long zoneId) { return _dcDao.findById(zoneId).getDomain(); @@ -5009,7 +5021,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + // if all the rules configured on public IP are revoked then, dis-associate IP with network service provider applyIpAssociations(network, true, continueOnError, publicIps); @@ -5081,7 +5093,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // can upgrade only Isolated networks if (oldNetworkOffering.getGuestType() != GuestType.Isolated) { - throw new InvalidParameterValueException("NetworkOfferingId can be upgraded only for the network of type " + GuestType.Isolated); + throw new InvalidParameterValueException("NetworkOfferingId can be upgraded only for the network of type " + GuestType.Isolated, null); } // security group service should be the same @@ -5191,16 +5203,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check if zone exists if (zoneId == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + throw new InvalidParameterValueException("Please specify a valid zone.", null); } DataCenterVO zone = _dcDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + throw new InvalidParameterValueException("Please specify a valid zone.", null); } if (Grouping.AllocationState.Enabled == zone.getAllocationState()) { - // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). + // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId); } @@ -5208,7 +5220,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (zoneType == NetworkType.Basic) { if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) { - // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). + // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic Zone"); } } @@ -5226,7 +5238,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Verify zone type if (zoneType == NetworkType.Basic || (zoneType == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { - throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); + throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled(), null); } String[] tokens = vnetRange.split("-"); @@ -5238,12 +5250,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag vnetEnd = Integer.parseInt(tokens[1]); } } catch (NumberFormatException e) { - throw new InvalidParameterValueException("Please specify valid integers for the vlan range."); + throw new InvalidParameterValueException("Please specify valid integers for the vlan range.", null); } if ((vnetStart > vnetEnd) || (vnetStart < 0) || (vnetEnd > 4096)) { s_logger.warn("Invalid vnet range: start range:" + vnetStart + " end range:" + vnetEnd); - throw new InvalidParameterValueException("Vnet range should be between 0-4096 and start range should be lesser than or equal to end range"); + throw new InvalidParameterValueException("Vnet range should be between 0-4096 and start range should be lesser than or equal to end range", null); } } @@ -5252,14 +5264,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase()); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}"); + throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}", null); } // in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) { - throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only"); + throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only", null); } else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) { - throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only"); + throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only", null); } } @@ -5331,23 +5343,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(id); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(network, id, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find physical network by id", null); } // if zone is of Basic type, don't allow to add vnet range DataCenter zone = _dcDao.findById(network.getDataCenterId()); if (zone == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Zone with id=" + network.getDataCenterId() + " doesn't exist in the system"); - ex.addProxyObject(zone, network.getDataCenterId(), "dataCenterId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find zone by id", null); } if (newVnetRangeString != null) { if (zone.getNetworkType() == NetworkType.Basic || (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: " - + zone.isSecurityGroupEnabled()); + + zone.isSecurityGroupEnabled(), null); } } @@ -5360,7 +5368,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { networkState = PhysicalNetwork.State.valueOf(state); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve state '" + state + "' to a supported value {Enabled or Disabled}"); + throw new InvalidParameterValueException("Unable to resolve state '" + state + "' to a supported value {Enabled or Disabled}", null); } } @@ -5391,15 +5399,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("ISOLATION METHODS:" + network.getIsolationMethods()); // Java does not have unsigned types... if (network.getIsolationMethods().contains("GRE")) { - maxVnet = (int)(Math.pow(2, 32)-1); + maxVnet = (int)(Math.pow(2, 32)-1); } String rangeMessage = " between 0 and " + maxVnet; if (newVnetRange.length < 2) { - throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage, null); } if (newVnetRange[0] == null || newVnetRange[1] == null) { - throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage, null); } try { @@ -5407,14 +5415,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag newEndVnet = Integer.parseInt(newVnetRange[1]); } catch (NumberFormatException e) { s_logger.warn("Unable to parse vnet range:", e); - throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage, null); } if (newStartVnet < 0 || newEndVnet > maxVnet) { - throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage); + throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage, null); } if (newStartVnet > newEndVnet) { - throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage + " and start range should be lesser than or equal to stop range"); + throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage + " and start range should be lesser than or equal to stop range", null); } if (physicalNetworkHasAllocatedVnets(network.getDataCenterId(), network.getId())) { @@ -5424,7 +5432,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // check if vnet is being extended if (newStartVnet.intValue() > existingStartVnet || newEndVnet.intValue() < existingEndVnet) { - throw new InvalidParameterValueException("Can't shrink existing vnet range as it the range has vnets allocated. Only extending existing vnet is supported"); + throw new InvalidParameterValueException("Can't shrink existing vnet range as it the range has vnets allocated. Only extending existing vnet is supported", null); } if (newStartVnet < existingStartVnet) { @@ -5469,13 +5477,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_DELETE, eventDescription = "deleting physical network", async = true) @DB public boolean deletePhysicalNetwork(Long physicalNetworkId) { - // verify input parameters PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(pNetwork, physicalNetworkId, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find Physical Network by id", null); } checkIfPhysicalNetworkIsDeletable(physicalNetworkId); @@ -5501,7 +5506,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // delete service providers List providers = _pNSPDao.listBy(physicalNetworkId); - + for(PhysicalNetworkServiceProviderVO provider : providers){ try { deleteNetworkServiceProvider(provider.getId()); @@ -5518,7 +5523,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId); boolean success = _physicalNetworkDao.remove(physicalNetworkId); - + txn.commit(); return success; @@ -5601,14 +5606,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (providerName != null) { provider = Network.Provider.getProvider(providerName); if (provider == null) { - throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName); + throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName, null); } } if (provider != null) { NetworkElement element = getElementImplementingProvider(providerName); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'", null); } return new ArrayList(element.getCapabilities().keySet()); } else { @@ -5622,7 +5627,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (serviceName != null) { service = Network.Service.getService(serviceName); if (service == null) { - throw new InvalidParameterValueException("Invalid Network Service=" + serviceName); + throw new InvalidParameterValueException("Invalid Network Service=" + serviceName, null); } } @@ -5660,44 +5665,40 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(network, physicalNetworkId, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find Physical Network by id", null); } // verify input parameters if (destinationPhysicalNetworkId != null) { PhysicalNetworkVO destNetwork = _physicalNetworkDao.findById(destinationPhysicalNetworkId); if (destNetwork == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Destination Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(destNetwork, destinationPhysicalNetworkId, "destinationPhysicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find Destination Physical Network by id", null); } } if (providerName != null) { Provider provider = Network.Provider.getProvider(providerName); if (provider == null) { - throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName); + throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName, null); } } if (_pNSPDao.findByServiceProvider(physicalNetworkId, providerName) != null) { - // TBD: send uuid instead of physicalNetworkId. + // TBD: send uuid instead of physicalNetworkId. throw new CloudRuntimeException("The '" + providerName + "' provider already exists on physical network : " + physicalNetworkId); } // check if services can be turned off NetworkElement element = getElementImplementingProvider(providerName); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'", null); } List services = new ArrayList(); if (enabledServices != null) { if (!element.canEnableIndividualServices()) { if (enabledServices.size() != element.getCapabilities().keySet().size()) { - throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + providerName + "'"); + throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + providerName + "'", null); } } @@ -5706,14 +5707,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (String serviceName : enabledServices) { Network.Service service = Network.Service.getService(serviceName); if (service == null || service == Service.Gateway) { - throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName); + throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName, null); } else if (service == Service.SourceNat) { addGatewayService = true; } // check if the service is provided by this Provider if (!element.getCapabilities().containsKey(service)) { - throw new InvalidParameterValueException(providerName + " Provider cannot provide this Service specified=" + serviceName); + throw new InvalidParameterValueException(providerName + " Provider cannot provide this Service specified=" + serviceName, null); } services.add(service); } @@ -5776,12 +5777,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); if (provider == null) { - throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find Network Service Provider by id", null); } NetworkElement element = getElementImplementingProvider(provider.getProviderName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'", null); } PhysicalNetworkServiceProvider.State state = null; @@ -5789,7 +5790,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { state = PhysicalNetworkServiceProvider.State.valueOf(stateStr); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve state '" + stateStr + "' to a supported value {Enabled or Disabled}"); + throw new InvalidParameterValueException("Unable to resolve state '" + stateStr + "' to a supported value {Enabled or Disabled}", null); } } @@ -5797,7 +5798,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (state != null) { if (state == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported"); + throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported", null); } if (s_logger.isDebugEnabled()) { @@ -5823,7 +5824,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (enabledServices != null) { // check if services can be turned of if (!element.canEnableIndividualServices()) { - throw new InvalidParameterValueException("Cannot update set of Services for this Service Provider '" + provider.getProviderName() + "'"); + throw new InvalidParameterValueException("Cannot update set of Services for this Service Provider '" + provider.getProviderName() + "'", null); } // validate Services @@ -5831,7 +5832,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (String serviceName : enabledServices) { Network.Service service = Network.Service.getService(serviceName); if (service == null) { - throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName); + throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName, null); } services.add(service); } @@ -5852,7 +5853,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); if (provider == null) { - throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find Network Service Provider by id", null); } // check if there are networks using this provider @@ -5870,7 +5871,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } NetworkElement element = getElementImplementingProvider(provider.getProviderName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'", null); } if (element != null && element.shutdownProviderInstances(provider, context)) { @@ -5910,14 +5911,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { pNtwks = _physicalNetworkDao.listByZone(zoneId); } - + if (pNtwks.isEmpty()) { - throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find physical network in zone with specified id", idList); } if (pNtwks.size() > 1) { if (tag == null) { - throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " and no tags are specified in order to make a choice"); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("More than one physical networks exist in zone with specified id and no tags are specified in order to make a choice", idList); } Long pNtwkId = null; @@ -5929,7 +5934,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } if (pNtwkId == null) { - throw new InvalidParameterValueException("Unable to find physical network which match the tags " + tag); + throw new InvalidParameterValueException("Unable to find physical network which match the tags " + tag, null); } return pNtwkId; } else { @@ -5941,11 +5946,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public PhysicalNetwork translateZoneIdToPhysicalNetwork(long zoneId) { List pNtwks = _physicalNetworkDao.listByZone(zoneId); if (pNtwks.isEmpty()) { - throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find physical network in zone with specified id", idList); } if (pNtwks.size() > 1) { - throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("More than one physical networks exist in zone with specified id", idList); } return pNtwks.get(0); @@ -6011,7 +6020,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // shouldn't even come here as network is being cleaned up after all network elements are shutdown s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex); } - + //revoke all network ACLs for network try { if (_networkACLMgr.revokeAllNetworkACLsForNetwork(networkId, callerUserId, caller)) { @@ -6030,9 +6039,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List ipsToRelease = _ipAddressDao.listByAssociatedNetwork(networkId, null); for (IPAddressVO ipToRelease : ipsToRelease) { if (ipToRelease.getVpcId() != null) { - IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId()); - assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable."; - } + IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId()); + assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable."; + } } try { @@ -6085,7 +6094,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag FirewallRuleVO ruleVO = _firewallDao.findById(firewallStaticNatRule.getId()); if (ip == null || !ip.isOneToOneNat() || ip.getAssociatedWithVmId() == null) { - throw new InvalidParameterValueException("Source ip address of the rule id=" + firewallStaticNatRule.getId() + " is not static nat enabled"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(firewallStaticNatRule, firewallStaticNatRule.getId(), "firewallStaticNatRuleId")); + throw new InvalidParameterValueException("Source ip address of the rule with specified id is not static nat enabled", idList); } String dstIp = getIpInNetwork(ip.getAssociatedWithVmId(), firewallStaticNatRule.getNetworkId()); @@ -6151,7 +6162,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Failed to cleanup firewall rules as a part of shutdownNetworkRules due to ", ex); success = false; } - + //revoke all Network ACLs for the network w/o applying them in the DB List networkACLs = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.NetworkACL); if (s_logger.isDebugEnabled()) { @@ -6173,7 +6184,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules due to ", ex); success = false; } - + // Get all ip addresses, mark as releasing and release them on the backend Network network = getNetwork(networkId); @@ -6224,7 +6235,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); if (network == null) { - throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find Physical Network by id", null); } Networks.TrafficType trafficType = null; @@ -6232,7 +6243,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { trafficType = Networks.TrafficType.valueOf(trafficTypeStr); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve trafficType '" + trafficTypeStr + "' to a supported value"); + throw new InvalidParameterValueException("Unable to resolve trafficType '" + trafficTypeStr + "' to a supported value", null); } } @@ -6318,7 +6329,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); if (trafficType == null) { - throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find traffic type by id", null); } if (xenLabel != null) { @@ -6350,7 +6361,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); if (trafficType == null) { - throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find traffic type by id", null); } // check if there are any networks associated to this physical network with this traffic type @@ -6371,9 +6382,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List listTrafficTypes(Long physicalNetworkId) { PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(network, physicalNetworkId, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find Physical Network by id", null); } return _pNTrafficTypeDao.listBy(physicalNetworkId); @@ -6385,21 +6394,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List networkList = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType); if (networkList.isEmpty()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the default physical network with traffic=" + trafficType + " in the specified zone id"); - // Since we don't have a DataCenterVO object at our disposal, we just set the table name that the zoneId's corresponding uuid is looked up from, manually. - ex.addProxyObject("data_center", zoneId, "zoneId"); - throw ex; + List idList = new ArrayList(); + // Since we don't have a DataCenterVO object at our disposal, we just set the table name that the zoneId's corresponding uuid is looked up from, manually. + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find the default physical network with traffic=" + trafficType + " in the specified zone id", idList); } if (networkList.size() > 1) { - InvalidParameterValueException ex = new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " with traffic type=" + trafficType); - ex.addProxyObject("data_center", zoneId, "zoneId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("More than one physical networks exist in zone with specified id, with traffic type=" + trafficType, idList); } return networkList.get(0); } - + @Override public String getDefaultManagementTrafficLabel(long zoneId, HypervisorType hypervisorType){ try{ @@ -6408,12 +6417,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if(mgmtTraffic != null){ String label = null; switch(hypervisorType){ - case XenServer : label = mgmtTraffic.getXenNetworkLabel(); - break; - case KVM : label = mgmtTraffic.getKvmNetworkLabel(); - break; - case VMware : label = mgmtTraffic.getVmwareNetworkLabel(); - break; + case XenServer : label = mgmtTraffic.getXenNetworkLabel(); + break; + case KVM : label = mgmtTraffic.getKvmNetworkLabel(); + break; + case VMware : label = mgmtTraffic.getVmwareNetworkLabel(); + break; } return label; } @@ -6424,7 +6433,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return null; } - + @Override public String getDefaultStorageTrafficLabel(long zoneId, HypervisorType hypervisorType){ try{ @@ -6433,12 +6442,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if(storageTraffic != null){ String label = null; switch(hypervisorType){ - case XenServer : label = storageTraffic.getXenNetworkLabel(); - break; - case KVM : label = storageTraffic.getKvmNetworkLabel(); - break; - case VMware : label = storageTraffic.getVmwareNetworkLabel(); - break; + case XenServer : label = storageTraffic.getXenNetworkLabel(); + break; + case KVM : label = storageTraffic.getKvmNetworkLabel(); + break; + case VMware : label = storageTraffic.getVmwareNetworkLabel(); + break; } return label; } @@ -6632,10 +6641,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public String getNetworkTag(HypervisorType hType, Network network) { // no network tag for control traffic type - TrafficType effectiveTrafficType = network.getTrafficType(); - if(hType == HypervisorType.VMware && effectiveTrafficType == TrafficType.Control) - effectiveTrafficType = TrafficType.Management; - + TrafficType effectiveTrafficType = network.getTrafficType(); + if(hType == HypervisorType.VMware && effectiveTrafficType == TrafficType.Control) + effectiveTrafficType = TrafficType.Management; + if (effectiveTrafficType == TrafficType.Control) { return null; } @@ -6662,11 +6671,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // have to remove this sanity check as VMware control network is management network // we need to retrieve traffic label information through physical network -/* + /* if (network.getTrafficType() == TrafficType.Control) { return null; } -*/ + */ Long physicalNetworkId = network.getPhysicalNetworkId(); if (physicalNetworkId == null) { @@ -6692,11 +6701,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public NetworkVO getExclusiveGuestNetwork(long zoneId) { List networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, zoneId, GuestType.Shared, TrafficType.Guest); if (networks == null || networks.isEmpty()) { - throw new InvalidParameterValueException("Unable to find network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone with specified id", idList); } if (networks.size() > 1) { - throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone with specified id", idList); } @@ -6773,7 +6786,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (checkPhysicalNetwork) { if (!_pNSPDao.isServiceProviderEnabled(physicalNetworkId, provider, service)) { throw new UnsupportedServiceException("Provider " + provider + " is either not enabled or doesn't " + - "support service " + service + " in physical network id=" + physicalNetworkId); + "support service " + service + " in physical network id=" + physicalNetworkId); } } @@ -6849,7 +6862,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // check if services can be turned off NetworkElement element = getElementImplementingProvider(provider.getName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'", null); } Set enabledServices = new HashSet(); @@ -6859,15 +6872,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (!element.canEnableIndividualServices()) { Set requiredServices = new HashSet(); requiredServices.addAll(element.getCapabilities().keySet()); - + if (requiredServices.contains(Network.Service.Gateway)) { requiredServices.remove(Network.Service.Gateway); } - + if (requiredServices.contains(Network.Service.Firewall)) { requiredServices.remove(Network.Service.Firewall); } - + if (enabledServices.contains(Network.Service.Firewall)) { enabledServices.remove(Network.Service.Firewall); } @@ -6886,7 +6899,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag servicesSet.delete(servicesSet.toString().length() - 2, servicesSet.toString().length()); throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services: " + servicesSet.toString() + " for Service Provider " - + provider.getName()); + + provider.getName(), null); } } for (Service service : enabledServices) { @@ -7007,6 +7020,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + @Override public IpAddress assignSystemIp(long networkId, Account owner, boolean forElasticLb, boolean forElasticIp) throws InsufficientAddressCapacityException { Network guestNetwork = getNetwork(networkId); @@ -7069,8 +7083,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + @Override public void allocateDirectIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network, String requestedIp) throws InsufficientVirtualNetworkCapcityException, - InsufficientAddressCapacityException { + InsufficientAddressCapacityException { if (nic.getIp4Address() == null) { PublicIp ip = assignPublicIpAddress(dc.getId(), null, vm.getOwner(), VlanType.DirectAttached, network.getId(), requestedIp, false); nic.setIp4Address(ip.getAddress().toString()); @@ -7146,17 +7161,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return null; } - + @Override public List listNetworksByVpc(long vpcId) { return _networksDao.listByVpc(vpcId); } - + @Override public String getDefaultNetworkDomain() { return _networkDomain; } - + @Override public List getNtwkOffDistinctProviders(long networkId) { List providerNames = _ntwkOfferingSrvcDao.getDistinctProviders(networkId); @@ -7175,27 +7190,27 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return false; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true) public IpAddress associateIP(long ipId, Long networkId, Long vpcId) throws InsufficientAddressCapacityException, - ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException { + ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException { if (vpcId != null) { return associateIPToVpc(ipId, vpcId); } - + if (networkId != null) { Network network = _networksDao.findById(networkId); if (network == null) { - throw new InvalidParameterValueException("Invalid network id is given"); + throw new InvalidParameterValueException("Invalid network id is given", null); } - + if (network.getVpcId() != null) { - throw new InvalidParameterValueException("Specify vpcId to associate ip address to VPC"); + throw new InvalidParameterValueException("Specify vpcId to associate ip address to VPC", null); } return associateIPToGuestNetwork(ipId, networkId); } - + return null; } @@ -7203,8 +7218,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List networkList = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType); if (networkList.isEmpty()) { + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); throw new InvalidParameterValueException("Unable to find the default physical network with traffic=" - + trafficType + " in zone id=" + zoneId + ". "); + + trafficType + " in zone with specified id", idList); } if (networkList.size() > 1) { @@ -7214,16 +7231,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return networkList.get(0); } - + @Override public void unassignIPFromVpcNetwork(long ipId) { IPAddressVO ip = _ipAddressDao.findById(ipId); Long vpcId = ip.getVpcId(); - + if (vpcId == null) { return; } - + ip.setAssociatedWithNetworkId(null); _ipAddressDao.update(ipId, ip); s_logger.debug("IP address " + ip + " is no longer associated with the network inside vpc id=" + vpcId); @@ -7233,49 +7250,46 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan, String startIp, String endIp, String gateway, String netmask, long networkOwnerId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { - + Account owner = _accountMgr.getAccount(networkOwnerId); - + // Get system network offeirng NetworkOfferingVO ntwkOff = _systemNetworks.get(NetworkOffering.SystemPrivateGatewayNetworkOffering); - + // Validate physical network PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId); if (pNtwk == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a physical network" + - " having the given id"); - ex.addProxyObject("physical_network", physicalNetworkId, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Unable to find physical network by id", null); } - + // VALIDATE IP INFO // if end ip is not specified, default it to startIp if (!NetUtils.isValidIp(startIp)) { - throw new InvalidParameterValueException("Invalid format for the startIp parameter"); + throw new InvalidParameterValueException("Invalid format for the startIp parameter", null); } if (endIp == null) { endIp = startIp; } else if (!NetUtils.isValidIp(endIp)) { - throw new InvalidParameterValueException("Invalid format for the endIp parameter"); + throw new InvalidParameterValueException("Invalid format for the endIp parameter", null); } String cidr = null; if (!NetUtils.isValidIp(gateway)) { - throw new InvalidParameterValueException("Invalid gateway"); + throw new InvalidParameterValueException("Invalid gateway", null); } if (!NetUtils.isValidNetmask(netmask)) { - throw new InvalidParameterValueException("Invalid netmask"); + throw new InvalidParameterValueException("Invalid netmask", null); } cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); - - + + Transaction txn = Transaction.currentTxn(); txn.start(); - + //lock datacenter as we need to get mac address seq from there DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true); - + //check if we need to create guest network Network privateNetwork = _networksDao.getPrivateNetwork(BroadcastDomainType.Vlan.toUri(vlan).toString(), cidr, networkOwnerId, pNtwk.getDataCenterId()); @@ -7287,44 +7301,44 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { s_logger.debug("Private network already exists: " + privateNetwork); } - + //add entry to private_ip_address table PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNetwork.getId(), startIp); if (privateIp != null) { throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + - " in zone " + _configMgr.getZone(pNtwk.getDataCenterId()).getName()); + " in zone " + _configMgr.getZone(pNtwk.getDataCenterId()).getName(), null); } - + Long mac = dc.getMacAddress(); Long nextMac = mac + 1; dc.setMacAddress(nextMac); - + privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac); _privateIpDao.persist(privateIp); - + _dcDao.update(dc.getId(), dc); - + txn.commit(); s_logger.debug("Private network " + privateNetwork + " is created"); return privateNetwork; } - + @Override public boolean setupDns(Network network, Provider provider) { boolean dnsProvided = isProviderSupportServiceInNetwork(network.getId(), Service.Dns, provider ); boolean dhcpProvided =isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, provider); - + boolean setupDns = dnsProvided || dhcpProvided; return setupDns; } - + @Override public List getPhysicalNtwksSupportingTrafficType(long zoneId, TrafficType trafficType) { - + List pNtwks = _physicalNetworkDao.listByZone(zoneId); - + Iterator it = pNtwks.iterator(); while (it.hasNext()) { PhysicalNetwork pNtwk = it.next(); @@ -7334,7 +7348,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return pNtwks; } - + @Override public boolean isPrivateGateway(Nic guestNic) { Network network = getNetwork(guestNic.getNetworkId()); diff --git a/server/src/com/cloud/template/TemplateAdapterBase.java b/server/src/com/cloud/template/TemplateAdapterBase.java index b8dfb1de41c..a63f8897b2c 100755 --- a/server/src/com/cloud/template/TemplateAdapterBase.java +++ b/server/src/com/cloud/template/TemplateAdapterBase.java @@ -57,95 +57,97 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.UserVmVO; public abstract class TemplateAdapterBase implements TemplateAdapter { - private final static Logger s_logger = Logger.getLogger(TemplateAdapterBase.class); - protected String _name; - protected @Inject DomainDao _domainDao; - protected @Inject AccountDao _accountDao; - protected @Inject ConfigurationDao _configDao; - protected @Inject UserDao _userDao; - protected @Inject AccountManager _accountMgr; - protected @Inject DataCenterDao _dcDao; - protected @Inject VMTemplateDao _tmpltDao; - protected @Inject VMTemplateHostDao _tmpltHostDao; - protected @Inject VMTemplateZoneDao _tmpltZoneDao; - protected @Inject UsageEventDao _usageEventDao; - protected @Inject HostDao _hostDao; - protected @Inject ResourceLimitService _resourceLimitMgr; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - return true; - } + private final static Logger s_logger = Logger.getLogger(TemplateAdapterBase.class); + protected String _name; + protected @Inject DomainDao _domainDao; + protected @Inject AccountDao _accountDao; + protected @Inject ConfigurationDao _configDao; + protected @Inject UserDao _userDao; + protected @Inject AccountManager _accountMgr; + protected @Inject DataCenterDao _dcDao; + protected @Inject VMTemplateDao _tmpltDao; + protected @Inject VMTemplateHostDao _tmpltHostDao; + protected @Inject VMTemplateZoneDao _tmpltZoneDao; + protected @Inject UsageEventDao _usageEventDao; + protected @Inject HostDao _hostDao; + protected @Inject ResourceLimitService _resourceLimitMgr; - @Override - public String getName() { - return _name; - } + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } - @Override - public boolean start() { - return true; - } + @Override + public String getName() { + return _name; + } - @Override - public boolean stop() { - return true; - } - - private static boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); - } + @Override + public boolean start() { + return true; + } - public TemplateProfile prepare(boolean isIso, Long userId, String name, String displayText, Integer bits, + @Override + public boolean stop() { + return true; + } + + private static boolean isAdmin(short accountType) { + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || + (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || + (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || + (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + } + + @Override + public TemplateProfile prepare(boolean isIso, Long userId, String name, String displayText, Integer bits, Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured, Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType, String accountName, Long domainId, String chksum, Boolean bootable, Map details) throws ResourceAllocationException { - return prepare(isIso, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, format, guestOSId, zoneId, hypervisorType, - chksum, bootable, null, null, details, false); - } - - public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits, - Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured, - Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType, - String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshkeyEnabled) throws ResourceAllocationException { - //Long accountId = null; - // parameters verification - - if (isPublic == null) { - isPublic = Boolean.FALSE; - } - - if (zoneId.longValue() == -1) { - zoneId = null; - } - - if (isIso) { - if (bootable == null) { - bootable = Boolean.TRUE; - } - GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE); - if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true){ - throw new InvalidParameterValueException("Please pass a valid GuestOS Id"); - } - if (bootable == false){ - guestOSId = noneGuestOs.getId(); //Guest os id of None. - } - } else { - if (bits == null) { - bits = Integer.valueOf(64); - } - if (passwordEnabled == null) { - passwordEnabled = false; - } - if (requiresHVM == null) { - requiresHVM = true; - } - } - + return prepare(isIso, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, format, guestOSId, zoneId, hypervisorType, + chksum, bootable, null, null, details, false); + } + + @Override + public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits, + Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured, + Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType, + String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshkeyEnabled) throws ResourceAllocationException { + //Long accountId = null; + // parameters verification + + if (isPublic == null) { + isPublic = Boolean.FALSE; + } + + if (zoneId.longValue() == -1) { + zoneId = null; + } + + if (isIso) { + if (bootable == null) { + bootable = Boolean.TRUE; + } + GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE); + if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true){ + throw new InvalidParameterValueException("Please pass a valid GuestOS Id", null); + } + if (bootable == false){ + guestOSId = noneGuestOs.getId(); //Guest os id of None. + } + } else { + if (bits == null) { + bits = Integer.valueOf(64); + } + if (passwordEnabled == null) { + passwordEnabled = false; + } + if (requiresHVM == null) { + requiresHVM = true; + } + } + if (isExtractable == null) { isExtractable = Boolean.FALSE; } @@ -153,201 +155,206 @@ public abstract class TemplateAdapterBase implements TemplateAdapter { sshkeyEnabled = Boolean.FALSE; } - boolean isAdmin = _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN; + boolean isAdmin = _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN; - if (!isAdmin && zoneId == null) { - throw new InvalidParameterValueException("Please specify a valid zone Id."); - } + if (!isAdmin && zoneId == null) { + throw new InvalidParameterValueException("Please specify a valid zone Id.", null); + } - if (url.toLowerCase().contains("file://")) { - throw new InvalidParameterValueException("File:// type urls are currently unsupported"); - } - - boolean allowPublicUserTemplates = Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates")); - if (!isAdmin && !allowPublicUserTemplates && isPublic) { - throw new InvalidParameterValueException("Only private templates/ISO can be created."); - } + if (url.toLowerCase().contains("file://")) { + throw new InvalidParameterValueException("File:// type urls are currently unsupported", null); + } + + boolean allowPublicUserTemplates = Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates")); + if (!isAdmin && !allowPublicUserTemplates && isPublic) { + throw new InvalidParameterValueException("Only private templates/ISO can be created.", null); + } + + if (!isAdmin || featured == null) { + featured = Boolean.FALSE; + } + + 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 (!isAdmin || featured == null) { - featured = Boolean.FALSE; - } - - ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase()); - if (imgfmt == null) { - throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); - } - // Check that the resource limit for templates/ISOs won't be exceeded UserVO user = _userDao.findById(userId); if (user == null) { throw new IllegalArgumentException("Unable to find user with id " + userId); } - + _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template); - + if (templateOwner.getType() != Account.ACCOUNT_TYPE_ADMIN && zoneId == null) { - throw new IllegalArgumentException("Only admins can create templates in all zones"); + throw new IllegalArgumentException("Only admins can create templates in all zones"); } - + // If a zoneId is specified, make sure it is valid if (zoneId != null) { - DataCenterVO zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new IllegalArgumentException("Please specify a valid zone."); - } - Account caller = UserContext.current().getCaller(); - if(Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())){ - throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: "+ zoneId ); - } + DataCenterVO zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new IllegalArgumentException("Please specify a valid zone."); + } + Account caller = UserContext.current().getCaller(); + if(Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())){ + throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: "+ zoneId ); + } } - + List systemvmTmplts = _tmpltDao.listAllSystemVMTemplates(); for (VMTemplateVO template : systemvmTmplts) { if (template.getName().equalsIgnoreCase(name) || template.getDisplayText().equalsIgnoreCase(displayText)) { throw new IllegalArgumentException("Cannot use reserved names for templates"); } } - + Long id = _tmpltDao.getNextInSequence(Long.class, "id"); UserContext.current().setEventDetails("Id: " +id+ " name: " + name); - return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, - featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled); - } - - @Override - public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException { - //check if the caller can operate with the template owner + return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, + featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled); + } + + @Override + public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException { + //check if the caller can operate with the template owner Account caller = UserContext.current().getCaller(); Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); _accountMgr.checkAccess(caller, null, true, owner); - - return prepare(false, UserContext.current().getCallerUserId(), cmd.getTemplateName(), cmd.getDisplayText(), - cmd.getBits(), cmd.isPasswordEnabled(), cmd.getRequiresHvm(), cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), - cmd.isExtractable(), cmd.getFormat(), cmd.getOsTypeId(), cmd.getZoneId(), HypervisorType.getType(cmd.getHypervisor()), - cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails(), cmd.isSshKeyEnabled()); - } - public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { - //check if the caller can operate with the template owner - Account caller = UserContext.current().getCaller(); - Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); - _accountMgr.checkAccess(caller, null, true, owner); - - return prepare(true, UserContext.current().getCallerUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false, - true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(), - cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false); - } - - protected VMTemplateVO persistTemplate(TemplateProfile profile) { - Long zoneId = profile.getZoneId(); - VMTemplateVO template = new VMTemplateVO(profile.getTemplateId(), profile.getName(), profile.getFormat(), profile.getIsPublic(), - profile.getFeatured(), profile.getIsExtractable(), TemplateType.USER, profile.getUrl(), profile.getRequiresHVM(), - profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(), - profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(), - profile.getDetails(), profile.getSshKeyEnabled()); - - if (zoneId == null || zoneId.longValue() == -1) { + return prepare(false, UserContext.current().getCallerUserId(), cmd.getTemplateName(), cmd.getDisplayText(), + cmd.getBits(), cmd.isPasswordEnabled(), cmd.getRequiresHvm(), cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), + cmd.isExtractable(), cmd.getFormat(), cmd.getOsTypeId(), cmd.getZoneId(), HypervisorType.getType(cmd.getHypervisor()), + cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails(), cmd.isSshKeyEnabled()); + } + + @Override + public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { + //check if the caller can operate with the template owner + Account caller = UserContext.current().getCaller(); + Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); + _accountMgr.checkAccess(caller, null, true, owner); + + return prepare(true, UserContext.current().getCallerUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false, + true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(), + cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false); + } + + protected VMTemplateVO persistTemplate(TemplateProfile profile) { + Long zoneId = profile.getZoneId(); + VMTemplateVO template = new VMTemplateVO(profile.getTemplateId(), profile.getName(), profile.getFormat(), profile.getIsPublic(), + profile.getFeatured(), profile.getIsExtractable(), TemplateType.USER, profile.getUrl(), profile.getRequiresHVM(), + profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(), + profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(), + profile.getDetails(), profile.getSshKeyEnabled()); + + if (zoneId == null || zoneId.longValue() == -1) { List dcs = _dcDao.listAll(); - + if (dcs.isEmpty()) { - throw new CloudRuntimeException("No zones are present in the system, can't add template"); + throw new CloudRuntimeException("No zones are present in the system, can't add template"); } template.setCrossZones(true); - for (DataCenterVO dc: dcs) { - _tmpltDao.addTemplateToZone(template, dc.getId()); - } - + for (DataCenterVO dc: dcs) { + _tmpltDao.addTemplateToZone(template, dc.getId()); + } + } else { - _tmpltDao.addTemplateToZone(template, zoneId); + _tmpltDao.addTemplateToZone(template, zoneId); } - return _tmpltDao.findById(template.getId()); - } - + return _tmpltDao.findById(template.getId()); + } - private Long accountAndUserValidation(Account account, long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg) - throws PermissionDeniedException { - if (account != null) { - if (!isAdmin(account.getType())) { - if ((vmInstanceCheck != null) && (account.getId() != vmInstanceCheck.getAccountId())) { - throw new PermissionDeniedException(msg + ". Permission denied."); - } + private Long accountAndUserValidation(Account account, long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg) + throws PermissionDeniedException { - if ((template != null) - && (!template.isPublicTemplate() && (account.getId() != template.getAccountId()) && (template.getTemplateType() != TemplateType.PERHOST))) { - throw new PermissionDeniedException(msg + ". Permission denied."); - } + if (account != null) { + if (!isAdmin(account.getType())) { + if ((vmInstanceCheck != null) && (account.getId() != vmInstanceCheck.getAccountId())) { + throw new PermissionDeniedException(msg + ". Permission denied."); + } - } else { - if ((vmInstanceCheck != null) && !_domainDao.isChildDomain(account.getDomainId(), vmInstanceCheck.getDomainId())) { - throw new PermissionDeniedException(msg + ". Permission denied."); - } - // FIXME: if template/ISO owner is null we probably need to - // throw some kind of exception + if ((template != null) + && (!template.isPublicTemplate() && (account.getId() != template.getAccountId()) && (template.getTemplateType() != TemplateType.PERHOST))) { + throw new PermissionDeniedException(msg + ". Permission denied."); + } - if (template != null) { - Account templateOwner = _accountDao.findById(template.getAccountId()); - if ((templateOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), templateOwner.getDomainId())) { - throw new PermissionDeniedException(msg + ". Permission denied."); - } - } - } - } + } else { + if ((vmInstanceCheck != null) && !_domainDao.isChildDomain(account.getDomainId(), vmInstanceCheck.getDomainId())) { + throw new PermissionDeniedException(msg + ". Permission denied."); + } + // FIXME: if template/ISO owner is null we probably need to + // throw some kind of exception - return userId; - } - - public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) { - Long templateId = cmd.getId(); - Long userId = UserContext.current().getCallerUserId(); - Account account = UserContext.current().getCaller(); - Long zoneId = cmd.getZoneId(); + if (template != null) { + Account templateOwner = _accountDao.findById(template.getAccountId()); + if ((templateOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), templateOwner.getDomainId())) { + throw new PermissionDeniedException(msg + ". Permission denied."); + } + } + } + } - VMTemplateVO template = _tmpltDao.findById(templateId.longValue()); - if (template == null) { - throw new InvalidParameterValueException("unable to find template with id " + templateId); - } + return userId; + } - userId = accountAndUserValidation(account, userId, null, template, "Unable to delete template "); - - UserVO user = _userDao.findById(userId); - if (user == null) { - throw new InvalidParameterValueException("Please specify a valid user."); - } - - if (template.getFormat() == ImageFormat.ISO) { - throw new InvalidParameterValueException("Please specify a valid template."); - } - - return new TemplateProfile(userId, template, zoneId); - } - - public TemplateProfile prepareDelete(DeleteIsoCmd cmd) { - Long templateId = cmd.getId(); + @Override + public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) { + Long templateId = cmd.getId(); Long userId = UserContext.current().getCallerUserId(); Account account = UserContext.current().getCaller(); Long zoneId = cmd.getZoneId(); - + VMTemplateVO template = _tmpltDao.findById(templateId.longValue()); if (template == null) { - throw new InvalidParameterValueException("unable to find iso with id " + templateId); + throw new InvalidParameterValueException("unable to find template by id", null); } - - userId = accountAndUserValidation(account, userId, null, template, "Unable to delete iso " ); - - UserVO user = _userDao.findById(userId); - if (user == null) { - throw new InvalidParameterValueException("Please specify a valid user."); - } - - if (template.getFormat() != ImageFormat.ISO) { - throw new InvalidParameterValueException("Please specify a valid iso."); - } - - return new TemplateProfile(userId, template, zoneId); - } - abstract public VMTemplateVO create(TemplateProfile profile); - abstract public boolean delete(TemplateProfile profile); + userId = accountAndUserValidation(account, userId, null, template, "Unable to delete template "); + + UserVO user = _userDao.findById(userId); + if (user == null) { + throw new InvalidParameterValueException("Please specify a valid user.", null); + } + + if (template.getFormat() == ImageFormat.ISO) { + throw new InvalidParameterValueException("Please specify a valid template.", null); + } + + return new TemplateProfile(userId, template, zoneId); + } + + @Override + public TemplateProfile prepareDelete(DeleteIsoCmd cmd) { + Long templateId = cmd.getId(); + Long userId = UserContext.current().getCallerUserId(); + Account account = UserContext.current().getCaller(); + Long zoneId = cmd.getZoneId(); + + VMTemplateVO template = _tmpltDao.findById(templateId.longValue()); + if (template == null) { + throw new InvalidParameterValueException("unable to find iso by id", null); + } + + userId = accountAndUserValidation(account, userId, null, template, "Unable to delete iso " ); + + UserVO user = _userDao.findById(userId); + if (user == null) { + throw new InvalidParameterValueException("Please specify a valid user.", null); + } + + if (template.getFormat() != ImageFormat.ISO) { + throw new InvalidParameterValueException("Please specify a valid iso.", null); + } + + return new TemplateProfile(userId, template, zoneId); + } + + @Override + abstract public VMTemplateVO create(TemplateProfile profile); + @Override + abstract public boolean delete(TemplateProfile profile); } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index 9e091164797..10094de7c2d 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -102,6 +102,7 @@ import com.cloud.user.Account.State; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; @@ -264,6 +265,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return true; } + @Override public AccountVO getSystemAccount() { if (_systemAccount == null) { _systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM); @@ -354,7 +356,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (!granted) { assert false : "How can all of the security checkers pass on checking this check: " + entity; - throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity); + throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity); } } @@ -445,7 +447,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public boolean deleteAccount(AccountVO account, long callerUserId, Account caller) { long accountId = account.getId(); - + //delete the account record if (!_accountDao.remove(accountId)) { s_logger.error("Unable to delete account " + accountId); @@ -463,7 +465,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) { long accountId = account.getId(); boolean accountCleanupNeeded = false; - + try { //cleanup the users from the account List users = _userDao.listByAccount(accountId); @@ -473,10 +475,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag accountCleanupNeeded = true; } } - + //delete the account from project accounts _projectAccountDao.removeAccountFromProjects(accountId); - + // delete all vm groups belonging to accont List groups = _vmGroupDao.listByAccountId(accountId); for (InstanceGroupVO group : groups) { @@ -598,7 +600,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag List ipsToRelease = _ipAddressDao.listByAccount(accountId); for (IpAddress ip : ipsToRelease) { s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup"); - if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) { + if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) { s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup"); accountCleanupNeeded = true; } @@ -704,37 +706,39 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId == null) { domainId = DomainVO.ROOT_DOMAIN; } - + if (userName.isEmpty()) { - throw new InvalidParameterValueException("Username is empty"); + throw new InvalidParameterValueException("Username is empty", null); } - + if (firstName.isEmpty()) { - throw new InvalidParameterValueException("Firstname is empty"); + throw new InvalidParameterValueException("Firstname is empty", null); } - + if (lastName.isEmpty()) { - throw new InvalidParameterValueException("Lastname is empty"); + throw new InvalidParameterValueException("Lastname is empty", null); } // Validate domain Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account"); + throw new InvalidParameterValueException("The domain does not exist; unable to create account", null); } // Check permissions checkAccess(UserContext.current().getCaller(), domain); if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) { - throw new InvalidParameterValueException("The user " + userName + " already exists in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("The user " + userName + " already exists in domain with specified id", idList); } if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } @@ -778,7 +782,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag Account account = _accountDao.findEnabledAccount(accountName, domainId); if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain id=" + domainId + " to create user"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specified id to create user", idList); } if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) { @@ -807,11 +813,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag UserVO user = _userDao.getUser(id); if (user == null) { - throw new InvalidParameterValueException("unable to find user by id"); + throw new InvalidParameterValueException("unable to find user by id", null); } if ((apiKey == null && secretKey != null) || (apiKey != null && secretKey == null)) { - throw new InvalidParameterValueException("Please provide an userApiKey/userSecretKey pair"); + throw new InvalidParameterValueException("Please provide an userApiKey/userSecretKey pair", null); } // If the account is an admin type, return an error. We do not allow this @@ -819,7 +825,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // don't allow updating project account if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("unable to find user by id"); + throw new InvalidParameterValueException("unable to find user by id", null); } if (account != null && (account.getId() == Account.ACCOUNT_ID_SYSTEM)) { @@ -830,37 +836,39 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (firstName != null) { if (firstName.isEmpty()) { - throw new InvalidParameterValueException("Firstname is empty"); + throw new InvalidParameterValueException("Firstname is empty", null); } - + user.setFirstname(firstName); } if (lastName != null) { if (lastName.isEmpty()) { - throw new InvalidParameterValueException("Lastname is empty"); + throw new InvalidParameterValueException("Lastname is empty", null); } - + user.setLastname(lastName); } if (userName != null) { if (userName.isEmpty()) { - throw new InvalidParameterValueException("Username is empty"); + throw new InvalidParameterValueException("Username is empty", null); } - + // don't allow to have same user names in the same domain List duplicatedUsers = _userDao.findUsersByName(userName); for (UserVO duplicatedUser : duplicatedUsers) { if (duplicatedUser.getId() != user.getId()) { Account duplicatedUserAccount = _accountDao.findById(duplicatedUser.getAccountId()); if (duplicatedUserAccount.getDomainId() == account.getDomainId()) { - throw new InvalidParameterValueException("User with name " + userName + " already exists in domain " + duplicatedUserAccount.getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", duplicatedUserAccount.getDomainId(), "domainId")); + throw new InvalidParameterValueException("User with name " + userName + " already exists in domain with specified id", idList); } } } user.setUsername(userName); } - + if (password != null) { user.setPassword(password); } @@ -888,7 +896,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (apiKeyOwner != null) { User usr = apiKeyOwner.first(); if (usr.getId() != id) { - throw new InvalidParameterValueException("The api key:" + apiKey + " exists in the system for user id:" + id + " ,please provide a unique key"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(usr, id, "userId")); + throw new InvalidParameterValueException("The api key:" + apiKey + " exists in the system for user with specified id, please provide a unique key", idList); } else { // allow the updation to take place } @@ -911,19 +921,21 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Check if user exists in the system User user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + throw new InvalidParameterValueException("Unable to find active user by id ", null); } Account account = _accountDao.findById(user.getAccountId()); // don't allow disabling user belonging to project's account if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + throw new InvalidParameterValueException("Unable to find active user by id", null); } // If the user is a System user, return an error if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("User id : " + userId + " is a system user, disabling is not allowed"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(user, userId, "userId")); + throw new InvalidParameterValueException("User with specified id is a system user, disabling is not allowed", idList); } checkAccess(caller, null, true, account); @@ -947,18 +959,20 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Check if user exists in the system User user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + throw new InvalidParameterValueException("Unable to find active user by id", null); } Account account = _accountDao.findById(user.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + throw new InvalidParameterValueException("Unable to find active user by id", null); } // If the user is a System user, return an error if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("User id : " + userId + " is a system user, enabling is not allowed"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(user, userId, "userId")); + throw new InvalidParameterValueException("User with specified id is a system user, enabling is not allowed", idList); } checkAccess(caller, null, true, account); @@ -988,14 +1002,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Check if user with id exists in the system User user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { - throw new InvalidParameterValueException("Unable to find user by id"); + throw new InvalidParameterValueException("Unable to find user by id", null); } Account account = _accountDao.findById(user.getAccountId()); // don't allow to lock user of the account of type Project if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find user by id"); + throw new InvalidParameterValueException("Unable to find user by id", null); } // If the user is a System user, return an error. We do not allow this @@ -1060,7 +1074,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // don't allow removing Project account if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("The specified account does not exist in the system"); + throw new InvalidParameterValueException("The specified account does not exist in the system", null); } checkAccess(caller, null, true, account); @@ -1072,12 +1086,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Account that manages project(s) can't be removed List managedProjectIds = _projectAccountDao.listAdministratedProjectIds(accountId); if (!managedProjectIds.isEmpty()) { - StringBuilder projectIds = new StringBuilder(); + List idList = new ArrayList(); + idList.add(new IdentityProxy(account, accountId, "accountId")); for (Long projectId : managedProjectIds) { - projectIds.append(projectId + ", "); + idList.add(new IdentityProxy("projects", projectId, "projectId")); } - - throw new InvalidParameterValueException("The account id=" + accountId + " manages project(s) with ids " + projectIds + "and can't be removed"); + throw new InvalidParameterValueException("The account with specified id manages project(s) with specified ids and can't be removed", idList); } return deleteAccount(account, callerUserId, caller); @@ -1095,12 +1109,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain with specified id", idList); } // Don't allow to modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Can not modify system account"); + throw new InvalidParameterValueException("Can not modify system account", null); } // Check if user performing the action is allowed to modify this account @@ -1128,14 +1144,16 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain with specified id", idList); } checkAccess(caller, null, true, account); // don't allow modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("can not lock system account"); + throw new InvalidParameterValueException("can not lock system account", null); } if (lockAccount(account.getId())) { @@ -1158,7 +1176,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain with specified id", idList); } checkAccess(caller, null, true, account); @@ -1191,34 +1211,34 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Check if account exists if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { s_logger.error("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); - throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain with specified id", idList); } // Don't allow to modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Can not modify system account"); + throw new InvalidParameterValueException("Can not modify system account", null); } // Check if user performing the action is allowed to modify this account checkAccess(UserContext.current().getCaller(), _domainMgr.getDomain(account.getDomainId())); // check if the given account name is unique in this domain for updating - Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId); - if (duplicateAcccount != null && duplicateAcccount.getId() != account.getId()) {// allow - // same - // account - // to - // update - // itself - throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:" - + duplicateAcccount.getId()); + Account duplicateAccount = _accountDao.findActiveAccount(newAccountName, domainId); + if (duplicateAccount != null && duplicateAccount.getId() != account.getId()) { + // allow same account to update itself + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + idList.add(new IdentityProxy(duplicateAccount, duplicateAccount.getId(), "accountId")); + throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in domain with specified id, with existing account with specified id", idList); } if (networkDomain != null && !networkDomain.isEmpty()) { 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); } } @@ -1259,18 +1279,20 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag UserVO user = _userDao.findById(id); if (user == null) { - throw new InvalidParameterValueException("The specified user doesn't exist in the system"); + throw new InvalidParameterValueException("The specified user doesn't exist in the system", null); } Account account = _accountDao.findById(user.getAccountId()); // don't allow to delete the user from the account of type Project if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("The specified user doesn't exist in the system"); + throw new InvalidParameterValueException("The specified user doesn't exist in the system", null); } if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Account id : " + user.getAccountId() + " is a system account, delete for user associated with this account is not allowed"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(account, user.getAccountId(), "accountId")); + throw new InvalidParameterValueException("Account with specified id is a system account, delete for user associated with this account is not allowed", idList); } checkAccess(UserContext.current().getCaller(), null, true, account); @@ -1377,18 +1399,18 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public Account finalizeOwner(Account caller, String accountName, Long domainId, Long projectId) { // don't default the owner to the system account if (caller.getId() == Account.ACCOUNT_ID_SYSTEM && ((accountName == null || domainId == null) && projectId == null)) { - throw new InvalidParameterValueException("Account and domainId are needed for resource creation"); + throw new InvalidParameterValueException("Account and domainId are needed for resource creation", null); } // projectId and account/domainId can't be specified together if ((accountName != null && domainId != null) && projectId != null) { - throw new InvalidParameterValueException("ProjectId and account/domainId can't be specified together"); + throw new InvalidParameterValueException("ProjectId and account/domainId can't be specified together", null); } if (projectId != null) { Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id=" + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { @@ -1401,12 +1423,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (isAdmin(caller.getType()) && accountName != null && domainId != null) { Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find the domain by id=" + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } Account owner = _accountDao.findActiveAccount(accountName, domainId); if (owner == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specified id", idList); } checkAccess(caller, domain); @@ -1419,7 +1443,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } else { if ((accountName == null && domainId != null) || (accountName != null && domainId == null)) { - throw new InvalidParameterValueException("AccountName and domainId must be specified together"); + throw new InvalidParameterValueException("AccountName and domainId must be specified together", null); } // regular user can't create/list resources for other people return caller; @@ -1429,7 +1453,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public Account getActiveAccountByName(String accountName, Long domainId) { if (accountName == null || domainId == null) { - throw new InvalidParameterValueException("Both accountName and domainId are required for finding active account in the system"); + throw new InvalidParameterValueException("Both accountName and domainId are required for finding active account in the system", null); } else { return _accountDao.findActiveAccount(accountName, domainId); } @@ -1438,7 +1462,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public Account getActiveAccountById(Long accountId) { if (accountId == null) { - throw new InvalidParameterValueException("AccountId is required by account search"); + throw new InvalidParameterValueException("AccountId is required by account search", null); } else { return _accountDao.findById(accountId); } @@ -1447,7 +1471,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public Account getAccount(Long accountId) { if (accountId == null) { - throw new InvalidParameterValueException("AccountId is required by account search"); + throw new InvalidParameterValueException("AccountId is required by account search", null); } else { return _accountDao.findByIdIncludingRemoved(accountId); } @@ -1469,11 +1493,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (isAdmin(caller.getType())) { if (domainId == null && accountName != null) { - throw new InvalidParameterValueException("accountName and domainId might be specified together"); + throw new InvalidParameterValueException("accountName and domainId might be specified together", null); } else if (domainId != null) { Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find the domain by id=" + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } checkAccess(caller, domain); @@ -1481,7 +1505,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (accountName != null) { Account owner = getActiveAccountByName(accountName, domainId); if (owner == null) { - throw new InvalidParameterValueException("Unable to find account with name " + accountName + " in domain id=" + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account with name " + accountName + " in domain with specified id", idList); } permittedAccounts.add(owner.getId()); @@ -1508,10 +1534,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag permittedAccounts.clear(); Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id ", null); } if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { - throw new InvalidParameterValueException("Account " + caller + " can't access project id=" + projectId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Account " + caller + " can't access project with specified id", idList); } permittedAccounts.add(project.getProjectAccountId()); } @@ -1538,7 +1566,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Validate domain Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account"); + throw new InvalidParameterValueException("Domain does not exist; unable to create account", null); } if (domain.getState().equals(Domain.State.Inactive)) { @@ -1546,31 +1574,33 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if ((domainId != DomainVO.ROOT_DOMAIN) && (accountType == Account.ACCOUNT_TYPE_ADMIN)) { - throw new InvalidParameterValueException("Invalid account type " + accountType + " given for an account in domain " + domainId + "; unable to create user."); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Invalid account type " + accountType + " given for an account in domain with specified id; unable to create user.", idList); } // Validate account/user/domain settings if (_accountDao.findActiveAccount(accountName, domainId) != null) { - throw new InvalidParameterValueException("The specified account: " + accountName + " already exists"); + throw new InvalidParameterValueException("The specified account: " + accountName + " already exists", null); } if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } // Verify account type if ((accountType < Account.ACCOUNT_TYPE_NORMAL) || (accountType > Account.ACCOUNT_TYPE_PROJECT)) { - throw new InvalidParameterValueException("Invalid account type " + accountType + " given; unable to create user"); + throw new InvalidParameterValueException("Invalid account type " + accountType + " given; unable to create user", null); } if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { List dc = _dcDao.findZonesByDomainId(domainId); if (dc.isEmpty()) { - throw new InvalidParameterValueException("The account cannot be created as domain " + domain.getName() + " is not associated with any private Zone"); + throw new InvalidParameterValueException("The account cannot be created as domain " + domain.getName() + " is not associated with any private Zone", null); } } @@ -1808,8 +1838,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public String[] createApiKeyAndSecretKey(RegisterCmd cmd) { Long userId = cmd.getId(); - if (getUserIncludingRemoved(userId) == null) { - throw new InvalidParameterValueException("unable to find user for id : " + userId); + if (getUserIncludingRemoved(userId) == null) { + throw new InvalidParameterValueException("unable to find user by id", null); } // generate both an api key and a secret key, update the user table with the keys, return the keys to the user @@ -1891,7 +1921,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (accountId != null) { Account account = _accountDao.findById(accountId); if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Unable to find account by id " + accountId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(account, accountId, "accountId")); + throw new InvalidParameterValueException("Unable to find account with specified id", idList); } checkAccess(caller, null, true, account); @@ -1900,7 +1932,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId != null) { Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Domain with specified id doesn't exist", idList); } checkAccess(caller, domain); @@ -1908,7 +1942,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (accountName != null) { Account account = _accountDao.findActiveAccount(accountName, domainId); if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain with specified id", idList); } checkAccess(caller, null, true, account); } @@ -2005,7 +2041,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId != null) { Domain domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } checkAccess(caller, domain); @@ -2169,7 +2205,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId != null) { Domain domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id " + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } // check permissions checkAccess(caller, domain); @@ -2177,7 +2213,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (accountName != 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 userAccount = null; @@ -2190,7 +2226,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (userAccount != null) { permittedAccounts.add(userAccount.getId()); } else { - throw new InvalidParameterValueException("could not find account " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("could not find account " + accountName + " in domain with specified id", idList); } } @@ -2206,7 +2244,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } else { Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { throw new PermissionDeniedException("Account " + caller + " can't access project id=" + projectId); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 1ea462c72d2..962d3844a13 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -196,6 +196,7 @@ import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.SSHKeyPairDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; @@ -376,17 +377,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Do parameters input validation if (userVm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + cmd.getId()); + throw new InvalidParameterValueException("unable to find a virtual machine by id", null); } VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId()); if (template == null || !template.getEnablePassword()) { - throw new InvalidParameterValueException("Fail to reset password for the virtual machine, the template is not password enabled"); + throw new InvalidParameterValueException("Fail to reset password for the virtual machine, the template is not password enabled", null); } if (userVm.getState() == State.Error || userVm.getState() == State.Expunging) { s_logger.error("vm is not in the right state: " + vmId); - throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(userVm, vmId, "vmId")); + throw new InvalidParameterValueException("Vm with specified id is not in the right state", idList); } _accountMgr.checkAccess(caller, null, true, userVm); @@ -454,7 +457,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.debug("Vm " + vmInstance + " is stopped, not rebooting it as a part of password reset"); return true; } - + if (rebootVirtualMachine(userId, vmId) == null) { s_logger.warn("Failed to reboot the vm " + vmInstance); return false; @@ -514,68 +517,68 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VolumeVO volume = _volsDao.findById(volumeId); // Check that the volume is a data volume if (volume == null || volume.getVolumeType() != Volume.Type.DATADISK) { - throw new InvalidParameterValueException("Please specify a valid data volume."); + throw new InvalidParameterValueException("Please specify a valid data volume.", null); } // 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 the volume is not destroyed if (volume.getState() == Volume.State.Destroy) { - throw new InvalidParameterValueException("Please specify a volume that is not destroyed."); + throw new InvalidParameterValueException("Please specify a volume that is not destroyed.", null); } // Check that the virtual machine ID is valid and it's a user vm UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getType() != VirtualMachine.Type.User) { - throw new InvalidParameterValueException("Please specify a valid User VM."); + throw new InvalidParameterValueException("Please specify a valid User VM.", null); } // Check that the VM is in the correct state if (vm.getState() != State.Running && vm.getState() != State.Stopped) { - throw new InvalidParameterValueException("Please specify a VM that is either running or stopped."); + throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.", null); } // Check that the device ID is valid if (deviceId != null) { if (deviceId.longValue() == 0) { - throw new InvalidParameterValueException("deviceId can't be 0, which is used by Root device"); + throw new InvalidParameterValueException("deviceId can't be 0, which is used by Root device", null); } } // Check that the VM has less than 6 data volumes attached List existingDataVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK); if (existingDataVolumes.size() >= 6) { - throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (6). Please specify another VM."); + throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (6). Please specify another VM.", null); } // Check that the VM and the volume are in the same zone if (vm.getDataCenterIdToDeployIn() != volume.getDataCenterId()) { - throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume."); + throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume.", null); } //permission check _accountMgr.checkAccess(caller, null, true, volume, vm); - + //Check if volume is stored on secondary Storage. boolean isVolumeOnSec = false; VolumeHostVO volHostVO = _volumeHostDao.findByVolumeId(volume.getId()); if (volHostVO != null){ - isVolumeOnSec = true; - if( !(volHostVO.getDownloadState() == Status.DOWNLOADED) ){ - throw new InvalidParameterValueException("Volume is not uploaded yet. Please try this operation once the volume is uploaded"); - } + isVolumeOnSec = true; + if( !(volHostVO.getDownloadState() == Status.DOWNLOADED) ){ + throw new InvalidParameterValueException("Volume is not uploaded yet. Please try this operation once the volume is uploaded", null); + } } //If the volume is Ready, check that the volume is stored on shared storage if (!(Volume.State.Allocated.equals(volume.getState()) || Volume.State.UploadOp.equals(volume.getState())) && !_storageMgr.volumeOnSharedStoragePool(volume)) { - throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool."); + throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool.", null); } if ( !(Volume.State.Allocated.equals(volume.getState()) || Volume.State.Ready.equals(volume.getState()) || Volume.State.UploadOp.equals(volume.getState())) ) { - throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state"); + throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state", null); } VolumeVO rootVolumeOfVm = null; @@ -589,9 +592,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager HypervisorType rootDiskHyperType = vm.getHypervisorType(); HypervisorType dataDiskHyperType = _volsDao.getHypervisorType(volume.getId()); if (dataDiskHyperType != HypervisorType.None && rootDiskHyperType != dataDiskHyperType) { - throw new InvalidParameterValueException("Can't attach a volume created by: " + dataDiskHyperType + " to a " + rootDiskHyperType + " vm"); + throw new InvalidParameterValueException("Can't attach a volume created by: " + dataDiskHyperType + " to a " + rootDiskHyperType + " vm", null); } - + //allocate deviceId List vols = _volsDao.findByInstance(vmId); if (deviceId != null) { @@ -615,12 +618,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } deviceId = Long.parseLong(devIds.iterator().next()); } - + boolean createVolumeOnBackend = true; if (rootVolumeOfVm.getState() == Volume.State.Allocated) { createVolumeOnBackend = false; if(isVolumeOnSec){ - throw new CloudRuntimeException("Cant attach uploaded volume to the vm which is not created. Please start it and then retry"); + throw new CloudRuntimeException("Cant attach uploaded volume to the vm which is not created. Please start it and then retry"); } } @@ -635,34 +638,34 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager ServiceOfferingVO svo = _serviceOfferingDao.findById(vm.getServiceOfferingId()); DiskOfferingVO diskVO = _diskOfferingDao.findById(volume.getDiskOfferingId()); Long clusterId = (rootDiskPool == null ? null : rootDiskPool.getClusterId()); - + if (!isVolumeOnSec){ - volume = _storageMgr.createVolume(volume, vm, rootDiskTmplt, dcVO, pod, clusterId, svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); + volume = _storageMgr.createVolume(volume, vm, rootDiskTmplt, dcVO, pod, clusterId, svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); }else { - try { - // Format of data disk should be the same as root disk - if( ! volHostVO.getFormat().getFileExtension().equals(_storageMgr.getSupportedImageFormatForCluster(rootDiskPool.getClusterId())) ){ - throw new InvalidParameterValueException("Failed to attach volume to VM since volumes format " +volHostVO.getFormat().getFileExtension() + " is not compatible with the vm hypervisor type" ); - } - - // Check that there is some shared storage. + try { + // Format of data disk should be the same as root disk + if( ! volHostVO.getFormat().getFileExtension().equals(_storageMgr.getSupportedImageFormatForCluster(rootDiskPool.getClusterId())) ){ + throw new InvalidParameterValueException("Failed to attach volume to VM since volumes format " +volHostVO.getFormat().getFileExtension() + " is not compatible with the vm hypervisor type", null); + } + + // Check that there is some shared storage. StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); List sharedVMPools = _storagePoolDao.findPoolsByTags(vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId(), null, true); if (sharedVMPools.size() == 0) { throw new CloudRuntimeException("Cannot attach volume since there are no shared storage pools in the VM's cluster to copy the uploaded volume to."); } - - volume = _storageMgr.copyVolumeFromSecToPrimary(volume, vm, rootDiskTmplt, dcVO, pod, rootDiskPool.getClusterId(), svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); - } catch (NoTransitionException e) { - throw new CloudRuntimeException("Unable to transition the volume ",e); - } + + volume = _storageMgr.copyVolumeFromSecToPrimary(volume, vm, rootDiskTmplt, dcVO, pod, rootDiskPool.getClusterId(), svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); + } catch (NoTransitionException e) { + throw new CloudRuntimeException("Unable to transition the volume ",e); + } } if (volume == null) { throw new CloudRuntimeException("Failed to create volume when attaching it to VM: " + vm.getHostName()); } } - + StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); DiskOfferingVO volumeDiskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); String[] volumeTags = volumeDiskOffering.getTagsArray(); @@ -695,7 +698,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } } - + if (moveVolumeNeeded) { // Move the volume to a storage pool in the VM's zone, pod, or cluster try { @@ -767,7 +770,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Account caller = UserContext.current().getCaller(); if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null) || (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null)) || (cmmd.getId() == null && (cmmd.getDeviceId() == null || cmmd.getVirtualMachineId() == null))) { - throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)"); + throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)", null); } Long volumeId = cmmd.getId(); @@ -789,7 +792,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Check that the volume ID is valid if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId); + throw new InvalidParameterValueException("Unable to find volume by ID", null); } // Permissions check @@ -797,23 +800,23 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Check that the volume is a data volume if (volume.getVolumeType() != Volume.Type.DATADISK) { - throw new InvalidParameterValueException("Please specify a data volume."); + throw new InvalidParameterValueException("Please specify a data volume.", null); } - + // Check that the volume is currently attached to a VM if (vmId == null) { - throw new InvalidParameterValueException("The specified volume is not attached to a VM."); + throw new InvalidParameterValueException("The specified volume is not attached to a VM.", null); } // Check that the volume is stored on shared storage if (volume.getState() != Volume.State.Allocated && !_storageMgr.volumeOnSharedStoragePool(volume)) { - throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool."); + throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool.", null); } // Check that the VM is in the correct state UserVmVO vm = _vmDao.findById(vmId); if (vm.getState() != State.Running && vm.getState() != State.Stopped && vm.getState() != State.Destroyed) { - throw new InvalidParameterValueException("Please specify a VM that is either running or stopped."); + throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.", null); } AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); @@ -944,14 +947,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters UserVmVO vmInstance = _vmDao.findById(vmId); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find virtual machine by id ", null); } _accountMgr.checkAccess(caller, null, true, vmInstance); // Check that the specified service offering ID is valid _itMgr.checkIfCanUpgrade(vmInstance, svcOffId); - + _itMgr.upgradeVmDb(vmId, svcOffId); return _vmDao.findById(vmInstance.getId()); @@ -1004,7 +1007,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserVmVO vm = _vmDao.findById(vmId.longValue()); if (vm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find virtual machine by id ", null); } //check permissions @@ -1014,14 +1017,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is removed: " + vmId); } - throw new InvalidParameterValueException("Unable to find vm by id " + vmId); + throw new InvalidParameterValueException("unable to find virtual machine by id ", null); } if (vm.getState() != State.Destroyed) { if (s_logger.isDebugEnabled()) { s_logger.debug("vm is not in the right state: " + vmId); } - throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("Vm with specified id is not in the right state", idList); } if (s_logger.isDebugEnabled()) { @@ -1047,10 +1052,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager try { if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) { s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId); - throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("Unable to recover the vm with specified id because it is not in the correct state", idList); } } catch (NoTransitionException e) { - throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("Unable to recover the vm with specified id because it is not in the correct state", idList); } // Recover the VM's disks @@ -1163,7 +1172,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager ctx.setAccountId(vm.getAccountId()); try { - //expunge the vm + //expunge the vm if (!_itMgr.advanceExpunge(vm, _accountMgr.getSystemUser(), caller)) { s_logger.info("Did not expunge " + vm); return false; @@ -1267,7 +1276,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager String name = cmd.getTemplateName(); if ((name == null) || (name.length() > 32)) { - throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters"); + throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters", null); } if(cmd.getTemplateTag() != null){ @@ -1296,10 +1305,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Long volumeId = cmd.getVolumeId(); Long snapshotId = cmd.getSnapshotId(); if ((volumeId == null) && (snapshotId == null)) { - throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified."); + throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified.", null); } if ((volumeId != null) && (snapshotId != null)) { - throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")"); + throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")", null); } HypervisorType hyperType; @@ -1308,7 +1317,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (volumeId != null) { // create template from volume volume = _volsDao.findById(volumeId); if (volume == null) { - throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId); + throw new InvalidParameterValueException("Failed to create private template record, unable to find volume by id", null); } //check permissions _accountMgr.checkAccess(caller, null, true, volume); @@ -1326,9 +1335,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } else { // create template from snapshot SnapshotVO snapshot = _snapshotDao.findById(snapshotId); if (snapshot == null) { - throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot " + snapshotId); + throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot by id", null); } - + volume = _volsDao.findById(snapshot.getVolumeId()); VolumeVO snapshotVolume = _volsDao.findByIdIncludingRemoved(snapshot.getVolumeId()); @@ -1336,16 +1345,18 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _accountMgr.checkAccess(caller, null, true, snapshot); if (snapshot.getStatus() != Snapshot.Status.BackedUp) { - throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for template creation"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(snapshot, snapshotId, "snapshotId")); + throw new InvalidParameterValueException("Snapshot with specified id is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for template creation", idList); } -/* + /* // bug #11428. Operation not supported if vmware and snapshots parent volume = ROOT if(snapshot.getHypervisorType() == HypervisorType.VMware && snapshotVolume.getVolumeType() == Type.DATADISK){ throw new UnsupportedServiceException("operation not supported, snapshot with id " + snapshotId + " is created from Data Disk"); } -*/ - + */ + hyperType = snapshot.getHypervisorType(); } @@ -1357,7 +1368,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Long guestOSId = cmd.getOsTypeId(); GuestOSVO guestOS = _guestOSDao.findById(guestOSId); if (guestOS == null) { - throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist."); + throw new InvalidParameterValueException("Couldn't find GuestOS by id", null); } String uniqueName = Long.valueOf((userId == null) ? 1 : userId).toString() + UUID.nameUUIDFromBytes(name.getBytes()).toString(); @@ -1393,19 +1404,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VMTemplateVO template = _templateDao.persist(privateTemplate); // Increment the number of templates if (template != null) { - if(cmd.getDetails() != null) { - _templateDetailsDao.persist(template.getId(), cmd.getDetails()); - } - + if(cmd.getDetails() != null) { + _templateDetailsDao.persist(template.getId(), cmd.getDetails()); + } + _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template); } if (template != null){ - return template; + return template; }else { - throw new CloudRuntimeException("Failed to create a template"); + throw new CloudRuntimeException("Failed to create a template"); } - + } @Override @@ -1605,11 +1616,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager txn.commit(); } } - + if (privateTemplate != null){ - return privateTemplate; + return privateTemplate; }else { - throw new CloudRuntimeException("Failed to create a template"); + throw new CloudRuntimeException("Failed to create a template"); } } @@ -1631,10 +1642,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // used for vm transitioning to error state private void updateVmStateForFailedVmCreation(Long vmId) { - + UserVmVO vm = _vmDao.findById(vmId); - - + + if (vm != null) { if (vm.getState().equals(State.Stopped)) { s_logger.debug("Destroying vm " + vm + " as it failed to create"); @@ -1721,12 +1732,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager vmInstance = _vmDao.findById(id.longValue()); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find virtual machine with id " + id); + throw new InvalidParameterValueException("unable to find virtual machine by id ", null); } ServiceOffering offering = _serviceOfferingDao.findById(vmInstance.getServiceOfferingId()); if (!offering.getOfferHA() && ha != null && ha) { - throw new InvalidParameterValueException("Can't enable ha for the vm as it's created from the Service offering having HA disabled"); + throw new InvalidParameterValueException("Can't enable ha for the vm as it's created from the Service offering having HA disabled", null); } _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, vmInstance); @@ -1746,7 +1757,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (vm.getState() == State.Error || vm.getState() == State.Expunging) { s_logger.error("vm is not in the right state: " + id); - throw new InvalidParameterValueException("Vm with id " + id + " is not in the right state"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, id, "vmId")); + throw new InvalidParameterValueException("Vm with specified id is not in the right state", idList); } if (userData != null) { @@ -1801,7 +1814,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters UserVmVO vmInstance = _vmDao.findById(vmId.longValue()); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find a virtual machine by id ", null); } _accountMgr.checkAccess(caller, null, true, vmInstance); @@ -1831,7 +1844,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean isNameInUse = _vmGroupDao.isNameInUse(accountId, groupName); if (isNameInUse) { - throw new InvalidParameterValueException("Unable to create vm group, a group with name " + groupName + " already exisits for account " + accountId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("account", accountId, "accountId")); + throw new InvalidParameterValueException("Unable to create vm group, a group with name " + groupName + " already exisits for account with specified id", idList); } return createVmGroup(groupName, accountId); @@ -1870,7 +1885,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters InstanceGroupVO group = _vmGroupDao.findById(groupId); if ((group == null) || (group.getRemoved() != null)) { - throw new InvalidParameterValueException("unable to find a vm group with id " + groupId); + throw new InvalidParameterValueException("unable to find vm group by id", null); } _accountMgr.checkAccess(caller, null, true, group); @@ -2005,7 +2020,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Network defaultNetwork = _networkMgr.getExclusiveGuestNetwork(zone.getId()); if (defaultNetwork == null) { - throw new InvalidParameterValueException("Unable to find a default network to start a vm"); + throw new InvalidParameterValueException("Unable to find a default network to start a vm", null); } else { networkList.add(_networkDao.findById(defaultNetwork.getId())); } @@ -2013,7 +2028,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); if (securityGroupIdList != null && isVmWare) { - throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor"); + throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor", null); } else if (!isVmWare && _networkMgr.isSecurityGroupSupportedInNetwork(defaultNetwork) && _networkMgr.canAddDefaultSecurityGroup()) { //add the default securityGroup only if no security group is specified if(securityGroupIdList == null || securityGroupIdList.isEmpty()){ @@ -2064,11 +2079,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } else if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) { if (isVmWare) { - throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor"); + throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor", null); } // Only one network can be specified, and it should be security group enabled if (networkIdList.size() > 1) { - throw new InvalidParameterValueException("Only support one network per VM if security group enabled"); + throw new InvalidParameterValueException("Only support one network per VM if security group enabled", null); } NetworkVO network = _networkDao.findById(networkIdList.get(0).longValue()); @@ -2096,11 +2111,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean isSecurityGroupEnabled = _networkMgr.isSecurityGroupSupportedInNetwork(network); if (isSecurityGroupEnabled && networkIdList.size() > 1) { - throw new InvalidParameterValueException("Can't create a vm with multiple networks one of which is Security Group enabled"); + throw new InvalidParameterValueException("Can't create a vm with multiple networks one of which is Security Group enabled", null); } if (network.getTrafficType() != TrafficType.Guest || network.getGuestType() != Network.GuestType.Shared || (network.getGuestType() == Network.GuestType.Shared && !isSecurityGroupEnabled)) { - throw new InvalidParameterValueException("Can specify only Direct Guest Account specific networks when deploy vm in Security Group enabled zone"); + throw new InvalidParameterValueException("Can specify only Direct Guest Account specific networks when deploy vm in Security Group enabled zone", null); } // Perform account permission check @@ -2118,13 +2133,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // if network is security group enabled, and no security group is specified, then add the default security group automatically if (isSecurityGroupEnabledNetworkUsed && !isVmWare && _networkMgr.canAddDefaultSecurityGroup()) { - - //add the default securityGroup only if no security group is specified + + //add the default securityGroup only if no security group is specified if(securityGroupIdList == null || securityGroupIdList.isEmpty()){ if (securityGroupIdList == null) { securityGroupIdList = new ArrayList(); } - + SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(owner.getId()); if (defaultGroup != null) { securityGroupIdList.add(defaultGroup.getId()); @@ -2153,7 +2168,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, null, true, owner); - + if (networkIdList == null || networkIdList.isEmpty()) { NetworkVO defaultNetwork = null; @@ -2165,9 +2180,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { - throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation"); + throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation", null); } - + PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { // get Virtual networks @@ -2175,18 +2190,18 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (virtualNetworks.isEmpty()) { s_logger.debug("Creating network for account " + owner + " from the network offering id=" + - requiredOfferings.get(0).getId() + " as a part of deployVM process"); + requiredOfferings.get(0).getId() + " as a part of deployVM process"); Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, zone.getId(), ACLType.Account, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { - throw new InvalidParameterValueException("More than 1 default Isolated networks are found for account " + owner + "; please specify networkIds"); + throw new InvalidParameterValueException("More than 1 default Isolated networks are found for account " + owner + "; please specify networkIds", null); } else { defaultNetwork = virtualNetworks.get(0); } } else { - throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); + throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } networkList.add(defaultNetwork); @@ -2217,11 +2232,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Long diskSize, List networkList, List securityGroupIdList, String group, String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, Map requestedIps, String defaultNetworkIp, String keyboard) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { _accountMgr.checkAccess(caller, null, true, owner); - + if (owner.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner); } - + long accountId = owner.getId(); assert !(requestedIps != null && defaultNetworkIp != null) : "requestedIp list and defaultNetworkIp should never be specified together"; @@ -2248,12 +2263,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //verify security group ids if (securityGroupIdList != null) { for (Long securityGroupId : securityGroupIdList) { - SecurityGroup sg = _securityGroupDao.findById(securityGroupId); + SecurityGroup sg = _securityGroupDao.findById(securityGroupId); if (sg == null) { throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId); } else { - //verify permissions - _accountMgr.checkAccess(caller, null, true, owner, sg); + //verify permissions + _accountMgr.checkAccess(caller, null, true, owner, sg); } } } @@ -2295,13 +2310,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); if (diskOffering == null) { - throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId); + throw new InvalidParameterValueException("Unable to find disk offering by id", null); } Long size = null; if (diskOffering.getDiskSize() == 0) { size = diskSize; if (size == null) { - throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter."); + throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter.", null); } } rootDiskOffering.first(diskOffering); @@ -2311,13 +2326,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (diskOfferingId != null) { DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); if (diskOffering == null) { - throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId); + throw new InvalidParameterValueException("Unable to find disk offering by id", null); } Long size = null; if (diskOffering.getDiskSize() == 0) { size = diskSize; if (size == null) { - throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter."); + throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter.", null); } } dataDiskOfferings.add(new Pair(diskOffering, size)); @@ -2332,7 +2347,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (sshKeyPair != null && !sshKeyPair.equals("")) { SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair); if (pair == null) { - throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found."); + throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found.", null); } sshPublicKey = pair.getPublicKey(); @@ -2345,22 +2360,22 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (network.getDataCenterId() != zone.getId()) { throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId()); } - + String requestedIp = null; if (requestedIps != null && !requestedIps.isEmpty()) { - requestedIp = requestedIps.get(network.getId()); + requestedIp = requestedIps.get(network.getId()); } NicProfile profile = new NicProfile(requestedIp); - + if (defaultNetworkNumber == 0) { - defaultNetworkNumber++; - // if user requested specific ip for default network, add it - if (defaultNetworkIp != null) { - profile = new NicProfile(defaultNetworkIp); - } - - profile.setDefaultNic(true); + defaultNetworkNumber++; + // if user requested specific ip for default network, add it + if (defaultNetworkIp != null) { + profile = new NicProfile(defaultNetworkIp); + } + + profile.setDefaultNic(true); } networks.add(new Pair(network, profile)); @@ -2371,22 +2386,22 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } if (securityGroupIdList != null && !securityGroupIdList.isEmpty() && !securityGroupEnabled) { - throw new InvalidParameterValueException("Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network"); + throw new InvalidParameterValueException("Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network", null); } // Verify network information - network default network has to be set; and vm can't have more than one default network // This is a part of business logic because default network is required by Agent Manager in order to configure default // gateway for the vm if (defaultNetworkNumber == 0) { - throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm"); + throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm", null); } else if (defaultNetworkNumber > 1) { - throw new InvalidParameterValueException("Only 1 default network per vm is supported"); + throw new InvalidParameterValueException("Only 1 default network per vm is supported", null); } long id = _vmDao.getNextInSequence(Long.class, "id"); String instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance); - + String uuidName = UUID.randomUUID().toString(); if (hostName == null) { hostName = uuidName; @@ -2394,7 +2409,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // verify hostName (hostname doesn't have to be unique) if (!NetUtils.verifyDomainNameLabel(hostName, true)) { throw new InvalidParameterValueException("Invalid name. Vm name can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit"); + + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit", null); } } @@ -2409,7 +2424,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, template.getGuestOSId(), offering.getOfferHA(), offering.getLimitCpuUse(), owner.getDomainId(), owner.getId(), offering.getId(), userData, hostName); vm.setUuid(uuidName); - + if (sshPublicKey != null) { vm.setDetail("SSH.PublicKey", sshPublicKey); } @@ -2461,14 +2476,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager byte[] decodedUserData = null; if (userData != null) { if (userData.length() >= 2 * MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException("User data is too long"); + throw new InvalidParameterValueException("User data is too long", null); } decodedUserData = org.apache.commons.codec.binary.Base64.decodeBase64(userData.getBytes()); if (decodedUserData.length > MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException("User data is too long"); + throw new InvalidParameterValueException("User data is too long", null); } if (decodedUserData.length < 1) { - throw new InvalidParameterValueException("User data is too short"); + throw new InvalidParameterValueException("User data is too short", null); } } } @@ -2485,7 +2500,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long vmId = cmd.getEntityId(); Long hostId = cmd.getHostId(); UserVmVO vm = _vmDao.findById(vmId); - + Pair> vmParamPair = null; try { vmParamPair = startVirtualMachine(vmId, hostId, additonalParams); @@ -2493,7 +2508,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } finally { updateVmStateForFailedVmCreation(vm.getId()); } - + // Check that the password was passed in and is valid VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId()); if (template.getEnablePassword()) { @@ -2521,14 +2536,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Pair isoPathPair = _storageMgr.getAbsoluteIsoPath(template.getId(), vm.getDataCenterIdToDeployIn()); if (template.getTemplateType() == TemplateType.PERHOST) { - isoPath = template.getName(); + isoPath = template.getName(); } else { - if (isoPathPair == null) { - s_logger.warn("Couldn't get absolute iso path"); - return false; - } else { - isoPath = isoPathPair.first(); - } + if (isoPathPair == null) { + s_logger.warn("Couldn't get absolute iso path"); + return false; + } else { + isoPath = isoPathPair.first(); + } } if (template.isBootable()) { @@ -2556,7 +2571,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Override public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) { - UserVmVO userVm = profile.getVirtualMachine(); + UserVmVO userVm = profile.getVirtualMachine(); List nics = _nicDao.listByVmId(userVm.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); @@ -2636,7 +2651,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.info("Detected that ip changed in the answer, updated nic in the db with new ip " + returnedIp); } } - + //get system ip and create static nat rule for the vm try { _rulesMgr.getSystemIpAndEnableStaticNatForVm(profile.getVirtualMachine(), false); @@ -2644,8 +2659,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.warn("Failed to get system ip and enable static nat for the vm " + profile.getVirtualMachine() + " due to exception ", ex); return false; } - - return true; + + return true; } @Override @@ -2684,7 +2699,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find a virtual machine by id", null); } _accountMgr.checkAccess(caller, null, true, vm); @@ -2703,16 +2718,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Override public void finalizeStop(VirtualMachineProfile profile, StopAnswer answer) { - //release elastic IP here - IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(profile.getId()); - if (ip != null && ip.getSystem()) { - UserContext ctx = UserContext.current(); - try { - _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), ctx.getCallerUserId(), true); - } catch (Exception ex) { - s_logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", ex); - } - } + //release elastic IP here + IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(profile.getId()); + if (ip != null && ip.getSystem()) { + UserContext ctx = UserContext.current(); + try { + _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), ctx.getCallerUserId(), true); + } catch (Exception ex) { + s_logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", ex); + } + } } public String generateRandomPassword() { @@ -2729,14 +2744,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (callerAccount != null && callerAccount.getRemoved() != null) { throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed"); } - + UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find a virtual machine by id ", null); } _accountMgr.checkAccess(callerAccount, null, true, vm); - + Account owner = _accountDao.findById(vm.getAccountId()); if (owner == null) { @@ -2746,7 +2761,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (owner.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId()); } - + Host destinationHost = null; if(hostId != null){ Account account = UserContext.current().getCaller(); @@ -2773,13 +2788,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _securityGroupMgr.addInstanceToGroups(vmId, groupList); } } - + DataCenterDeployment plan = null; if (destinationHost != null) { s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM"); plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null); } - + //Set parameters Map params = null; VMTemplateVO template = null; @@ -2794,7 +2809,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } if (!validPassword(password)) { - throw new InvalidParameterValueException("A valid password for this virtual machine was not provided."); + throw new InvalidParameterValueException("A valid password for this virtual machine was not provided.", null); } // Check if an SSH key pair was selected for the instance and if so use it to encrypt & save the vm password @@ -2808,7 +2823,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager vm.setDetail("Encrypted.Password", encryptedPasswd); _vmDao.saveDetails(vm); } - + params = new HashMap(); if (additionalParams != null) { params.putAll(additionalParams); @@ -2817,17 +2832,17 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } vm = _itMgr.start(vm, params, callerUser, callerAccount, plan); - + Pair> vmParamPair = new Pair(vm, params); if (vm != null && vm.isUpdateParameters()) { - // this value is not being sent to the backend; need only for api display purposes + // this value is not being sent to the backend; need only for api display purposes if (template.getEnablePassword()) { vm.setPassword((String)vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword)); vm.setUpdateParameters(false); _vmDao.update(vm.getId(), vm); } } - + return vmParamPair; } @@ -2839,8 +2854,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getRemoved() != null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId"); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId", null); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -2858,8 +2873,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager try { status = _itMgr.destroy(vm, userCaller, caller); } catch (OperationTimedoutException e) { - CloudRuntimeException ex = new CloudRuntimeException("Unable to destroy with specified vmId", e); - ex.addProxyObject(vm, vmId, "vmId"); + CloudRuntimeException ex = new CloudRuntimeException("Unable to destroy with specified vmId", e); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -2879,22 +2894,22 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return _vmDao.findById(vmId); } else { - CloudRuntimeException ex = new CloudRuntimeException("Failed to destroy vm with specified vmId"); - ex.addProxyObject(vm, vmId, "vmId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to destroy vm with specified vmId"); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } } @Override public List searchForUserVMs(ListVMsCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - String hypervisor = cmd.getHypervisor(); - boolean listAll = cmd.listAll(); - Long id = cmd.getId(); - Map tags = cmd.getTags(); + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + String hypervisor = cmd.getHypervisor(); + boolean listAll = cmd.listAll(); + Long id = cmd.getId(); + Map tags = cmd.getTags(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); @@ -2917,7 +2932,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (HypervisorType.getType(hypervisor) != HypervisorType.None) { c.addCriteria(Criteria.HYPERVISOR, hypervisor); } else if (hypervisor != null) { - throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor); + throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor, null); } // ignore these search requests if it's not an admin @@ -2942,7 +2957,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager SearchBuilder sb = _vmDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + Object id = c.getCriteria(Criteria.ID); Object name = c.getCriteria(Criteria.NAME); Object state = c.getCriteria(Criteria.STATE); @@ -2980,7 +2995,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager groupSearch.and("groupId", groupSearch.entity().getGroupId(), SearchCriteria.Op.EQ); sb.join("groupSearch", groupSearch, sb.entity().getId(), groupSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } - + if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); for (int count=0; count < tags.size(); count++) { @@ -3013,7 +3028,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // populate the search criteria with the values passed in SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.UserVm.toString()); @@ -3023,7 +3038,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager count++; } } - + if (groupId != null && (Long) groupId == -1) { sc.setJoinParameters("vmSearch", "instanceId", (Object) null); } else if (groupId != null) { @@ -3113,8 +3128,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager public HypervisorType getHypervisorTypeOfUserVM(long vmId) { UserVmVO userVm = _vmDao.findById(vmId); if (userVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); - ex.addProxyObject(userVm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); + ex.addProxyObject(userVm, vmId, "vmId"); throw ex; } @@ -3146,22 +3161,22 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { - throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId); + throw new InvalidParameterValueException("Unable to find the VM by id", null); } if (vm.getState() != State.Stopped) { - InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to migrate the vm having the specified id"); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to migrate the vm having the specified id"); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } if (vm.getType() != VirtualMachine.Type.User) { throw new InvalidParameterValueException("can only do storage migration on user vm"); } - + List vols = _volsDao.findByInstance(vm.getId()); if (vols.size() > 1) { - throw new InvalidParameterValueException("Data disks attached to the vm, can not migrate. Need to dettach data disks at first"); + throw new InvalidParameterValueException("Data disks attached to the vm, can not migrate. Need to dettach data disks at first"); } HypervisorType destHypervisorType = _clusterDao.findById(destPool.getClusterId()).getHypervisorType(); @@ -3212,13 +3227,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate"); } - + //check if migrating to same host long srcHostId = vm.getHostId(); if(destinationHost.getId() == srcHostId){ throw new InvalidParameterValueException("Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM"); } - + //check if host is UP if(destinationHost.getStatus() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled){ throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: "+destinationHost.getStatus() + ", state: " +destinationHost.getResourceState()); @@ -3255,7 +3270,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //VV 1: verify the two users Account caller = UserContext.current().getCaller(); if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && caller.getType() != Account.ACCOUNT_TYPE_DOMAIN_ADMIN){ // only root admin can assign VMs - throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType()); + throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType()); } //get and check the valid VM @@ -3277,54 +3292,54 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } //don't allow to move the vm from the project if (oldAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { - InvalidParameterValueException ex = new InvalidParameterValueException("Specified Vm id belongs to the project and can't be moved"); - ex.addProxyObject(vm, cmd.getVmId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Specified Vm id belongs to the project and can't be moved"); + ex.addProxyObject(vm, cmd.getVmId(), "vmId"); throw ex; } Account newAccount = _accountService.getActiveAccountByName(cmd.getAccountName(), cmd.getDomainId()); if (newAccount == null || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain " + cmd.getDomainId()); } - + if (newAccount.getState() == Account.State.disabled) { throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled."); } - + // make sure the accounts are under same domain if (oldAccount.getDomainId() != newAccount.getDomainId()){ - throw new InvalidParameterValueException("The account should be under same domain for moving VM between two accounts. Old owner domain =" + oldAccount.getDomainId() + - " New owner domain=" + newAccount.getDomainId()); - } - - // make sure the accounts are not same - if (oldAccount.getAccountId() == newAccount.getAccountId()){ - throw new InvalidParameterValueException("The account should be same domain for moving VM between two accounts. Account id =" + oldAccount.getAccountId()); + throw new InvalidParameterValueException("The account should be under same domain for moving VM between two accounts. Old owner domain =" + oldAccount.getDomainId() + + " New owner domain=" + newAccount.getDomainId()); } - + // make sure the accounts are not same + if (oldAccount.getAccountId() == newAccount.getAccountId()){ + throw new InvalidParameterValueException("The account should be same domain for moving VM between two accounts. Account id =" + oldAccount.getAccountId()); + } + + // don't allow to move the vm if there are existing PF/LB/Static Nat rules, or vm is assigned to static Nat ip List pfrules = _portForwardingDao.listByVm(cmd.getVmId()); if (pfrules != null && pfrules.size() > 0){ - throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user."); } List snrules = _rulesDao.listStaticNatByVmId(vm.getId()); if (snrules != null && snrules.size() > 0){ - throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user."); } List maps = _loadBalancerVMMapDao.listByInstanceId(vm.getId()); if (maps != null && maps.size() > 0) { - throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user."); } // check for one on one nat IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(cmd.getVmId()); if (ip != null){ - if (ip.isOneToOneNat()){ - throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString()); - } + if (ip.isOneToOneNat()){ + throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString()); + } } - + DataCenterVO zone = _dcDao.findById(vm.getDataCenterIdToDeployIn()); - + //Remove vm from instance group removeInstanceFromInstanceGroup(cmd.getVmId()); @@ -3354,7 +3369,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager vm.setAccountId(newAccount.getAccountId()); vm.setDomainId(cmd.getDomainId()); _vmDao.persist(vm); - + // OS 2: update volume List volumes = _volsDao.findByInstance(cmd.getVmId()); for (VolumeVO volume : volumes) { @@ -3364,7 +3379,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _volsDao.persist(volume); _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume); _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize())); + volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize())); } _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.user_vm); @@ -3380,17 +3395,17 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // OS 3: update the network List networkIdList = cmd.getNetworkIds(); List securityGroupIdList = cmd.getSecurityGroupIdList(); - + if (zone.getNetworkType() == NetworkType.Basic) { - if (networkIdList != null && !networkIdList.isEmpty()) { - throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM"); - } - //cleanup the old security groups - _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId()); - //cleanup the network for the oldOwner + if (networkIdList != null && !networkIdList.isEmpty()) { + throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM"); + } + //cleanup the old security groups + _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId()); + //cleanup the network for the oldOwner _networkMgr.cleanupNics(vmOldProfile); _networkMgr.expungeNics(vmOldProfile); - //security groups will be recreated for the new account, when the VM is started + //security groups will be recreated for the new account, when the VM is started List networkList = new ArrayList(); // Get default guest network in Basic zone @@ -3434,63 +3449,63 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager securityGroupIdList.add(defaultGroup.getId()); } } - + List> networks = new ArrayList>(); NicProfile profile = new NicProfile(); profile.setDefaultNic(true); networks.add(new Pair(networkList.get(0), profile)); - + VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(), vm.getId()); VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi); _networkMgr.allocate(vmProfile, networks); _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList); - + s_logger.debug("AssignVM: Basic zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName() ); } else { if (zone.isSecurityGroupEnabled()) { - throw new InvalidParameterValueException("Not yet implemented for SecurityGroupEnabled advanced networks."); + throw new InvalidParameterValueException("Not yet implemented for SecurityGroupEnabled advanced networks."); } else { if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) { throw new InvalidParameterValueException("Can't move vm with security groups; security group feature is not enabled in this zone"); } - //cleanup the network for the oldOwner + //cleanup the network for the oldOwner _networkMgr.cleanupNics(vmOldProfile); _networkMgr.expungeNics(vmOldProfile); - + Set applicableNetworks = new HashSet(); - + if (networkIdList != null && !networkIdList.isEmpty()){ - // add any additional networks - for (Long networkId : networkIdList) { - NetworkVO network = _networkDao.findById(networkId); - if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; - } - - _networkMgr.checkNetworkPermissions(newAccount, network); - - //don't allow to use system networks - NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); - if (networkOffering.isSystemOnly()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; - } - applicableNetworks.add(network); - } + // add any additional networks + for (Long networkId : networkIdList) { + NetworkVO network = _networkDao.findById(networkId); + if (network == null) { + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id"); + ex.addProxyObject(network, networkId, "networkId"); + throw ex; + } + + _networkMgr.checkNetworkPermissions(newAccount, network); + + //don't allow to use system networks + NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); + if (networkOffering.isSystemOnly()) { + InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment"); + ex.addProxyObject(network, networkId, "networkId"); + throw ex; + } + applicableNetworks.add(network); + } } else { - NetworkVO defaultNetwork = null; + NetworkVO defaultNetwork = null; List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { - throw new InvalidParameterValueException("Unable to find network offering with availability=" - + Availability.Required + " to automatically create the network as a part of vm creation"); + throw new InvalidParameterValueException("Unable to find network offering with availability=" + + Availability.Required + " to automatically create the network as a part of vm creation"); } - + PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { // get Virtual networks @@ -3498,20 +3513,20 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (virtualNetworks.isEmpty()) { s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + - requiredOfferings.get(0).getId() + " as a part of deployVM process"); + requiredOfferings.get(0).getId() + " as a part of deployVM process"); Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + - "for account " + newAccount + "; please specify networkIds"); + "for account " + newAccount + "; please specify networkIds"); } else { defaultNetwork = virtualNetworks.get(0); } } else { - throw new InvalidParameterValueException("Required network offering id=" + - requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); + throw new InvalidParameterValueException("Required network offering id=" + + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } applicableNetworks.add(defaultNetwork); @@ -3550,11 +3565,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long vmId = cmd.getVmId(); UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Cann not find VM with ID " + vmId); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Cann not find VM with ID " + vmId); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } - + Account owner = _accountDao.findById(vm.getAccountId()); if (owner == null) { throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId()); @@ -3574,8 +3589,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List rootVols = _volsDao.findByInstance(vmId); if (rootVols.isEmpty()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can not find root volume for VM " + vmId); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Can not find root volume for VM " + vmId); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -3583,9 +3598,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long templateId = root.getTemplateId(); VMTemplateVO template = _templateDao.findById(templateId); if (template == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template for specified volumeid and vmId"); - ex.addProxyObject(vm, vmId, "vmId"); - ex.addProxyObject(root, root.getId(), "volumeId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template for specified volumeid and vmId"); + ex.addProxyObject(vm, vmId, "vmId"); + ex.addProxyObject(root, root.getId(), "volumeId"); throw ex; } @@ -3626,7 +3641,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.debug("Restore VM " + vmId + " with template " + root.getTemplateId() + " successfully"); return vm; } - + @Override public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException, @@ -3643,8 +3658,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType()); } - @Override - public void prepareStop(VirtualMachineProfile profile) { - } - + @Override + public void prepareStop(VirtualMachineProfile profile) { + } + } diff --git a/utils/src/com/cloud/utils/IdentityProxy.java b/utils/src/com/cloud/utils/IdentityProxy.java index 5c75cb9880a..567752e86ab 100644 --- a/utils/src/com/cloud/utils/IdentityProxy.java +++ b/utils/src/com/cloud/utils/IdentityProxy.java @@ -10,7 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.utils; +package com.cloud.utils; + public class IdentityProxy { private String _tableName; @@ -25,11 +26,24 @@ public class IdentityProxy { } public IdentityProxy(String tableName, Long id, String fieldName) { - _tableName = tableName; - _value = id; - _idFieldName = fieldName; + setTableName(tableName); + setValue(id); + setIdFieldName(fieldName); + } + + public IdentityProxy(Object vo, Long id, String fieldName) { + if (vo instanceof String) { + setTableName((String)vo); + } else { + String tablename = AnnotationHelper.getTableName(vo); + if (tablename != null) { + setTableName(tablename); + } + } + setValue(id); + setIdFieldName(fieldName); } - + public String getTableName() { return _tableName; } @@ -45,12 +59,12 @@ public class IdentityProxy { public void setValue(Long value) { _value = value; } - - public void setidFieldName(String value) { - _idFieldName = value; + + public void setIdFieldName(String value) { + _idFieldName = value; } - + public String getidFieldName() { - return _idFieldName; + return _idFieldName; } }