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<IdentityProxy>. 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.
This commit is contained in:
Vijayendra Bhamidipati 2012-07-05 16:22:44 -07:00
parent e6d73fb114
commit f1ec4fddd3
65 changed files with 2207 additions and 2083 deletions

View File

@ -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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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;

View File

@ -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;

View File

@ -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<String, String> getTags() {
Map<String, String> 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);
}

View File

@ -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;

View File

@ -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) {

View File

@ -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();
}
}

View File

@ -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<? extends Network> 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;

View File

@ -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);

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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<String> 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<String> 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<String> 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;

View File

@ -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<String> 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<String> 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;

View File

@ -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<String> 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<? extends Network> 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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<String> 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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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;

View File

@ -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<String> 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<String> 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<String> 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;

View File

@ -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);

View File

@ -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<String> 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<String> getSupportedServices() {
return supportedServices;
}
public String getGuestIpType() {
public List<String> 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<String, String> svcCapabilityMap = (HashMap<String, String>) 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;

View File

@ -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<String> 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;

View File

@ -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;

View File

@ -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) {

View File

@ -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;
}

View File

@ -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();
}

View File

@ -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()));

View File

@ -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;

View File

@ -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");
}
}
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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();
}

View File

@ -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;

View File

@ -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;

View File

@ -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();
}

View File

@ -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;

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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{

View File

@ -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;

View File

@ -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<Long> 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<String> 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<Long> 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<Long> securityGroupIds = new ArrayList<Long>();
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<Long> getNetworkIds() {
if (ipToNetworkList != null) {
if (networkIds != null || ipAddress != null) {
throw new InvalidParameterValueException("ipToNetworkMap can't be specified along with networkIds or ipAddress");
} else {
List<Long> networks = new ArrayList<Long>();
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<Long> networks = new ArrayList<Long>();
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<Long, String> 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<Long, String> ipToNetworkMap = null;
if (ipToNetworkList != null && !ipToNetworkList.isEmpty()) {
@ -257,11 +258,11 @@ public class DeployVMCmd extends BaseAsyncCreateCmd {
while (iter.hasNext()) {
HashMap<String, String> ips = (HashMap<String, String>) 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);

View File

@ -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);

View File

@ -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;
}

View File

@ -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();

View File

@ -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());

View File

@ -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<? extends Capacity> result = null;
@ -124,7 +124,7 @@ public class ListCapacityCmd extends BaseListCmd {
} else {
result = _mgr.listCapacities(this);
}
ListResponse<CapacityResponse> response = new ListResponse<CapacityResponse>();
List<CapacityResponse> capacityResponses = _responseGenerator.createCapacityResponse(result, s_percentFormat);
response.setResponses(capacityResponses);

View File

@ -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<String> 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<HostDetails> getDetails() throws InvalidParameterValueException {
EnumSet<HostDetails> 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<? extends Host> result = new ArrayList<Host>();
List<? extends Host> hostsWithCapacity = new ArrayList<Host>();
if(getVirtualMachineId() != null){
List<? extends Host> result = new ArrayList<Host>();
List<? extends Host> hostsWithCapacity = new ArrayList<Host>();
if(getVirtualMachineId() != null){
Pair<List<? extends Host>, List<? extends Host>> 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<HostResponse> response = new ListResponse<HostResponse>();
List<HostResponse> hostResponses = new ArrayList<HostResponse>();

View File

@ -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<? extends Network.Service> 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<Network.Service> serviceList = new ArrayList<Network.Service>();
@ -92,14 +92,14 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd {
}else{
services = _networkService.listNetworkServices(getProviderName());
}
ListResponse<ServiceResponse> response = new ListResponse<ServiceResponse>();
List<ServiceResponse> servicesResponses = new ArrayList<ServiceResponse>();
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);
}

View File

@ -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<String> 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<VMDetails> getDetails() throws InvalidParameterValueException {
EnumSet<VMDetails> 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<? extends UserVm> result = _userVmService.searchForUserVMs(this);
ListResponse<UserVmResponse> response = new ListResponse<UserVmResponse>();
EnumSet<VMDetails> details = getDetails();
List<UserVmResponse> 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);
}
}

View File

@ -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());
}
}
}
}

View File

@ -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());
}
}
}
}

View File

@ -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();
}
}

View File

@ -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();
}

View File

@ -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();
}
}

View File

@ -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");
}

View File

@ -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;

View File

@ -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;

View File

@ -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<Long> projectIds;
@ -61,9 +61,9 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd {
public List<String> 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<Long> 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;
}

View File

@ -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);

View File

@ -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);

View File

@ -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<IdentityProxy> idProxyList) {
super(message);
if (idProxyList != null) {
for (IdentityProxy id : idProxyList) {
this.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName());
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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<String, Object> 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<String, Object> 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<VMTemplateVO> 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<DataCenterVO> 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);
}

View File

@ -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<UserVO> 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<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
for (InstanceGroupVO group : groups) {
@ -598,7 +600,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
List<? extends IpAddress> 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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<UserVO> 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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<Long> managedProjectIds = _projectAccountDao.listAdministratedProjectIds(accountId);
if (!managedProjectIds.isEmpty()) {
StringBuilder projectIds = new StringBuilder();
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<DataCenterVO> 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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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<IdentityProxy> idList = new ArrayList<IdentityProxy>();
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);

File diff suppressed because it is too large Load Diff

View File

@ -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;
}
}