Refactored AssignPortForwardingServiceCmd and DeletePortForwardingServiceCmd

This commit is contained in:
alena 2010-09-08 20:06:15 -07:00
parent fd680189f6
commit 44f86d3726
6 changed files with 167 additions and 111 deletions

View File

@ -22,13 +22,13 @@ import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
@Implementation(method="assignSecurityGroup", manager=Manager.ManagementServer)
public class AssignPortForwardingServiceCmd extends BaseCmd {
public class AssignPortForwardingServiceCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(AssignPortForwardingServiceCmd.class.getName());
private static final String s_name = "assignportforwardingserviceresponse";
@ -148,5 +148,10 @@ public class AssignPortForwardingServiceCmd extends BaseCmd {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
return returnValues;
}
*/
*/
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -18,31 +18,17 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.network.SecurityGroupVO;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.Pair;
import com.cloud.api.BaseCmd.Manager;
@Implementation(method="deleteSecurityGroup", manager=Manager.ManagementServer)
public class DeletePortForwardingServiceCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(DeletePortForwardingServiceCmd.class.getName());
private static final String s_name = "deleteportforwardingserviceresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -60,7 +46,6 @@ public class DeletePortForwardingServiceCmd extends BaseCmd {
return id;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@ -68,40 +53,42 @@ public class DeletePortForwardingServiceCmd extends BaseCmd {
public String getName() {
return s_name;
}
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
Long id = (Long)params.get(BaseCmd.Properties.ID.getName());
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
//verify parameters
SecurityGroupVO sg = getManagementServer().findSecurityGroupById(id.longValue());
if (sg == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find port forwarding service with id " + id);
}
if (account != null) {
if (!isAdmin(account.getType())) {
if (account.getId().longValue() != sg.getAccountId()) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "unable to find a port forwarding service with id " + id + " for this account");
}
} else if (!getManagementServer().isChildDomain(account.getDomainId(), sg.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to delete port forwarding service " + id + ", permission denied.");
}
}
long jobId = getManagementServer().deleteSecurityGroupAsync(userId.longValue(), sg.getAccountId(), id.longValue());
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId).toString()));
return returnValues;
}
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
// Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
// Long id = (Long)params.get(BaseCmd.Properties.ID.getName());
//
// if (userId == null) {
// userId = Long.valueOf(User.UID_SYSTEM);
// }
//
// //verify parameters
// SecurityGroupVO sg = getManagementServer().findSecurityGroupById(id.longValue());
// if (sg == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find port forwarding service with id " + id);
// }
//
// if (account != null) {
// if (!isAdmin(account.getType())) {
// if (account.getId().longValue() != sg.getAccountId()) {
// throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "unable to find a port forwarding service with id " + id + " for this account");
// }
// } else if (!getManagementServer().isChildDomain(account.getDomainId(), sg.getDomainId())) {
// throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to delete port forwarding service " + id + ", permission denied.");
// }
// }
//
// long jobId = getManagementServer().deleteSecurityGroupAsync(userId.longValue(), sg.getAccountId(), id.longValue());
//
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId).toString()));
// return returnValues;
// }
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -33,7 +33,6 @@ import com.cloud.api.commands.RebootRouterCmd;
import com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd;
import com.cloud.api.commands.StartRouterCmd;
import com.cloud.api.commands.StopRouterCmd;
import com.cloud.api.commands.UpdateIPForwardingRuleCmd;
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;

View File

@ -71,7 +71,6 @@ import com.cloud.api.commands.RebootRouterCmd;
import com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd;
import com.cloud.api.commands.StartRouterCmd;
import com.cloud.api.commands.StopRouterCmd;
import com.cloud.api.commands.UpdateIPForwardingRuleCmd;
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
import com.cloud.async.AsyncJobExecutor;
import com.cloud.async.AsyncJobManager;

View File

@ -23,10 +23,12 @@ import java.util.List;
import java.util.Map;
import com.cloud.alert.AlertVO;
import com.cloud.api.commands.AssignPortForwardingServiceCmd;
import com.cloud.api.commands.CreateDomainCmd;
import com.cloud.api.commands.CreatePortForwardingServiceCmd;
import com.cloud.api.commands.CreatePortForwardingServiceRuleCmd;
import com.cloud.api.commands.CreateUserCmd;
import com.cloud.api.commands.DeletePortForwardingServiceCmd;
import com.cloud.api.commands.DeleteUserCmd;
import com.cloud.api.commands.EnableAccountCmd;
import com.cloud.api.commands.EnableUserCmd;
@ -1620,7 +1622,8 @@ public interface ManagementServer {
* @param publicIp ip address used for creating forwarding rules from the network rules in the group
* @param vmId vm id to use from getting the private ip address used for creating forwarding rules from the network rules in the group
*/
void assignSecurityGroup(Long userId, Long securityGroupId, List<Long> securityGroupIdList, String publicIp, Long vmId, long startEventId) throws PermissionDeniedException, NetworkRuleConflictException, InvalidParameterValueException, InternalErrorException;
// void assignSecurityGroup(Long userId, Long securityGroupId, List<Long> securityGroupIdList, String publicIp, Long vmId, long startEventId) throws PermissionDeniedException, NetworkRuleConflictException, InvalidParameterValueException, InternalErrorException;
void assignSecurityGroup(AssignPortForwardingServiceCmd cmd) throws PermissionDeniedException, NetworkRuleConflictException, InvalidParameterValueException, InternalErrorException;
/**
* remove a security group from a publicIp/vmId combination where it had been previously applied
@ -1632,7 +1635,7 @@ public interface ManagementServer {
void removeSecurityGroup(long userId, long securityGroupId, String publicIp, long vmId, long startEventId) throws InvalidParameterValueException, PermissionDeniedException;
void removeSecurityGroup(RemovePortForwardingServiceCmd cmd) throws InvalidParameterValueException, PermissionDeniedException;
long assignSecurityGroupAsync(Long userId, Long securityGroupId, List<Long> securityGroupIdList, String publicIp, Long vmId);
// long assignSecurityGroupAsync(Long userId, Long securityGroupId, List<Long> securityGroupIdList, String publicIp, Long vmId);
long removeSecurityGroupAsync(Long userId, long securityGroupId, String publicIp, long vmId);
@ -1685,8 +1688,10 @@ public interface ManagementServer {
* @param eventId
* @return true if the security group is deleted, exception is thrown otherwise
*/
boolean deleteSecurityGroup(long userId, long securityGroupId, long eventId) throws InvalidParameterValueException, PermissionDeniedException;
long deleteSecurityGroupAsync(long userId, Long accountId, long securityGroupId);
// boolean deleteSecurityGroup(long userId, long securityGroupId, long eventId) throws InvalidParameterValueException, PermissionDeniedException;
boolean deleteSecurityGroup(DeletePortForwardingServiceCmd cmd) throws InvalidParameterValueException, PermissionDeniedException;
// long deleteSecurityGroupAsync(long userId, Long accountId, long securityGroupId);
/**
* check if a security group name in the given account/domain is in use

View File

@ -33,6 +33,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@ -54,12 +55,14 @@ import com.cloud.alert.AlertVO;
import com.cloud.alert.dao.AlertDao;
import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
import com.cloud.api.commands.AssignPortForwardingServiceCmd;
import com.cloud.api.commands.AuthorizeNetworkGroupIngressCmd;
import com.cloud.api.commands.CreateDomainCmd;
import com.cloud.api.commands.CreatePortForwardingServiceCmd;
import com.cloud.api.commands.CreatePortForwardingServiceRuleCmd;
import com.cloud.api.commands.CreateUserCmd;
import com.cloud.api.commands.CreateVolumeCmd;
import com.cloud.api.commands.DeletePortForwardingServiceCmd;
import com.cloud.api.commands.DeleteUserCmd;
import com.cloud.api.commands.DeployVMCmd;
import com.cloud.api.commands.EnableAccountCmd;
@ -175,7 +178,6 @@ import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.info.ConsoleProxyInfo;
import com.cloud.network.Criteria;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.IPAddressVO;
import com.cloud.network.LoadBalancerVMMapVO;
@ -2874,18 +2876,58 @@ public class ManagementServerImpl implements ManagementServer {
@Override
@DB
public void assignSecurityGroup(Long userId, Long securityGroupId, List<Long> securityGroupIdList, String publicIp, Long vmId, long startEventId) throws PermissionDeniedException,
public void assignSecurityGroup(AssignPortForwardingServiceCmd cmd) throws PermissionDeniedException,
NetworkRuleConflictException, InvalidParameterValueException, InternalErrorException {
Long userId = UserContext.current().getUserId();
Account account = (Account)UserContext.current().getAccountObject();
Long securityGroupId = cmd.getId();
List<Long> sgIdList = cmd.getIds();
String publicIp = cmd.getPublicIp();
Long vmId = cmd.getVirtualMachineId();
//Verify input parameters
if ((securityGroupId == null) && (sgIdList == null)) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "No service id (or list of ids) specified.");
}
if (userId == null) {
userId = Long.valueOf(1);
}
List<Long> validateSGList = null;
if (securityGroupId == null) {
validateSGList = sgIdList;
} else {
validateSGList = new ArrayList<Long>();
validateSGList.add(securityGroupId);
}
Long validatedAccountId = validateSecurityGroupsAndInstance(validateSGList, vmId);
if (validatedAccountId == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to apply port forwarding services " + StringUtils.join(sgIdList, ",") + " to instance " + vmId + ". Invalid list of port forwarding services for the given instance.");
}
if (account != null) {
if (!isAdmin(account.getType()) && (account.getId().longValue() != validatedAccountId.longValue())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Permission denied applying port forwarding services " + StringUtils.join(sgIdList, ",") + " to instance " + vmId + ".");
} else {
Account validatedAccount = findAccountById(validatedAccountId);
if (!isChildDomain(account.getDomainId(), validatedAccount.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Permission denied applying port forwarding services " + StringUtils.join(sgIdList, ",") + " to instance " + vmId + ".");
}
}
}
UserVm userVm = _userVmDao.findById(vmId);
if (userVm == null) {
s_logger.warn("Unable to find virtual machine with id " + vmId);
throw new InvalidParameterValueException("Unable to find virtual machine with id " + vmId);
}
long startEventId = EventUtils.saveScheduledEvent(userId, userVm.getAccountId(), EventTypes.EVENT_PORT_FORWARDING_SERVICE_APPLY, "applying port forwarding service for Vm with Id: "+vmId);
boolean locked = false;
Transaction txn = Transaction.currentTxn();
try {
UserVmVO userVm = _userVmDao.findById(vmId);
if (userVm == null) {
s_logger.warn("Unable to find virtual machine with id " + vmId);
throw new InvalidParameterValueException("Unable to find virtual machine with id " + vmId);
}
EventUtils.saveStartedEvent(userId, userVm.getAccountId(), EventTypes.EVENT_PORT_FORWARDING_SERVICE_APPLY, "Applying port forwarding service for Vm with Id: "+vmId, startEventId);
State vmState = userVm.getState();
switch (vmState) {
case Destroyed:
@ -2893,7 +2935,7 @@ public class ManagementServerImpl implements ManagementServer {
case Expunging:
case Unknown:
throw new InvalidParameterValueException("Unable to assign port forwarding service(s) '"
+ ((securityGroupId == null) ? StringUtils.join(securityGroupIdList, ",") : securityGroupId) + "' to virtual machine " + vmId
+ ((securityGroupId == null) ? StringUtils.join(sgIdList, ",") : securityGroupId) + "' to virtual machine " + vmId
+ " due to virtual machine being in an invalid state for assigning a port forwarding service (" + vmState + ")");
}
@ -2933,9 +2975,6 @@ public class ManagementServerImpl implements ManagementServer {
txn.start();
// save off the owner of the instance to be used for events
Account account = _accountDao.findById(userVm.getAccountId());
if (securityGroupId == null) {
// - send one command to agent to remove *all* rules for
// publicIp/vm combo
@ -2954,7 +2993,7 @@ public class ManagementServerImpl implements ManagementServer {
description = "deleted ip forwarding rule [" + fwRule.getPublicIpAddress() + ":" + fwRule.getPublicPort() + "]->[" + fwRule.getPrivateIpAddress() + ":"
+ fwRule.getPrivatePort() + "]" + " " + fwRule.getProtocol();
EventUtils.saveEvent(userId, account.getId(), level, type, description);
EventUtils.saveEvent(userId, userVm.getAccountId(), level, type, description);
}
}
@ -2962,7 +3001,7 @@ public class ManagementServerImpl implements ManagementServer {
if ((updatedRules != null) && (updatedRules.size() != fwRulesToRemove.size())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to clean up all port forwarding service rules for public IP " + publicIp + " and guest vm " + userVm.getName()
+ " while applying port forwarding service(s) '" + ((securityGroupId == null) ? StringUtils.join(securityGroupIdList, ",") : securityGroupId) + "'"
+ " while applying port forwarding service(s) '" + ((securityGroupId == null) ? StringUtils.join(sgIdList, ",") : securityGroupId) + "'"
+ " -- intended to remove " + fwRulesToRemove.size() + " rules, removd " + ((updatedRules == null) ? "null" : updatedRules.size()) + " rules.");
}
}
@ -3008,7 +3047,7 @@ public class ManagementServerImpl implements ManagementServer {
if (securityGroupId != null) {
finalSecurityGroupIdList.add(securityGroupId);
} else {
finalSecurityGroupIdList.addAll(securityGroupIdList);
finalSecurityGroupIdList.addAll(sgIdList);
}
for (Long sgId : finalSecurityGroupIdList) {
@ -3123,20 +3162,20 @@ public class ManagementServerImpl implements ManagementServer {
}
}
@Override
public long assignSecurityGroupAsync(Long userId, Long securityGroupId, List<Long> securityGroupIdList, String publicIp, Long vmId) {
UserVm userVm = _userVmDao.findById(vmId);
long eventId = EventUtils.saveScheduledEvent(userId, userVm.getAccountId(), EventTypes.EVENT_PORT_FORWARDING_SERVICE_APPLY, "applying port forwarding service for Vm with Id: "+vmId);
SecurityGroupParam param = new SecurityGroupParam(userId, securityGroupId, securityGroupIdList, publicIp, vmId, eventId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(userVm.getAccountId());
job.setCmd("AssignSecurityGroup");
job.setCmdInfo(gson.toJson(param));
return _asyncMgr.submitAsyncJob(job);
}
// @Override
// public long assignSecurityGroupAsync(Long userId, Long securityGroupId, List<Long> securityGroupIdList, String publicIp, Long vmId) {
// UserVm userVm = _userVmDao.findById(vmId);
// long eventId = EventUtils.saveScheduledEvent(userId, userVm.getAccountId(), EventTypes.EVENT_PORT_FORWARDING_SERVICE_APPLY, "applying port forwarding service for Vm with Id: "+vmId);
// SecurityGroupParam param = new SecurityGroupParam(userId, securityGroupId, securityGroupIdList, publicIp, vmId, eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(userVm.getAccountId());
// job.setCmd("AssignSecurityGroup");
// job.setCmdInfo(gson.toJson(param));
// return _asyncMgr.submitAsyncJob(job);
// }
@Override
public void removeSecurityGroup(RemovePortForwardingServiceCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
@ -7231,28 +7270,50 @@ public class ManagementServerImpl implements ManagementServer {
return _securityGroupDao.persist(group);
}
// @Override
// public long deleteSecurityGroupAsync(long userId, Long accountId, long securityGroupId) {
//
// long eventId = EventUtils.saveScheduledEvent(userId, accountId, EventTypes.EVENT_PORT_FORWARDING_SERVICE_DELETE, "deleting security group with Id: " + securityGroupId);
// SecurityGroupParam param = new SecurityGroupParam(userId, securityGroupId, null, null, null, eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(accountId);
// job.setCmd("DeleteSecurityGroup");
// job.setCmdInfo(gson.toJson(param));
// return _asyncMgr.submitAsyncJob(job);
// }
@Override
public long deleteSecurityGroupAsync(long userId, Long accountId, long securityGroupId) {
public boolean deleteSecurityGroup(DeletePortForwardingServiceCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
Long securityGroupId = cmd.getId();
Long userId = UserContext.current().getUserId();
Account account = (Account)UserContext.current().getAccountObject();
long eventId = EventUtils.saveScheduledEvent(userId, accountId, EventTypes.EVENT_PORT_FORWARDING_SERVICE_DELETE, "deleting security group with Id: " + securityGroupId);
SecurityGroupParam param = new SecurityGroupParam(userId, securityGroupId, null, null, null, eventId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(accountId);
job.setCmd("DeleteSecurityGroup");
job.setCmdInfo(gson.toJson(param));
return _asyncMgr.submitAsyncJob(job);
}
@Override
public boolean deleteSecurityGroup(long userId, long securityGroupId, long startEventId) throws InvalidParameterValueException, PermissionDeniedException {
SecurityGroupVO securityGroup = _securityGroupDao.findById(Long.valueOf(securityGroupId));
if (securityGroup == null) {
return true; // already deleted, return true
//Verify input parameters
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
//verify parameters
SecurityGroupVO securityGroup = _securityGroupDao.findById(Long.valueOf(securityGroupId));
if (securityGroup == null) {
throw new InvalidParameterValueException("unable to find port forwarding service with id " + securityGroupId);
}
if (account != null) {
if (!isAdmin(account.getType())) {
if (account.getId().longValue() != securityGroup.getAccountId()) {
throw new PermissionDeniedException("unable to find a port forwarding service with id " + securityGroupId + " for this account, permission denied");
}
} else if (!isChildDomain(account.getDomainId(), securityGroup.getDomainId())) {
throw new PermissionDeniedException("Unable to delete port forwarding service " + securityGroupId + ", permission denied.");
}
}
long startEventId = EventUtils.saveScheduledEvent(userId, securityGroup.getAccountId(), EventTypes.EVENT_PORT_FORWARDING_SERVICE_DELETE, "deleting security group with Id: " + securityGroupId);
final EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(securityGroup.getAccountId());