remote access vpn, user ip address changes

This commit is contained in:
Alex Huang 2010-12-29 07:14:19 -08:00
parent 1afb34d38e
commit 544fa7ff1b
134 changed files with 1752 additions and 2459 deletions

View File

@ -134,7 +134,7 @@ import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
import com.cloud.agent.api.routing.RoutingCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
@ -1109,7 +1109,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
return execute((FenceCommand) cmd);
} else if (cmd instanceof StartCommand ) {
return execute((StartCommand) cmd);
} else if (cmd instanceof RoutingCommand) {
} else if (cmd instanceof NetworkElementCommand) {
return _virtRouterResource.executeRequest(cmd);
} else if (cmd instanceof CheckSshCommand) {
return execute((CheckSshCommand) cmd);

View File

@ -24,7 +24,7 @@ import com.cloud.agent.api.to.IpAddressTO;
* @author alena
*
*/
public class IPAssocCommand extends RoutingCommand {
public class IPAssocCommand extends NetworkElementCommand {
IpAddressTO[] ipAddresses;

View File

@ -23,7 +23,7 @@ import com.cloud.agent.api.to.LoadBalancerTO;
* LoadBalancerConfigCommand sends the load balancer configuration
* to the load balancer. Isn't that kinda obvious?
*/
public class LoadBalancerConfigCommand extends RoutingCommand {
public class LoadBalancerConfigCommand extends NetworkElementCommand {
LoadBalancerTO[] loadBalancers;
public LoadBalancerConfigCommand( LoadBalancerTO[] loadBalancers) {

View File

@ -21,13 +21,13 @@ import java.util.HashMap;
import com.cloud.agent.api.Command;
public abstract class RoutingCommand extends Command {
public abstract class NetworkElementCommand extends Command {
HashMap<String, String> accessDetails = new HashMap<String, String>(0);
public static final String ROUTER_NAME = "router.name";
public static final String ROUTER_IP = "router.ip";
protected RoutingCommand() {
protected NetworkElementCommand() {
super();
}

View File

@ -27,7 +27,7 @@ import com.cloud.agent.api.to.FirewallRuleTO;
* AccessDetails allow different components to put in information about
* how to access the components inside the command.
*/
public class SetFirewallRulesCommand extends RoutingCommand {
public class SetFirewallRulesCommand extends NetworkElementCommand {
FirewallRuleTO[] rules;
protected SetFirewallRulesCommand() {

View File

@ -22,7 +22,7 @@ import java.util.List;
import com.cloud.agent.api.to.PortForwardingRuleTO;
import com.cloud.network.rules.PortForwardingRule;
public class SetPortForwardingRulesCommand extends RoutingCommand {
public class SetPortForwardingRulesCommand extends NetworkElementCommand {
PortForwardingRuleTO[] rules;
protected SetPortForwardingRulesCommand() {

View File

@ -32,13 +32,16 @@ import com.cloud.consoleproxy.ConsoleProxyService;
import com.cloud.dao.EntityManager;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.VirtualNetworkApplianceService;
import com.cloud.network.NetworkService;
import com.cloud.network.VirtualNetworkApplianceService;
import com.cloud.network.lb.LoadBalancingRulesService;
import com.cloud.network.rules.RulesService;
import com.cloud.network.security.SecurityGroupService;
import com.cloud.network.vpn.RemoteAccessVpnService;
import com.cloud.resource.ResourceService;
import com.cloud.server.ManagementService;
import com.cloud.storage.StorageService;
@ -46,6 +49,7 @@ import com.cloud.storage.snapshot.SnapshotService;
import com.cloud.template.TemplateService;
import com.cloud.user.Account;
import com.cloud.user.AccountService;
import com.cloud.user.UserContext;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.UserVmService;
@ -92,18 +96,19 @@ public abstract class BaseCmd {
public static AccountService _accountService;
public static UserVmService _userVmService;
public static ManagementService _mgr;
public static StorageService _storageMgr;
public static StorageService _storageService;
public static ResourceService _resourceService;
public static NetworkService _networkService;
public static TemplateService _templateService;
public static SecurityGroupService _securityGroupMgr;
public static SnapshotService _snapshotMgr;
public static ConsoleProxyService _consoleProxyMgr;
public static SecurityGroupService _securityGroupService;
public static SnapshotService _snapshotService;
public static ConsoleProxyService _consoleProxyService;
public static VirtualNetworkApplianceService _routerService;
public static ResponseGenerator _responseGenerator;
public static EntityManager _entityMgr;
public static RulesService _rulesService;
public static LoadBalancingRulesService _lbService;
public static RemoteAccessVpnService _ravService;
static void setComponents(ResponseGenerator generator) {
@ -112,17 +117,18 @@ public abstract class BaseCmd {
_accountService = locator.getManager(AccountService.class);
_configService = locator.getManager(ConfigurationService.class);
_userVmService = locator.getManager(UserVmService.class);
_storageMgr = locator.getManager(StorageService.class);
_storageService = locator.getManager(StorageService.class);
_resourceService = locator.getManager(ResourceService.class);
_networkService = locator.getManager(NetworkService.class);
_templateService = locator.getManager(TemplateService.class);
_securityGroupMgr = locator.getManager(SecurityGroupService.class);
_snapshotMgr = locator.getManager(SnapshotService.class);
_consoleProxyMgr = locator.getManager(ConsoleProxyService.class);
_securityGroupService = locator.getManager(SecurityGroupService.class);
_snapshotService = locator.getManager(SnapshotService.class);
_consoleProxyService = locator.getManager(ConsoleProxyService.class);
_routerService = locator.getManager(VirtualNetworkApplianceService.class);
_entityMgr = locator.getManager(EntityManager.class);
_rulesService = locator.getManager(RulesService.class);
_lbService = locator.getManager(LoadBalancingRulesService.class);
_ravService = locator.getManager(RemoteAccessVpnService.class);
_responseGenerator = generator;
}
@ -160,6 +166,22 @@ public abstract class BaseCmd {
return formattedString;
}
protected Account getValidOwner(String accountName, Long domainId) {
Account owner = null;
if (accountName != null) {
owner = _responseGenerator.findAccountByNameDomain(accountName, domainId);
} else {
owner = UserContext.current().getCaller();
}
if (owner == null) {
throw new InvalidParameterValueException("Invalid value for owner specified: " + accountName);
}
if (owner.getState() == Account.State.Disabled || owner.getState() == Account.State.Locked) {
throw new PermissionDeniedException("Account disabled.");
}
return owner;
}
public Map<String, Object> validateParams(Map<String, String> params, boolean decode) {
// List<Pair<Enum, Boolean>> properties = getProperties();
@ -253,7 +275,7 @@ public abstract class BaseCmd {
return validatedParams;
*/
}
private Map<String, Object> lowercaseParams(Map<String, String> params, boolean decode) {
Map<String, Object> lowercaseParams = new HashMap<String, Object>();
for (String key : params.keySet()) {

View File

@ -20,7 +20,7 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseAsyncCreateCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
@ -28,13 +28,12 @@ import com.cloud.api.ServerApiException;
import com.cloud.api.response.VpnUsersResponse;
import com.cloud.domain.Domain;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.network.VpnUser;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
@Implementation(description="Adds vpn users", responseObject=VpnUsersResponse.class)
public class AddVpnUserCmd extends BaseAsyncCmd {
public class AddVpnUserCmd extends BaseAsyncCreateCmd {
public static final Logger s_logger = Logger.getLogger(AddVpnUserCmd.class.getName());
private static final String s_name = "addvpnuserresponse";
@ -94,7 +93,7 @@ public class AddVpnUserCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
@ -125,29 +124,38 @@ public class AddVpnUserCmd extends BaseAsyncCmd {
@Override
public void execute(){
try {
VpnUser vpnUser = _networkService.addVpnUser(this);
if (vpnUser != null) {
VpnUsersResponse vpnResponse = new VpnUsersResponse();
vpnResponse.setId(vpnUser.getId());
vpnResponse.setUserName(vpnUser.getUsername());
vpnResponse.setAccountName(vpnUser.getAccountName());
Account accountTemp = _entityMgr.findById(Account.class, vpnUser.getAccountId());
if (accountTemp != null) {
vpnResponse.setDomainId(accountTemp.getDomainId());
vpnResponse.setDomainName(_entityMgr.findById(Domain.class, accountTemp.getDomainId()).getName());
}
vpnResponse.setResponseName(getCommandName());
vpnResponse.setObjectName("vpnuser");
this.setResponseObject(vpnResponse);
} else {
VpnUser vpnUser = _entityMgr.findById(VpnUser.class, getEntityId());
Account account = _entityMgr.findById(Account.class, vpnUser.getAccountId());
if (!_ravService.applyVpnUsers(vpnUser.getAccountId())) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user");
}
} catch (ConcurrentOperationException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
}
VpnUsersResponse vpnResponse = new VpnUsersResponse();
vpnResponse.setId(vpnUser.getId());
vpnResponse.setUserName(vpnUser.getUsername());
vpnResponse.setAccountName(account.getAccountName());
vpnResponse.setDomainId(account.getDomainId());
vpnResponse.setDomainName(_entityMgr.findById(Domain.class, account.getDomainId()).getName());
vpnResponse.setResponseName(getCommandName());
vpnResponse.setObjectName("vpnuser");
this.setResponseObject(vpnResponse);
}
@Override
public void create() {
Account owner = null;
if (accountName != null) {
owner = _responseGenerator.findAccountByNameDomain(accountName, domainId);
} else {
owner = UserContext.current().getCaller();
}
VpnUser vpnUser = _ravService.addVpnUser(owner.getId(), userName, password);
if (vpnUser == null) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user");
}
setEntityId(vpnUser.getId());
}
}

View File

@ -67,14 +67,14 @@ public class AssociateIPAddrCmd extends BaseCmd {
if (accountName != null) {
return accountName;
}
return UserContext.current().getAccount().getAccountName();
return UserContext.current().getCaller().getAccountName();
}
public long getDomainId() {
if (domainId != null) {
return domainId;
}
return UserContext.current().getAccount().getDomainId();
return UserContext.current().getCaller().getDomainId();
}
public long getZoneId() {

View File

@ -154,7 +154,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
@ -207,7 +207,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd {
@Override
public void execute(){
List<? extends IngressRule> ingressRules = _securityGroupMgr.authorizeSecurityGroupIngress(this);
List<? extends IngressRule> ingressRules = _securityGroupService.authorizeSecurityGroupIngress(this);
if (ingressRules != null && ! ingressRules.isEmpty()) {
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponseFromIngressRule(ingressRules);
this.setResponseObject(response);

View File

@ -71,7 +71,7 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -79,7 +79,7 @@ public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}
@ -99,7 +99,7 @@ public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd {
@Override
public void execute(){
StoragePool result = _storageMgr.cancelPrimaryStorageForMaintenance(this);
StoragePool result = _storageService.cancelPrimaryStorageForMaintenance(this);
if (result != null) {
StoragePoolResponse response = _responseGenerator.createStoragePoolResponse(result);
response.setResponseName(getCommandName());

View File

@ -77,7 +77,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Por
public void execute(){
boolean result;
try {
result = _rulesService.applyPortForwardingRules(new Ip(ipAddress), UserContext.current().getAccount());
result = _rulesService.applyPortForwardingRules(new Ip(ipAddress), UserContext.current().getCaller());
} catch (Exception e) {
s_logger.error("Unable to apply port forwarding rules", e);
_rulesService.revokePortForwardingRule(getEntityId(), true);

View File

@ -166,12 +166,12 @@ public class CreateLoadBalancerRuleCmd extends BaseCmd implements LoadBalancer
@Override
public long getAccountId() {
return UserContext.current().getAccount().getId();
return UserContext.current().getCaller().getId();
}
@Override
public long getDomainId() {
return UserContext.current().getAccount().getDomainId();
return UserContext.current().getCaller().getDomainId();
}
@Override

View File

@ -102,7 +102,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements
boolean success = false;
PortForwardingRule rule = _entityMgr.findById(PortForwardingRule.class, getEntityId());
try {
success = _rulesService.applyPortForwardingRules(rule.getSourceIpAddress(), callerContext.getAccount());
success = _rulesService.applyPortForwardingRules(rule.getSourceIpAddress(), callerContext.getCaller());
} finally {
if (!success) {
_rulesService.revokePortForwardingRule(getEntityId(), true);
@ -186,6 +186,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements
setEntityId(result.getId());
} catch (NetworkRuleConflictException ex) {
s_logger.info("Network rule conflict: " + ex.getMessage());
s_logger.trace("Network Rule Conflict: ", ex);
throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage());
}
}

View File

@ -29,10 +29,12 @@ import com.cloud.api.response.RemoteAccessVpnResponse;
import com.cloud.domain.Domain;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
import com.cloud.utils.net.Ip;
@Implementation(description="Creates a l2tp/ipsec remote access vpn", responseObject=RemoteAccessVpnResponse.class)
public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
@ -43,10 +45,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name="zoneid", type=CommandType.LONG, required=true, description="zone id where the vpn server needs to be created")
private Long zoneId;
@Parameter(name="publicip", type=CommandType.STRING, required=false, description="public ip address of the vpn server")
@Parameter(name="publicip", type=CommandType.STRING, required=true, description="public ip address of the vpn server")
private String publicIp;
@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")
@ -86,13 +85,6 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
this.ipRange = ipRange;
}
public void setZoneId(Long zoneId) {
this.zoneId = zoneId;
}
public Long getZoneId() {
return zoneId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@ -106,7 +98,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
@ -125,7 +117,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
@Override
public String getEventDescription() {
return "Create Remote Access VPN for account " + getEntityOwnerId() + " in zone " + getZoneId();
return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public " + publicIp;
}
@Override
@ -134,29 +126,30 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
}
@Override
public void create(){
public void create() {
try {
RemoteAccessVpn vpn = _networkService.createRemoteAccessVpn(this);
RemoteAccessVpn vpn = _ravService.createRemoteAccessVpn(new Ip(publicIp), ipRange);
if (vpn != null) {
this.setEntityId(vpn.getId());
this.setEntityId(vpn.getServerAddress().longValue());
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create remote access vpn");
}
} catch (ConcurrentOperationException ex) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
}
} catch (NetworkRuleConflictException e) {
s_logger.info("Network rule conflict: " + e.getMessage());
s_logger.trace("Network Rule Conflict: ", e);
throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());
}
}
@Override
public void execute(){
try {
RemoteAccessVpn result = _networkService.startRemoteAccessVpn(this);
RemoteAccessVpn result = _ravService.startRemoteAccessVpn(new Ip(getEntityId()));
if (result != null) {
RemoteAccessVpnResponse response = new RemoteAccessVpnResponse();
response.setId(result.getId());
response.setPublicIp(result.getVpnServerAddress());
response.setPublicIp(result.getServerAddress().toString());
response.setIpRange(result.getIpRange());
response.setAccountName(result.getAccountName());
response.setAccountName(_entityMgr.findById(Account.class, result.getAccountId()).getAccountName());
response.setDomainId(result.getDomainId());
response.setDomainName(_entityMgr.findById(Domain.class, result.getDomainId()).getName());
response.setObjectName("remoteaccessvpn");

View File

@ -83,7 +83,7 @@ public class CreateSecurityGroupCmd extends BaseCmd {
@Override
public void execute(){
SecurityGroup group = _securityGroupMgr.createSecurityGroup(this);
SecurityGroup group = _securityGroupService.createSecurityGroup(this);
if (group != null) {
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponse(group);
response.setResponseName(getCommandName());

View File

@ -120,14 +120,14 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd {
@Override
public void create(){
long id = _snapshotMgr.getNextInSequence(this);
long id = _snapshotService.getNextInSequence(this);
this.setEntityId(id);
}
@Override
public void execute(){
try {
Snapshot snapshot = _snapshotMgr.createSnapshot(this);
Snapshot snapshot = _snapshotService.createSnapshot(this);
if (snapshot != null) {
SnapshotResponse response = _responseGenerator.createSnapshotResponse(snapshot);
response.setResponseName(getCommandName());

View File

@ -109,7 +109,7 @@ public class CreateSnapshotPolicyCmd extends BaseCmd {
@Override
public void execute(){
SnapshotPolicy result = _snapshotMgr.createPolicy(this);
SnapshotPolicy result = _snapshotService.createPolicy(this);
if (result != null) {
SnapshotPolicyResponse response = _responseGenerator.createSnapshotPolicyResponse(result);
response.setResponseName(getCommandName());

View File

@ -109,7 +109,7 @@ public class CreateStoragePoolCmd extends BaseCmd {
@Override
public void execute(){
try {
StoragePool result = _storageMgr.createPool(this);
StoragePool result = _storageService.createPool(this);
if (result != null) {
StoragePoolResponse response = _responseGenerator.createStoragePoolResponse(result);
response.setResponseName(getCommandName());

View File

@ -116,7 +116,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
@ -146,7 +146,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd {
@Override
public void create(){
try {
Volume volume = _storageMgr.allocVolume(this);
Volume volume = _storageService.allocVolume(this);
if (volume != null) {
this.setEntityId(volume.getId());
} else {
@ -160,7 +160,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd {
@Override
public void execute(){
Volume volume = _storageMgr.createVolume(this);
Volume volume = _storageService.createVolume(this);
if (volume != null) {
VolumeResponse response = _responseGenerator.createVolumeResponse(volume);
//FIXME - have to be moved to ApiResponseHelper

View File

@ -69,7 +69,7 @@ public class DeleteAccountCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -42,7 +42,7 @@ public class DeletePoolCmd extends BaseCmd {
@Override
public void execute(){
boolean result = _storageMgr.deletePool(this);
boolean result = _storageService.deletePool(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);

View File

@ -21,15 +21,12 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.utils.net.Ip;
@Implementation(description="Destroys a l2tp/ipsec remote access vpn", responseObject=SuccessResponse.class)
public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd {
@ -40,35 +37,13 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd {
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name="zoneid", type=CommandType.LONG, required=true, description="zone id where the vpn server needs to be created")
private Long zoneId;
@Parameter(name="account", type=CommandType.STRING, description="an optional account for the virtual machine. Must be used with domainId.")
private String accountName;
@Parameter(name="domainid", type=CommandType.LONG, description="an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.")
private Long domainId;
@Parameter(name="publicip", type=CommandType.STRING, required=true, description="public ip address of the vpn server")
private String publicIp;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public void setZoneId(Long zoneId) {
this.zoneId = zoneId;
}
public Long getZoneId() {
return zoneId;
}
public String getAccountName() {
return accountName;
}
public Long getDomainId() {
return domainId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@ -80,26 +55,13 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
if (userAccount != null) {
return userAccount.getId();
}
}
}
if (account != null) {
return account.getId();
}
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
RemoteAccessVpn vpn = _entityMgr.findById(RemoteAccessVpn.class, new Ip(publicIp));
return vpn.getAccountId();
}
@Override
public String getEventDescription() {
return "Delete Remote Access VPN for account " + getEntityOwnerId() + " in zone " + getZoneId();
return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for " + publicIp;
}
@Override
@ -109,18 +71,7 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd {
@Override
public void execute(){
try {
boolean result = _networkService.destroyRemoteAccessVpn(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete remote access vpn");
}
} catch (ConcurrentOperationException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
}
_ravService.destroyRemoteAccessVpn(new Ip(publicIp));
}
}

View File

@ -58,7 +58,7 @@ public class DeleteSecurityGroupCmd extends BaseCmd {
@Override
public void execute(){
try{
boolean result = _securityGroupMgr.deleteSecurityGroup(this);
boolean result = _securityGroupService.deleteSecurityGroup(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);

View File

@ -92,7 +92,7 @@ public class DeleteSnapshotCmd extends BaseAsyncCmd {
@Override
public void execute(){
boolean result = _snapshotMgr.deleteSnapshot(this);
boolean result = _snapshotService.deleteSnapshot(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);

View File

@ -70,7 +70,7 @@ public class DeleteSnapshotPoliciesCmd extends BaseCmd {
@Override
public void execute(){
boolean result = _snapshotMgr.deleteSnapshotPolicies(this);
boolean result = _snapshotService.deleteSnapshotPolicies(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);

View File

@ -64,7 +64,7 @@ public class DeleteVolumeCmd extends BaseCmd {
@Override
public void execute(){
boolean result = _storageMgr.deleteVolume(this);
boolean result = _storageService.deleteVolume(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);

View File

@ -101,7 +101,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd {
public String getAccountName() {
if (accountName == null) {
return UserContext.current().getAccount().getAccountName();
return UserContext.current().getCaller().getAccountName();
}
return accountName;
}
@ -116,7 +116,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd {
public Long getDomainId() {
if (domainId == null) {
return UserContext.current().getAccount().getDomainId();
return UserContext.current().getCaller().getDomainId();
}
return domainId;
}
@ -186,7 +186,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);

View File

@ -65,7 +65,7 @@ public class DestroyConsoleProxyCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = (Account)UserContext.current().getAccount();
Account account = (Account)UserContext.current().getCaller();
if (account != null) {
return account.getId();
}
@ -85,7 +85,7 @@ public class DestroyConsoleProxyCmd extends BaseAsyncCmd {
@Override
public void execute(){
boolean result = _consoleProxyMgr.destroyConsoleProxy(this);
boolean result = _consoleProxyService.destroyConsoleProxy(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);

View File

@ -76,7 +76,7 @@ public class DisableAccountCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -67,7 +67,7 @@ public class DisableUserCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -25,6 +25,7 @@ import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse;
import com.cloud.utils.net.Ip;
@Implementation(description="Disassociates an ip address from the account.", responseObject=SuccessResponse.class)
public class DisassociateIPAddrCmd extends BaseCmd {
@ -43,8 +44,8 @@ public class DisassociateIPAddrCmd extends BaseCmd {
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getIpAddress() {
return ipAddress;
public Ip getIpAddress() {
return new Ip(ipAddress);
}
/////////////////////////////////////////////////////

View File

@ -154,7 +154,7 @@ public class ListIsosCmd extends BaseListCmd {
}
boolean isAdmin = false;
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
isAdmin = true;
}

View File

@ -65,7 +65,7 @@ public class ListRecurringSnapshotScheduleCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends SnapshotSchedule> snapshotSchedules = _snapshotMgr.findRecurringSnapshotSchedule(this);
List<? extends SnapshotSchedule> snapshotSchedules = _snapshotService.findRecurringSnapshotSchedule(this);
ListResponse<SnapshotScheduleResponse> response = new ListResponse<SnapshotScheduleResponse>();
List<SnapshotScheduleResponse> snapshotScheduleResponses = new ArrayList<SnapshotScheduleResponse>();
for (SnapshotSchedule snapshotSchedule : snapshotSchedules) {

View File

@ -29,6 +29,7 @@ import com.cloud.api.Parameter;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.RemoteAccessVpnResponse;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.utils.net.Ip;
@Implementation(description="Lists remote access vpns", responseObject=RemoteAccessVpnResponse.class)
public class ListRemoteAccessVpnsCmd extends BaseListCmd {
@ -46,16 +47,9 @@ public class ListRemoteAccessVpnsCmd extends BaseListCmd {
@Parameter(name="domainid", type=CommandType.LONG, description="the domain ID of the remote access vpn rule. If used with the account parameter, lists remote access vpns for the account in the specified domain.")
private Long domainId;
@Parameter(name="id", type=CommandType.LONG, description="the ID of the remote access vpn")
private Long id;
@Parameter(name="zoneid", type=CommandType.LONG, description="the zone ID of the remote access vpn rule")
private Long zoneId;
@Parameter(name="publicip", type=CommandType.STRING, description="the public IP address of the remote access vpn ")
@Parameter(name="publicip", type=CommandType.STRING, required=true, description="public ip address of the vpn server")
private String publicIp;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@ -67,24 +61,11 @@ public class ListRemoteAccessVpnsCmd extends BaseListCmd {
public Long getDomainId() {
return domainId;
}
public Long getId() {
return id;
public Ip getPublicIp() {
return new Ip(publicIp);
}
public void setZoneId(Long zoneId) {
this.zoneId = zoneId;
}
public Long getZoneId() {
return zoneId;
}
public String getPublicIp() {
return publicIp;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@ -96,7 +77,7 @@ public class ListRemoteAccessVpnsCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends RemoteAccessVpn> vpns = _mgr.searchForRemoteAccessVpns(this);
List<? extends RemoteAccessVpn> vpns = _ravService.searchForRemoteAccessVpns(this);
ListResponse<RemoteAccessVpnResponse> response = new ListResponse<RemoteAccessVpnResponse>();
List<RemoteAccessVpnResponse> vpnResponses = new ArrayList<RemoteAccessVpnResponse>();
for (RemoteAccessVpn vpn : vpns) {

View File

@ -89,7 +89,7 @@ public class ListSecurityGroupsCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends SecurityGroupRules> securityGroups = _securityGroupMgr.searchForSecurityGroupRules(this);
List<? extends SecurityGroupRules> securityGroups = _securityGroupService.searchForSecurityGroupRules(this);
ListResponse<SecurityGroupResponse> response = _responseGenerator.createSecurityGroupResponses(securityGroups);
response.setResponseName(getCommandName());

View File

@ -77,7 +77,7 @@ public class ListSnapshotPoliciesCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends SnapshotPolicy> result = _snapshotMgr.listPoliciesforVolume(this);
List<? extends SnapshotPolicy> result = _snapshotService.listPoliciesforVolume(this);
ListResponse<SnapshotPolicyResponse> response = new ListResponse<SnapshotPolicyResponse>();
List<SnapshotPolicyResponse> policyResponses = new ArrayList<SnapshotPolicyResponse>();
for (SnapshotPolicy policy : result) {

View File

@ -109,7 +109,7 @@ public class ListSnapshotsCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends Snapshot> result = _snapshotMgr.listSnapshots(this);
List<? extends Snapshot> result = _snapshotService.listSnapshots(this);
ListResponse<SnapshotResponse> response = new ListResponse<SnapshotResponse>();
List<SnapshotResponse> snapshotResponses = new ArrayList<SnapshotResponse>();
for (Snapshot snapshot : result) {

View File

@ -89,7 +89,7 @@ public class ListTemplateOrIsoPermissionsCmd extends BaseCmd {
public void execute(){
List<String> accountNames = _mgr.listTemplatePermissions(this);
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
boolean isAdmin = ((account == null) || isAdmin(account.getType()));
TemplatePermissionsResponse response = _responseGenerator.createTemplatePermissionsResponse(accountNames, id, isAdmin);

View File

@ -123,7 +123,7 @@ public class ListTemplatesCmd extends BaseListCmd {
Set<Pair<Long, Long>> templateZonePairSet = _mgr.listTemplates(this);
boolean isAdmin = false;
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
isAdmin = true;
}

View File

@ -83,7 +83,7 @@ public class ListVpnUsersCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends VpnUser> vpnUsers = _mgr.searchForVpnUsers(this);
List<? extends VpnUser> vpnUsers = _ravService.searchForVpnUsers(this);
ListResponse<VpnUsersResponse> response = new ListResponse<VpnUsersResponse>();
List<VpnUsersResponse> vpnResponses = new ArrayList<VpnUsersResponse>();

View File

@ -68,7 +68,7 @@ public class PrepareForMaintenanceCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -75,7 +75,7 @@ public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}
@ -95,7 +95,7 @@ public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd {
@Override
public void execute(){
StoragePool result = _storageMgr.preparePrimaryStorageForMaintenance(this);
StoragePool result = _storageService.preparePrimaryStorageForMaintenance(this);
if (result != null){
StoragePoolResponse response = _responseGenerator.createStoragePoolResponse(result);
response.setResponseName("storagepool");

View File

@ -65,7 +65,7 @@ public class RebootSystemVmCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -70,7 +70,7 @@ public class ReconnectHostCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -27,7 +27,6 @@ import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
@ -82,7 +81,7 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
@ -112,17 +111,13 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd {
@Override
public void execute(){
try {
boolean result = _networkService.removeVpnUser(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove vpn user");
}
} catch (ConcurrentOperationException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
}
Account owner = getValidOwner(accountName, domainId);
boolean result = _ravService.removeVpnUser(owner.getId(), userName);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove vpn user");
}
}
}

View File

@ -67,14 +67,14 @@ public class RestartNetworkCmd extends BaseAsyncCmd {
if (accountName != null) {
return accountName;
}
return UserContext.current().getAccount().getAccountName();
return UserContext.current().getCaller().getAccountName();
}
public long getDomainId() {
if (domainId != null) {
return domainId;
}
return UserContext.current().getAccount().getDomainId();
return UserContext.current().getCaller().getDomainId();
}
public long getZoneId() {

View File

@ -128,7 +128,7 @@ public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
@ -180,7 +180,7 @@ public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd {
@Override
public void execute(){
boolean result = _securityGroupMgr.revokeSecurityGroupIngress(this);
boolean result = _securityGroupService.revokeSecurityGroupIngress(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);

View File

@ -69,7 +69,7 @@ public class StartSystemVMCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -65,7 +65,7 @@ public class StopSystemVmCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if (account != null) {
return account.getId();
}

View File

@ -67,7 +67,7 @@ public class UpdateStoragePoolCmd extends BaseCmd {
@Override
public void execute(){
StoragePool result = _storageMgr.updateStoragePool(this);
StoragePool result = _storageService.updateStoragePool(this);
if (result != null){
StoragePoolResponse response = _responseGenerator.createStoragePoolResponse(result);
response.setResponseName(getCommandName());

View File

@ -21,9 +21,6 @@ import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
public class RemoteAccessVpnResponse extends BaseResponse {
@SerializedName("id") @Param(description="the vpn ID")
private Long id;
@SerializedName("publicip") @Param(description="the public ip address of the vpn server")
private String publicIp;
@ -46,14 +43,6 @@ public class RemoteAccessVpnResponse extends BaseResponse {
return accountName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPublicIp() {
return publicIp;
}

View File

@ -20,6 +20,7 @@ package com.cloud.network;
import java.util.Date;
import com.cloud.acl.ControlledEntity;
import com.cloud.utils.net.Ip;
/**
* IpAddress represents the public ip address to be allocated in the CloudStack.
@ -46,7 +47,7 @@ public interface IpAddress extends ControlledEntity {
long getDataCenterId();
String getAddress();
Ip getAddress();
Long getAllocatedToAccountId();
@ -64,5 +65,5 @@ public interface IpAddress extends ControlledEntity {
boolean readyToUse();
Long getAssociatedNetworkId();
Long getAssociatedWithNetworkId();
}

View File

@ -19,16 +19,11 @@ package com.cloud.network;
import java.util.List;
import com.cloud.api.commands.AddVpnUserCmd;
import com.cloud.api.commands.AssociateIPAddrCmd;
import com.cloud.api.commands.CreateNetworkCmd;
import com.cloud.api.commands.CreateRemoteAccessVpnCmd;
import com.cloud.api.commands.DeleteRemoteAccessVpnCmd;
import com.cloud.api.commands.DisassociateIPAddrCmd;
import com.cloud.api.commands.ListNetworksCmd;
import com.cloud.api.commands.RemoveVpnUserCmd;
import com.cloud.api.commands.RestartNetworkCmd;
import com.cloud.exception.AccountLimitException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InvalidParameterValueException;
@ -52,37 +47,6 @@ public interface NetworkService {
IpAddress associateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException, ResourceUnavailableException;
boolean disassociateIpAddress(DisassociateIPAddrCmd cmd);
/**
* Create a remote access vpn from the given ip address and client ip range
* @param cmd the command specifying the ip address, ip range
* @return the newly created RemoteAccessVpnVO if successful, null otherwise
* @throws InvalidParameterValueException
* @throws PermissionDeniedException
* @throws ConcurrentOperationException
*/
RemoteAccessVpn createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, InvalidParameterValueException, PermissionDeniedException;
/**
* Start a remote access vpn for the given ip address and client ip range
* @param cmd the command specifying the ip address, ip range
* @return the RemoteAccessVpnVO if successful, null otherwise
* @throws ConcurrentOperationException
* @throws ResourceUnavailableException
*/
RemoteAccessVpn startRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException;
/**
* Destroy a previously created remote access VPN
* @param cmd the command specifying the account and zone
* @return success if successful, false otherwise
* @throws ConcurrentOperationException
*/
boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException;
VpnUser addVpnUser(AddVpnUserCmd cmd) throws ConcurrentOperationException, AccountLimitException;
boolean removeVpnUser(RemoveVpnUserCmd cmd) throws ConcurrentOperationException;
Network createNetwork(CreateNetworkCmd cmd) throws InvalidParameterValueException, PermissionDeniedException;
List<? extends Network> searchForNetworks(ListNetworksCmd cmd) throws InvalidParameterValueException, PermissionDeniedException;
boolean deleteNetwork(long networkId) throws InvalidParameterValueException, PermissionDeniedException;

View File

@ -18,12 +18,12 @@
package com.cloud.network;
import com.cloud.acl.ControlledEntity;
import com.cloud.dc.Vlan;
/**
* PublicIp is a combo object of IPAddressVO and VLAN information.
*/
public interface PublicIpAddress extends ControlledEntity, IpAddress{
public interface PublicIpAddress extends ControlledEntity, IpAddress, Vlan {
String getMacAddress();
@ -31,5 +31,6 @@ public interface PublicIpAddress extends ControlledEntity, IpAddress{
public String getGateway();
@Override
public String getVlanTag();
}

View File

@ -18,28 +18,12 @@
package com.cloud.network;
import com.cloud.acl.ControlledEntity;
import com.cloud.utils.net.Ip;
/**
* @author ahuang
*
*/
public interface RemoteAccessVpn extends ControlledEntity {
long getId();
String getAccountName();
String getVpnServerAddress();
void setVpnServerAddress(String vpnServerAddress);
Ip getServerAddress();
String getIpRange();
void setIpRange(String ipRange);
String getIpsecPresharedKey();
void setIpsecPresharedKey(String ipsecPresharedKey);
void setId(Long id);
void setZoneId(long zoneId);
long getZoneId();
String getLocalIp();
long getNetworkId();
}

View File

@ -19,13 +19,18 @@ package com.cloud.network;
import com.cloud.acl.ControlledEntity;
public interface VpnUser extends ControlledEntity{
public interface VpnUser extends ControlledEntity {
enum State {
Add,
Revoke,
Active
}
long getId();
String getAccountName();
String getUsername();
String getPassword();
State getState();
}

View File

@ -0,0 +1,29 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.vpn;
import java.util.List;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.network.VpnUser;
import com.cloud.utils.component.Adapter;
public interface RemoteAccessVpnElement extends Adapter {
String[] applyVpnUsers(RemoteAccessVpn vpn, List<? extends VpnUser> users);
}

View File

@ -20,18 +20,28 @@ package com.cloud.network.vpn;
import java.util.List;
import com.cloud.api.commands.ListRemoteAccessVpnsCmd;
import com.cloud.api.commands.ListVpnUsersCmd;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.network.VpnUser;
import com.cloud.utils.net.Ip;
public interface RemoteAccessVpnService {
RemoteAccessVpn createRemoteAccessVpn(long zoneId, long ownerId, String publicIp, String ipRange);
RemoteAccessVpn destroyRemoteAccessVpn(long zoneId, long ownerId);
List<? extends RemoteAccessVpn> listRemoteAccessVpns(long vpnOwnerId, long zoneId, String publicIp);
RemoteAccessVpn createRemoteAccessVpn(Ip vpnServerAddress, String ipRange) throws NetworkRuleConflictException;
void destroyRemoteAccessVpn(Ip vpnServerAddress);
List<? extends RemoteAccessVpn> listRemoteAccessVpns(long vpnOwnerId, Ip publicIp);
RemoteAccessVpn startRemoteAccessVpn(Ip vpnServerAddress) throws ConcurrentOperationException, ResourceUnavailableException;
VpnUser addVpnUser(long vpnOwnerId, String userName, String password);
VpnUser removeVpnUser(long vpnOwnerId, String userName);
boolean removeVpnUser(long vpnOwnerId, String userName);
List<? extends VpnUser> listVpnUsers(long vpnOwnerId, String userName);
boolean applyVpnUsers(long vpnOwnerId);
List<? extends RemoteAccessVpn> searchForRemoteAccessVpns(ListRemoteAccessVpnsCmd cmd);
List<? extends VpnUser> searchForVpnUsers(ListVpnUsersCmd cmd);
}

View File

@ -30,7 +30,9 @@ public interface Resource {
Reserving("Resource is being reserved right now"),
Reserved("Resource has been reserved."),
Releasing("Resource is being released"),
Ready("Resource is ready which means it doesn't need to go through resservation");
Ready("Resource is ready which means it doesn't need to go through resservation"),
Deallocating("Resource is being deallocated"),
Free("Resource is now completely free");
String _description;

View File

@ -49,7 +49,6 @@ import com.cloud.api.commands.ListIsosCmd;
import com.cloud.api.commands.ListPodsByCmd;
import com.cloud.api.commands.ListPreallocatedLunsCmd;
import com.cloud.api.commands.ListPublicIpAddressesCmd;
import com.cloud.api.commands.ListRemoteAccessVpnsCmd;
import com.cloud.api.commands.ListRoutersCmd;
import com.cloud.api.commands.ListServiceOfferingsCmd;
import com.cloud.api.commands.ListStoragePoolsCmd;
@ -61,7 +60,6 @@ import com.cloud.api.commands.ListVMGroupsCmd;
import com.cloud.api.commands.ListVMsCmd;
import com.cloud.api.commands.ListVlanIpRangesCmd;
import com.cloud.api.commands.ListVolumesCmd;
import com.cloud.api.commands.ListVpnUsersCmd;
import com.cloud.api.commands.ListZonesByCmd;
import com.cloud.api.commands.RebootSystemVmCmd;
import com.cloud.api.commands.RegisterCmd;
@ -88,8 +86,6 @@ import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.host.Host;
import com.cloud.network.IpAddress;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.network.VpnUser;
import com.cloud.network.router.VirtualRouter;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.ServiceOffering;
@ -385,10 +381,6 @@ public interface ManagementService {
*/
String uploadCertificate(UploadCustomCertificateCmd cmd);
public List<? extends RemoteAccessVpn> searchForRemoteAccessVpns(ListRemoteAccessVpnsCmd cmd);
public List<? extends VpnUser> searchForVpnUsers(ListVpnUsersCmd cmd);
String getVersion();
/**

View File

@ -49,14 +49,8 @@ public interface Account extends ControlledEntity {
public long getId();
public String getAccountName();
public void setAccountName(String accountId);
public short getType();
public String getState();
public void setState(String state);
@Override
public long getDomainId();
public State getState();
public Date getRemoved();
public String getNetworkDomain();
public void setNetworkDomain(String networkDomain);
}

View File

@ -23,7 +23,7 @@ import java.util.Date;
public interface User extends OwnedBy {
public static final long UID_SYSTEM = 1;
public Long getId();
public long getId();
public Date getCreated();
@ -51,9 +51,9 @@ public interface User extends OwnedBy {
public void setEmail(String email);
public String getState();
public Account.State getState();
public void setState(String state);
public void setState(Account.State state);
public String getApiKey();

View File

@ -46,11 +46,11 @@ public class UserContext {
this.apiServer = apiServer;
}
public long getUserId() {
public long getCallerUserId() {
return userId;
}
public void setUserId(long userId) {
public void setCallerUserId(long userId) {
this.userId = userId;
}
@ -58,11 +58,11 @@ public class UserContext {
return sessionId;
}
public Account getAccount() {
public Account getCaller() {
return account;
}
public void setAccount(Account accountObject) {
public void setCaller(Account accountObject) {
this.account = accountObject;
}
@ -90,8 +90,8 @@ public class UserContext {
UserContext context = current();
assert(context != null) : "Context should be already setup before you can call this one";
context.setUserId(userId);
context.setAccount(accountObject);
context.setCallerUserId(userId);
context.setCaller(accountObject);
context.setSessionKey(sessionId);
}

View File

@ -19,7 +19,7 @@
package com.cloud.agent.api.routing;
public class DhcpEntryCommand extends RoutingCommand {
public class DhcpEntryCommand extends NetworkElementCommand {
String vmMac;
String vmIpAddress;

View File

@ -23,7 +23,7 @@ import com.cloud.network.LoadBalancerConfigurator;
* @author chiradeep
*
*/
public class LoadBalancerCfgCommand extends RoutingCommand {
public class LoadBalancerCfgCommand extends NetworkElementCommand {
private String [] config;
private String [] addFwRules;
private String [] removeFwRules;;

View File

@ -19,9 +19,8 @@
package com.cloud.agent.api.routing;
public class RemoteAccessVpnCfgCommand extends RoutingCommand {
public class RemoteAccessVpnCfgCommand extends NetworkElementCommand {
String vpnAppliancePrivateIpAddress; //router private ip address typically
boolean create;
String vpnServerIp;
String ipRange;
@ -42,8 +41,7 @@ public class RemoteAccessVpnCfgCommand extends RoutingCommand {
}
public RemoteAccessVpnCfgCommand(boolean create, String routerPrivateIp, String vpnServerAddress, String localIp, String ipRange, String ipsecPresharedKey) {
this.vpnAppliancePrivateIpAddress = routerPrivateIp;
public RemoteAccessVpnCfgCommand(boolean create, String vpnServerAddress, String localIp, String ipRange, String ipsecPresharedKey) {
this.vpnServerIp = vpnServerAddress;
this.ipRange = ipRange;
this.presharedKey = ipsecPresharedKey;
@ -79,12 +77,4 @@ public class RemoteAccessVpnCfgCommand extends RoutingCommand {
return localIp;
}
public String getVpnAppliancePrivateIpAddress() {
return vpnAppliancePrivateIpAddress;
}
public String getRouterPrivateIpAddress() {
return vpnAppliancePrivateIpAddress;
}
}

View File

@ -19,7 +19,7 @@
package com.cloud.agent.api.routing;
public class SavePasswordCommand extends RoutingCommand {
public class SavePasswordCommand extends NetworkElementCommand {
String password;
String vmIpAddress;

View File

@ -19,7 +19,7 @@
package com.cloud.agent.api.routing;
public class UserDataCommand extends RoutingCommand {
public class UserDataCommand extends NetworkElementCommand {
String userData;
String vmIpAddress;

View File

@ -21,7 +21,7 @@ package com.cloud.agent.api.routing;
import java.util.ArrayList;
import java.util.List;
public class VmDataCommand extends RoutingCommand {
public class VmDataCommand extends NetworkElementCommand {
String routerPrivateIpAddress;
String vmIpAddress;

View File

@ -22,7 +22,7 @@ import java.util.List;
import com.cloud.network.VpnUserVO;
public class VpnUsersCfgCommand extends RoutingCommand {
public class VpnUsersCfgCommand extends NetworkElementCommand {
public static class UsernamePassword{
private String username;
private String password;
@ -64,15 +64,13 @@ public class VpnUsersCfgCommand extends RoutingCommand {
return getUsername() + "," + getPassword();
}
}
String vpnAppliancePrivateIpAddress; //router private ip address typically
UsernamePassword [] userpwds;
protected VpnUsersCfgCommand() {
}
public VpnUsersCfgCommand(String routerIp, List<VpnUserVO> addUsers, List<VpnUserVO> removeUsers) {
this.vpnAppliancePrivateIpAddress = routerIp;
public VpnUsersCfgCommand(List<VpnUserVO> addUsers, List<VpnUserVO> removeUsers) {
userpwds = new UsernamePassword[addUsers.size() + removeUsers.size()];
int i = 0;
for (VpnUserVO vpnUser: removeUsers) {
@ -92,11 +90,4 @@ public class VpnUsersCfgCommand extends RoutingCommand {
return userpwds;
}
public String getVpnAppliancePrivateIpAddress() {
return vpnAppliancePrivateIpAddress;
}
public String getRouterPrivateIpAddress() {
return vpnAppliancePrivateIpAddress;
}
}

View File

@ -48,7 +48,7 @@ import com.cloud.agent.api.routing.DhcpEntryCommand;
import com.cloud.agent.api.routing.IPAssocCommand;
import com.cloud.agent.api.routing.IpAssocAnswer;
import com.cloud.agent.api.routing.LoadBalancerCfgCommand;
import com.cloud.agent.api.routing.RoutingCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
import com.cloud.agent.api.routing.SavePasswordCommand;
import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer;
@ -123,8 +123,8 @@ public class VirtualRoutingResource implements Manager {
}
private Answer execute(SetPortForwardingRulesCommand cmd) {
String routerIp = cmd.getAccessDetail(RoutingCommand.ROUTER_IP);
String routerName = cmd.getAccessDetail(RoutingCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String[] results = new String[cmd.getRules().length];
int i = 0;
@ -147,7 +147,7 @@ public class VirtualRoutingResource implements Manager {
}
private Answer execute(LoadBalancerConfigCommand cmd) {
String routerIp = cmd.getAccessDetail(RoutingCommand.ROUTER_IP);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
File tmpCfgFile = null;
try {
String cfgFilePath = "";
@ -277,8 +277,8 @@ public class VirtualRoutingResource implements Manager {
String[] results = new String[cmd.getIpAddresses().length];
int i = 0;
String result = null;
String routerName = cmd.getAccessDetail(RoutingCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(RoutingCommand.ROUTER_IP);
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
for (IpAddressTO ip : ips) {
result = assignPublicIpAddress(routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.getVlanNetmask());
if (result != null) {

View File

@ -25,16 +25,12 @@ import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import com.cloud.utils.db.GenericDao;
@Entity
@Table(name="usage_event")
@SecondaryTable(name="account",
pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")})
public class UsageEventVO implements UsageEvent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@ -91,7 +87,8 @@ public class UsageEventVO implements UsageEvent {
this.resourceName = resourceName;
}
public long getId() {
@Override
public long getId() {
return id;
}
@Override

View File

@ -127,7 +127,7 @@ import com.cloud.agent.api.routing.IpAssocAnswer;
import com.cloud.agent.api.routing.LoadBalancerCfgCommand;
import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand;
import com.cloud.agent.api.routing.RoutingCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.SavePasswordCommand;
import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer;
import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
@ -944,8 +944,8 @@ public abstract class CitrixResourceBase implements ServerResource {
protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesCommand cmd) {
Connection conn = getConnection();
String args;
String routerName = cmd.getAccessDetail(RoutingCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(RoutingCommand.ROUTER_IP);
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String[] results = new String[cmd.getRules().length];
int i = 0;
for (PortForwardingRuleTO rule : cmd.getRules()) {
@ -1046,7 +1046,7 @@ public abstract class CitrixResourceBase implements ServerResource {
protected Answer execute(final LoadBalancerConfigCommand cmd) {
Connection conn = getConnection();
String routerIp = cmd.getAccessDetail(RoutingCommand.ROUTER_IP);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
if (routerIp == null) {
return new Answer(cmd);
@ -1119,7 +1119,7 @@ public abstract class CitrixResourceBase implements ServerResource {
protected synchronized Answer execute(final RemoteAccessVpnCfgCommand cmd) {
Connection conn = getConnection();
String args = cmd.getRouterPrivateIpAddress();
String args = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
if (cmd.isCreate()) {
args += " -r " + cmd.getIpRange();
args += " -p " + cmd.getPresharedKey();
@ -1141,7 +1141,7 @@ public abstract class CitrixResourceBase implements ServerResource {
protected synchronized Answer execute(final VpnUsersCfgCommand cmd) {
Connection conn = getConnection();
for (VpnUsersCfgCommand.UsernamePassword userpwd: cmd.getUserpwds()) {
String args = cmd.getRouterPrivateIpAddress();
String args = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
if (!userpwd.isAdd()) {
args += " -U " + userpwd.getUsername();
} else {
@ -1333,8 +1333,8 @@ public abstract class CitrixResourceBase implements ServerResource {
Connection conn = getConnection();
String[] results = new String[cmd.getIpAddresses().length];
int i = 0;
String routerName = cmd.getAccessDetail(RoutingCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(RoutingCommand.ROUTER_IP);
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
try {
IpAddressTO[] ips = cmd.getIpAddresses();
for (IpAddressTO ip : ips) {

View File

@ -20,37 +20,36 @@ package com.cloud.network;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
@Entity
@Table(name=("vpn_users"))
@SecondaryTable(name="account",
pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")})
public class VpnUserVO implements VpnUser {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="account_id")
@Column(name="owner_id")
private long accountId;
@Column(name="account_name", table="account", insertable=false, updatable=false)
private String accountName = null;
@Column(name="domain_id", table="account", insertable=false, updatable=false)
@Column(name="domain_id")
private long domainId;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
private String password;
@Column(name="state")
@Enumerated(value=EnumType.STRING)
private State state;
public VpnUserVO() { }
@ -58,6 +57,7 @@ public class VpnUserVO implements VpnUser {
this.accountId = accountId;
this.username = userName;
this.password = password;
this.state = State.Add;
}
@Override
@ -70,11 +70,6 @@ public class VpnUserVO implements VpnUser {
return accountId;
}
@Override
public String getAccountName() {
return accountName;
}
@Override
public String getUsername() {
return username;
@ -88,20 +83,28 @@ public class VpnUserVO implements VpnUser {
public String getPassword() {
return password;
}
@Override
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public void setPassword(String password) {
this.password = password;
}
public void setId(Long id) {
this.id = id;
}
@Override
public long getDomainId() {
return domainId;
}
@Override
public String toString() {
return new StringBuilder("VpnUser[").append(id).append("-").append(username).append("-").append(accountId).append("]").toString();
}
}

View File

@ -22,6 +22,8 @@ import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@ -46,8 +48,9 @@ public class AccountVO implements Account {
@Column(name="domain_id")
private long domainId;
@Column(name="state")
private String state;
@Column(name="state")
@Enumerated(value=EnumType.STRING)
private State state;
@Column(name=GenericDao.REMOVED_COLUMN)
private Date removed;
@ -80,15 +83,17 @@ public class AccountVO implements Account {
@Override
public String getAccountName() {
return accountName;
}
@Override
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
}
@Override
public short getType() {
return type;
}
}
public void setType(short type) {
this.type = type;
}
@ -103,11 +108,11 @@ public class AccountVO implements Account {
}
@Override
public String getState() {
public State getState() {
return state;
}
@Override
public void setState(String state) {
}
public void setState(State state) {
this.state = state;
}
@ -119,7 +124,7 @@ public class AccountVO implements Account {
public String getNetworkDomain() {
return networkDomain;
}
@Override
public void setNetworkDomain(String networkDomain) {
this.networkDomain = networkDomain;
}
@ -131,6 +136,6 @@ public class AccountVO implements Account {
@Override
public String toString() {
return new StringBuilder("Acct:").append(id).append(":").append(accountName).toString();
return new StringBuilder("Acct[").append(id).append("-").append(accountName).append("]").toString();
}
}

View File

@ -16,180 +16,197 @@
*
*/
package com.cloud.user;
package com.cloud.user;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.cloud.user.Account.State;
import com.cloud.utils.db.GenericDao;
/**
* A bean representing a user
*
* @author Will Chan
*
*/
@Entity
@Table(name="user")
public class UserVO implements User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id = null;
@Column(name="username")
private String username = null;
@Column(name="password")
private String password = null;
@Column(name="firstname")
private String firstname = null;
@Column(name="lastname")
private String lastname = null;
@Column(name="account_id")
private long accountId;
@Column(name="email")
private String email = null;
@Column(name="state")
private String state;
@Column(name="api_key")
private String apiKey = null;
@Column(name="secret_key")
private String secretKey = null;
@Column(name=GenericDao.CREATED_COLUMN)
private Date created;
@Column(name=GenericDao.REMOVED_COLUMN)
private Date removed;
@Column(name="timezone")
/**
* A bean representing a user
*
* @author Will Chan
*
*/
@Entity
@Table(name = "user")
public class UserVO implements User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "username")
private String username = null;
@Column(name = "password")
private String password = null;
@Column(name = "firstname")
private String firstname = null;
@Column(name = "lastname")
private String lastname = null;
@Column(name = "account_id")
private long accountId;
@Column(name = "email")
private String email = null;
@Column(name = "state")
@Enumerated(value=EnumType.STRING)
private State state;
@Column(name = "api_key")
private String apiKey = null;
@Column(name = "secret_key")
private String secretKey = null;
@Column(name = GenericDao.CREATED_COLUMN)
private Date created;
@Column(name = GenericDao.REMOVED_COLUMN)
private Date removed;
@Column(name = "timezone")
private String timezone;
public UserVO() {}
public UserVO(Long id) {
this.id = id;
}
@Override
public Long getId() {
return id;
}
@Override
public Date getCreated() {
return created;
}
@Override
public Date getRemoved() {
return removed;
}
@Override
public String getUsername() {
return username;
}
@Override
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return password;
}
@Override
public void setPassword(String password) {
this.password = password;
}
@Override
public String getFirstname() {
return firstname;
}
@Override
public void setFirstname(String firstname) {
this.firstname = firstname;
}
@Override
public String getLastname() {
return lastname;
}
@Override
public void setLastname(String lastname) {
this.lastname = lastname;
}
@Override
public long getAccountId() {
return accountId;
}
@Override
public void setAccountId(long accountId) {
this.accountId = accountId;
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String email) {
this.email = email;
}
@Override
public String getState() {
return state;
}
@Override
public void setState(String state) {
this.state = state;
}
@Override
public String getApiKey() {
return apiKey;
}
@Override
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
@Override
public String getSecretKey() {
return secretKey;
}
@Override
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
public UserVO() {
}
@Override
public String getTimezone()
{
return timezone;
}
@Override
public void setTimezone(String timezone)
{
this.timezone = timezone;
public UserVO(long id) {
this.id = id;
}
@Override
public long getId() {
return id;
}
@Override
public Date getCreated() {
return created;
}
@Override
public Date getRemoved() {
return removed;
}
@Override
public String getUsername() {
return username;
}
@Override
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return password;
}
@Override
public void setPassword(String password) {
this.password = password;
}
@Override
public String getFirstname() {
return firstname;
}
@Override
public void setFirstname(String firstname) {
this.firstname = firstname;
}
@Override
public String getLastname() {
return lastname;
}
@Override
public void setLastname(String lastname) {
this.lastname = lastname;
}
@Override
public long getAccountId() {
return accountId;
}
@Override
public void setAccountId(long accountId) {
this.accountId = accountId;
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String email) {
this.email = email;
}
@Override
public State getState() {
return state;
}
@Override
public void setState(State state) {
this.state = state;
}
@Override
public String getApiKey() {
return apiKey;
}
@Override
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
@Override
public String getSecretKey() {
return secretKey;
}
@Override
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
@Override
public String getTimezone() {
return timezone;
}
@Override
public void setTimezone(String timezone) {
this.timezone = timezone;
}
@Transient
String toString = null;
@Override
public String toString() {
if (toString == null) {
toString = new StringBuilder("User:").append(id).append(":").append(username).toString();
}
return toString;
}
}
return new StringBuilder("User[").append(id).append("-").append(username).append("]").toString();
}
}

View File

@ -49,7 +49,7 @@ public class DomainChecker extends AdapterBase implements SecurityChecker {
@Override
public boolean checkAccess(Account account, Domain domain) throws PermissionDeniedException {
if (!account.getState().equals(Account.ACCOUNT_STATE_ENABLED)) {
if (account.getState() != Account.State.Enabled) {
throw new PermissionDeniedException(account + " is disabled.");
}
@ -136,10 +136,11 @@ public class DomainChecker extends AdapterBase implements SecurityChecker {
//found as a child
return true;
}
if(domainRecord.getParent() != null)
domainRecord = _domainDao.findById(domainRecord.getParent());
else
break;
if(domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
} else {
break;
}
}
}
}
@ -183,10 +184,11 @@ public class DomainChecker extends AdapterBase implements SecurityChecker {
//found as a child
return true;
}
if(domainRecord.getParent() != null)
domainRecord = _domainDao.findById(domainRecord.getParent());
else
break;
if(domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
} else {
break;
}
}
}
}
@ -219,10 +221,11 @@ public class DomainChecker extends AdapterBase implements SecurityChecker {
//found as a child
return true;
}
if(domainRecord.getParent() != null)
domainRecord = _domainDao.findById(domainRecord.getParent());
else
break;
if(domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
} else {
break;
}
}
}
}
@ -245,10 +248,11 @@ public class DomainChecker extends AdapterBase implements SecurityChecker {
//found as a child
return true;
}
if(localRecord.getParent() != null)
localRecord = _domainDao.findById(localRecord.getParent());
else
break;
if(localRecord.getParent() != null) {
localRecord = _domainDao.findById(localRecord.getParent());
} else {
break;
}
}
}
//didn't find in upper tree

View File

@ -32,10 +32,10 @@ import com.cloud.network.LoadBalancerVO;
import com.cloud.network.Network;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Service;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkRuleConfigVO;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.LoadBalancerDao;
import com.cloud.network.dao.NetworkDao;
@ -85,6 +85,7 @@ import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.DateUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.net.Ip;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.InstanceGroupVO;
import com.cloud.vm.Nic;
@ -338,7 +339,7 @@ public class ApiDBUtils {
}
public static IPAddressVO findIpAddressById(String address) {
return _ipAddressDao.findById(address);
return _ipAddressDao.findById(new Ip(address));
}
public static GuestOSCategoryVO getHostGuestOSCategory(long hostId) {
@ -419,19 +420,6 @@ public class ApiDBUtils {
return _userVmDao.findById(vmId);
}
public static UserVm findUserVmByPublicIpAndGuestIp(String publicIp, String guestIp) {
IPAddressVO addr = _ipAddressDao.findById(publicIp);
List<UserVmVO> vms = _userVmDao.listVmsUsingGuestIpAddress(addr.getDataCenterId(), guestIp);
if (vms != null) {
for (UserVmVO vm : vms) {
if (vm.getAccountId() == addr.getAllocatedToAccountId()) {
return vm;
}
}
}
return null;
}
public static VlanVO findVlanById(long vlanDbId) {
return _vlanDao.findById(vlanDbId);
}

View File

@ -107,17 +107,19 @@ public class ApiDispatcher {
} else if (t instanceof ServerApiException) {
s_logger.warn(t.getClass() + " : " + ((ServerApiException) t).getDescription());
errorMsg = ((ServerApiException) t).getDescription();
if (UserContext.current().getAccount().getType() == Account.ACCOUNT_TYPE_ADMIN)
if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage());
else
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
}
} else {
errorMsg = "Internal error";
s_logger.error("Exception while executing " + cmd.getClass().getSimpleName() + ":", t);
if (UserContext.current().getAccount().getType() == Account.ACCOUNT_TYPE_ADMIN)
if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage());
else
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
}
}
} finally {
if(cmd.getCreateEventType() != null){
@ -170,17 +172,19 @@ public class ApiDispatcher {
} else if (t instanceof ServerApiException) {
errorMsg = ((ServerApiException) t).getDescription();
s_logger.warn(t.getClass() + " : " + ((ServerApiException) t).getDescription());
if (UserContext.current().getAccount().getType() == Account.ACCOUNT_TYPE_ADMIN)
if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage());
else
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
}
} else {
errorMsg = "Internal error";
s_logger.error("Exception while executing " + cmd.getClass().getSimpleName() + ":", t);
if (UserContext.current().getAccount().getType() == Account.ACCOUNT_TYPE_ADMIN)
if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage());
else
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
}
}
} finally {
if(cmd instanceof BaseAsyncCmd){

View File

@ -197,7 +197,7 @@ public class ApiResponseHelper implements ResponseGenerator {
userResponse.setFirstname(user.getFirstname());
userResponse.setId(user.getId());
userResponse.setLastname(user.getLastname());
userResponse.setState(user.getState());
userResponse.setState(user.getState().toString());
userResponse.setTimezone(user.getTimezone());
userResponse.setUsername(user.getUsername());
userResponse.setApiKey(user.getApiKey());
@ -222,7 +222,7 @@ public class ApiResponseHelper implements ResponseGenerator {
accountResponse.setAccountType(account.getType());
accountResponse.setDomainId(account.getDomainId());
accountResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName());
accountResponse.setState(account.getState());
accountResponse.setState(account.getState().toString());
// get network stat
List<UserStatisticsVO> stats = ApiDBUtils.listUserStatsBy(account.getId());
@ -597,7 +597,7 @@ public class ApiResponseHelper implements ResponseGenerator {
long zoneId = ipAddress.getDataCenterId();
IPAddressResponse ipResponse = new IPAddressResponse();
ipResponse.setIpAddress(ipAddress.getAddress());
ipResponse.setIpAddress(ipAddress.getAddress().toString());
if (ipAddress.getAllocatedTime() != null) {
ipResponse.setAllocated(ipAddress.getAllocatedTime());
}
@ -616,10 +616,10 @@ public class ApiResponseHelper implements ResponseGenerator {
ipResponse.setForVirtualNetwork(forVirtualNetworks);
ipResponse.setStaticNat(ipAddress.isOneToOneNat());
ipResponse.setAssociatedNetworkId(ipAddress.getAssociatedNetworkId());
ipResponse.setAssociatedNetworkId(ipAddress.getAssociatedWithNetworkId());
//Network id the ip is associated withif associated networkId is null, try to get this information from vlan
Long associatedNetworkId = ipAddress.getAssociatedNetworkId();
Long associatedNetworkId = ipAddress.getAssociatedWithNetworkId();
Long vlanNetworkId = ApiDBUtils.getVlanNetworkId(ipAddress.getVlanId());
if (associatedNetworkId == null) {
associatedNetworkId = vlanNetworkId;
@ -638,7 +638,7 @@ public class ApiResponseHelper implements ResponseGenerator {
ipResponse.setNetworkId(networkId);
// show this info to admin only
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
ipResponse.setVlanId(ipAddress.getVlanId());
ipResponse.setVlanName(ApiDBUtils.findVlanById(ipAddress.getVlanId()).getVlanTag());
@ -698,7 +698,7 @@ public class ApiResponseHelper implements ResponseGenerator {
@Override
public ZoneResponse createZoneResponse(DataCenter dataCenter) {
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
ZoneResponse zoneResponse = new ZoneResponse();
zoneResponse.setId(dataCenter.getId());
zoneResponse.setName(dataCenter.getName());
@ -996,7 +996,7 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setZoneId(userVm.getDataCenterId());
userVmResponse.setZoneName(ApiDBUtils.findZoneById(userVm.getDataCenterId()).getName());
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
// if user is an admin, display host id
if (((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) {
userVmResponse.setHostId(userVm.getHostId());
@ -1264,10 +1264,10 @@ public class ApiResponseHelper implements ResponseGenerator {
VpnUsersResponse vpnResponse = new VpnUsersResponse();
vpnResponse.setId(vpnUser.getId());
vpnResponse.setUserName(vpnUser.getUsername());
vpnResponse.setAccountName(vpnUser.getAccountName());
Account accountTemp = ApiDBUtils.findAccountById(vpnUser.getAccountId());
if (accountTemp != null) {
vpnResponse.setAccountName(accountTemp.getAccountName());
vpnResponse.setDomainId(accountTemp.getDomainId());
vpnResponse.setDomainName(ApiDBUtils.findDomainById(accountTemp.getDomainId()).getName());
}
@ -1279,15 +1279,14 @@ public class ApiResponseHelper implements ResponseGenerator {
@Override
public RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn) {
RemoteAccessVpnResponse vpnResponse = new RemoteAccessVpnResponse();
vpnResponse.setId(vpn.getId());
vpnResponse.setPublicIp(vpn.getVpnServerAddress());
vpnResponse.setPublicIp(vpn.getServerAddress().toString());
vpnResponse.setIpRange(vpn.getIpRange());
vpnResponse.setPresharedKey(vpn.getIpsecPresharedKey());
vpnResponse.setAccountName(vpn.getAccountName());
vpnResponse.setDomainId(vpn.getDomainId());
Account accountTemp = ApiDBUtils.findAccountById(vpn.getAccountId());
if (accountTemp != null) {
vpnResponse.setDomainId(accountTemp.getDomainId());
vpnResponse.setAccountName(accountTemp.getAccountName());
vpnResponse.setDomainName(ApiDBUtils.findDomainById(accountTemp.getDomainId()).getName());
}
@ -1636,7 +1635,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
//set status
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
boolean isAdmin = false;
if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
isAdmin = true;
@ -1708,7 +1707,7 @@ public class ApiResponseHelper implements ResponseGenerator {
}
//set status
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
boolean isAdmin = false;
if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
isAdmin = true;
@ -1868,7 +1867,9 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setResponses(isoResponses);
if(isBootable != null && !isBootable)
continue; //fetch only non-bootable isos and return (for now only xen tools iso)
{
continue; //fetch only non-bootable isos and return (for now only xen tools iso)
}
}
List<VMTemplateHostVO> isoHosts = ApiDBUtils.listTemplateHostBy(iso.getId(), isoZonePair.second());

View File

@ -381,8 +381,8 @@ public class ApiServer implements HttpRequestHandler {
private String queueCommand(BaseCmd cmdObj, Map<String, String> params) {
UserContext ctx = UserContext.current();
Long userId = ctx.getUserId();
Account account = ctx.getAccount();
Long userId = ctx.getCallerUserId();
Account account = ctx.getCaller();
if (cmdObj instanceof BaseAsyncCmd) {
Long objectId = null;
if (cmdObj instanceof BaseAsyncCreateCmd) {
@ -416,7 +416,7 @@ public class ApiServer implements HttpRequestHandler {
job.setInstanceType(asyncCmd.getInstanceType());
job.setUserId(userId);
if (account != null) {
job.setAccountId(ctx.getAccount().getId());
job.setAccountId(ctx.getCaller().getId());
} else {
// Just have SYSTEM own the job for now. Users won't be able to see this job,
// but in an admin case (like domain admin) they won't be able to see it anyway
@ -461,7 +461,9 @@ public class ApiServer implements HttpRequestHandler {
// Using maps might possibly be more efficient if the set is large enough but for now, we'll just do a
// comparison of two lists. Either way, there shouldn't be too many async jobs active for the account.
for (AsyncJob job : jobs) {
if (job.getInstanceId() == null) continue;
if (job.getInstanceId() == null) {
continue;
}
for (ResponseObject response : responses) {
if (response.getObjectId() != null && job.getInstanceId().longValue() == response.getObjectId().longValue()) {
response.setJobId(job.getId());
@ -473,7 +475,9 @@ public class ApiServer implements HttpRequestHandler {
}
private void buildAuditTrail(StringBuffer auditTrailSb, String command, String result) {
if (result == null) return;
if (result == null) {
return;
}
auditTrailSb.append(" " + HttpServletResponse.SC_OK + " ");
auditTrailSb.append(result);
/*
@ -594,7 +598,7 @@ public class ApiServer implements HttpRequestHandler {
user = userAcctPair.first();
Account account = userAcctPair.second();
if (!user.getState().equals(Account.ACCOUNT_STATE_ENABLED) || !account.getState().equals(Account.ACCOUNT_STATE_ENABLED)) {
if (user.getState() != Account.State.Enabled || !account.getState().equals(Account.State.Enabled)) {
s_logger.info("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState());
return false;
}
@ -668,16 +672,19 @@ public class ApiServer implements HttpRequestHandler {
Account account = _ms.findAccountById(userAcct.getAccountId());
String hypervisorType = _ms.getConfigurationValue("hypervisor.type");
if (hypervisorType == null)
hypervisorType = "kvm";
if (hypervisorType == null) {
hypervisorType = "kvm";
}
String directAttachSecurityGroupsEnabled = _ms.getConfigurationValue("direct.attach.security.groups.enabled");
if(directAttachSecurityGroupsEnabled == null)
directAttachSecurityGroupsEnabled = "false";
if(directAttachSecurityGroupsEnabled == null) {
directAttachSecurityGroupsEnabled = "false";
}
String systemVmUseLocalStorage = _ms.getConfigurationValue("system.vm.use.local.storage");
if (systemVmUseLocalStorage == null)
systemVmUseLocalStorage = "false";
if (systemVmUseLocalStorage == null) {
systemVmUseLocalStorage = "false";
}
// set the userId and account object for everyone
session.setAttribute("userid", userAcct.getId());
@ -722,7 +729,7 @@ public class ApiServer implements HttpRequestHandler {
account = _ms.findAccountById(user.getAccountId());
}
if ((user == null) || (user.getRemoved() != null) || !user.getState().equals(Account.ACCOUNT_STATE_ENABLED) || (account == null) || !account.getState().equals(Account.ACCOUNT_STATE_ENABLED)) {
if ((user == null) || (user.getRemoved() != null) || !user.getState().equals(Account.State.Enabled) || (account == null) || !account.getState().equals(Account.State.Enabled)) {
s_logger.warn("Deleted/Disabled/Locked user with id=" + userId + " attempting to access public API");
return false;
}
@ -864,9 +871,13 @@ public class ApiServer implements HttpRequestHandler {
}
}
} catch (ConnectionClosedException ex) {
if (s_logger.isTraceEnabled()) s_logger.trace("ApiServer: Client closed connection");
if (s_logger.isTraceEnabled()) {
s_logger.trace("ApiServer: Client closed connection");
}
} catch (IOException ex) {
if (s_logger.isTraceEnabled()) s_logger.trace("ApiServer: IOException - " + ex);
if (s_logger.isTraceEnabled()) {
s_logger.trace("ApiServer: IOException - " + ex);
}
} catch (HttpException ex) {
s_logger.warn("ApiServer: Unrecoverable HTTP protocol violation" + ex);
} finally {

View File

@ -254,7 +254,7 @@ public class ApiServlet extends HttpServlet {
updateUserContext(params, session != null ? session.getId() : null);
*/
auditTrailSb.insert(0, "(userId="+UserContext.current().getUserId()+ " accountId="+UserContext.current().getAccount().getId()+ " sessionId="+(session != null ? session.getId() : null)+ ")" );
auditTrailSb.insert(0, "(userId="+UserContext.current().getCallerUserId()+ " accountId="+UserContext.current().getCaller().getId()+ " sessionId="+(session != null ? session.getId() : null)+ ")" );
try {
String response = _apiServer.handleRequest(params, true, responseType, auditTrailSb);

View File

@ -27,7 +27,6 @@ import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.async.SyncQueueItemVO;
import com.cloud.serializer.GsonHelper;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account;
@ -40,7 +39,8 @@ import com.google.gson.Gson;
public class DisableUserExecutor extends BaseAsyncJobExecutor {
public static final Logger s_logger = Logger.getLogger(DisableUserExecutor.class.getName());
public boolean execute() {
@Override
public boolean execute() {
Gson gson = GsonHelper.getBuilder().create();
AsyncJobManager asyncMgr = getAsyncJobMgr();
AsyncJobVO job = getJob();
@ -84,8 +84,9 @@ public class DisableUserExecutor extends BaseAsyncJobExecutor {
AsyncJobManager asyncMgr = getAsyncJobMgr();
UserVO user = asyncMgr.getExecutorContext().getUserDao().findById(userId);
if(user == null) {
if(s_logger.isInfoEnabled())
s_logger.info("User " + userId + " does not exist");
if(s_logger.isInfoEnabled()) {
s_logger.info("User " + userId + " does not exist");
}
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR,
"User " + userId + " does not exist");
@ -129,7 +130,7 @@ public class DisableUserExecutor extends BaseAsyncJobExecutor {
List<UserVO> allUsersByAccount = asyncMgr.getExecutorContext().getUserDao().listByAccount(user.getAccountId());
for (UserVO oneUser : allUsersByAccount) {
if (oneUser.getState().equals(Account.ACCOUNT_STATE_ENABLED)) {
if (oneUser.getState().equals(Account.State.Enabled)) {
return false;
}
}
@ -149,8 +150,9 @@ public class DisableUserExecutor extends BaseAsyncJobExecutor {
asyncMgr.updateAsyncJobStatus(job.getId(), routers.size(), "");
for(DomainRouterVO router : routers) {
if(s_logger.isInfoEnabled())
s_logger.info("Serialize DisableUser operation with previous activities on router " + router.getId());
if(s_logger.isInfoEnabled()) {
s_logger.info("Serialize DisableUser operation with previous activities on router " + router.getId());
}
asyncMgr.syncAsyncJobExecution(job, "Router", router.getId());
}

View File

@ -1,112 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.async.executor;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.network.IPAddressVO;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.serializer.GsonHelper;
import com.cloud.server.ManagementServer;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.dao.DomainRouterDao;
import com.google.gson.Gson;
public class DisassociateIpAddressExecutor extends BaseAsyncJobExecutor {
public static final Logger s_logger = Logger.getLogger(DisassociateIpAddressExecutor.class.getName());
public boolean execute() {
Gson gson = GsonHelper.getBuilder().create();
AsyncJobManager asyncMgr = getAsyncJobMgr();
AsyncJobVO job = getJob();
ManagementServer managementServer = asyncMgr.getExecutorContext().getManagementServer();
DisassociateIpAddressParam param = gson.fromJson(job.getCmdInfo(), DisassociateIpAddressParam.class);
/*
if(getSyncSource() == null) {
DomainRouterVO router = getRouterSyncSource(param);
if(router == null) {
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED,
BaseCmd.NET_INVALID_PARAM_ERROR, "Unable to find router with given user " + param.getUserId() + " and ip "
+ param.getIpAddress() + " to disassociate");
} else {
asyncMgr.syncAsyncJobExecution(job.getId(), "Router", router.getId());
}
return true;
} else {
try {
if(s_logger.isDebugEnabled())
s_logger.debug("Executing disassociateIpAddress, uid: " + param.getUserId() + ", account id: "
+ param.getAccountId() + ", ip: " + param.getIpAddress());
boolean result = managementServer.disassociateIpAddress(param.getUserId(),
param.getAccountId(), param.getIpAddress());
if(result) {
if(s_logger.isDebugEnabled())
s_logger.debug("disassociateIpAddress executed successfully, complete async-execution");
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, "success");
} else {
s_logger.warn("disassociateIpAddress execution failed, complete async-execution");
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "failed");
}
} catch (PermissionDeniedException e) {
s_logger.warn("disassociateIpAddress execution failed : PermissionDeniedException, complete async-execution", e);
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.PARAM_ERROR, e.getMessage());
} catch(IllegalArgumentException e) {
s_logger.warn("disassociateIpAddress execution failed : IllegalArgumentException, complete async-execution", e);
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.PARAM_ERROR, e.getMessage());
} catch(Exception e) {
s_logger.warn("disassociateIpAddress execution failed : Exception, complete async-execution", e);
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.PARAM_ERROR, e.getMessage());
}
}
*/
return true;
}
private DomainRouterVO getRouterSyncSource(DisassociateIpAddressParam param) {
IPAddressDao ipAddressDao = getAsyncJobMgr().getExecutorContext().getIpAddressDao();
DomainRouterDao routerDao = getAsyncJobMgr().getExecutorContext().getRouterDao();
IPAddressVO ip = null;
try {
ip = ipAddressDao.acquireInLockTable(param.getIpAddress());
DomainRouterVO router = null;
if (ip.isSourceNat()) {
router = routerDao.findByPublicIpAddress(param.getIpAddress());
} else {
router = routerDao.findBy(ip.getAllocatedToAccountId(), ip.getDataCenterId());
}
return router;
} finally {
if(ip != null) {
ipAddressDao.releaseFromLockTable(param.getIpAddress());
}
}
}
}

View File

@ -242,7 +242,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
@Override
public Configuration updateConfiguration(UpdateCfgCmd cmd) throws InvalidParameterValueException{
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
String name = cmd.getCfgName();
String value = cmd.getValue();
@ -494,7 +494,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
Long userId = 1L;
if (UserContext.current() != null) {
userId = UserContext.current().getUserId();
userId = UserContext.current().getCallerUserId();
}
// Make sure the pod exists
@ -541,7 +541,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
String cidr = null;
Long id = cmd.getId();
String name = cmd.getPodName();
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
//verify parameters
HostPodVO pod = _podDao.findById(id);;
@ -670,7 +670,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
throw new InvalidParameterValueException("Failed to create pod " + name + " -- if an end IP is specified, a start IP must be specified.");
}
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
@ -895,7 +895,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
@DB
public boolean deleteZone(DeleteZoneCmd cmd) {
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
Long zoneId = cmd.getId();
if (userId == null) {
@ -950,7 +950,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
String vnetRange = cmd.getVlan();
String guestCidr = cmd.getGuestCidrAddress();
// String domain = cmd.getDomain();
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
// Long domainId = cmd.getDomainId();
if (userId == null) {
@ -1196,7 +1196,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
@Override
public DataCenter createZone(CreateZoneCmd cmd) {
// grab parameters from the command
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
String zoneName = cmd.getZoneName();
String dns1 = cmd.getDns1();
String dns2 = cmd.getDns2();
@ -1236,7 +1236,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
@Override
public ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd) throws InvalidParameterValueException {
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
if (userId == null) {
userId = User.UID_SYSTEM;
}
@ -1327,7 +1327,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
Boolean ha = cmd.getOfferHa();
// String tags = cmd.getTags();
Boolean useVirtualNetwork = cmd.getUseVirtualNetwork();
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
Long domainId = cmd.getDomainId();
if (userId == null) {
@ -1497,7 +1497,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
// }
if (_diskOfferingDao.update(diskOfferingId, diskOffering)) {
saveConfigurationEvent(UserContext.current().getUserId(), null, EventTypes.EVENT_DISK_OFFERING_EDIT, "Successfully updated disk offering with name: " + diskOffering.getName() + ".", "doId=" + diskOffering.getId(), "name=" + diskOffering.getName(),
saveConfigurationEvent(UserContext.current().getCallerUserId(), null, EventTypes.EVENT_DISK_OFFERING_EDIT, "Successfully updated disk offering with name: " + diskOffering.getName() + ".", "doId=" + diskOffering.getId(), "name=" + diskOffering.getName(),
"displayText=" + diskOffering.getDisplayText(), "diskSize=" + diskOffering.getDiskSize(),"tags=" + diskOffering.getTags(),"domainId="+cmd.getDomainId());
return _diskOfferingDao.findById(diskOfferingId);
} else {
@ -1526,7 +1526,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
public boolean deleteServiceOffering(DeleteServiceOfferingCmd cmd) throws InvalidParameterValueException{
Long offeringId = cmd.getId();
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
@ -1576,7 +1576,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
String endIP = cmd.getEndIp();
String vlanGateway = cmd.getGateway();
String vlanNetmask = cmd.getNetmask();
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
String vlanId = cmd.getVlan();
Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
Long networkId = cmd.getNetworkID();
@ -2544,7 +2544,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
@Override
public boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd) throws InvalidParameterValueException {
Long vlanDbId = cmd.getId();
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
@ -2618,7 +2618,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
@Override
public NetworkOffering createNetworkOffering(CreateNetworkOfferingCmd cmd) throws InvalidParameterValueException {
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
String name = cmd.getNetworkOfferingName();
String displayText = cmd.getDisplayText();
String tags = cmd.getTags();
@ -2752,7 +2752,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
@Override
public boolean deleteNetworkOffering(DeleteNetworkOfferingCmd cmd) throws InvalidParameterValueException{
Long offeringId = cmd.getId();
Long userId = UserContext.current().getUserId();
Long userId = UserContext.current().getCallerUserId();
//Verify network offering id
NetworkOfferingVO offering = _networkOfferingDao.findById(offeringId);

View File

@ -81,6 +81,7 @@ import com.cloud.network.security.dao.SecurityGroupRulesDaoImpl;
import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl;
import com.cloud.network.security.dao.SecurityGroupWorkDaoImpl;
import com.cloud.network.security.dao.VmRulesetLogDaoImpl;
import com.cloud.network.vpn.RemoteAccessVpnManagerImpl;
import com.cloud.offerings.dao.NetworkOfferingDaoImpl;
import com.cloud.service.dao.ServiceOfferingDaoImpl;
import com.cloud.storage.StorageManagerImpl;
@ -114,8 +115,8 @@ import com.cloud.user.dao.UserStatisticsDaoImpl;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Adapter;
import com.cloud.utils.component.ComponentLibrary;
import com.cloud.utils.component.Manager;
import com.cloud.utils.component.ComponentLocator.ComponentInfo;
import com.cloud.utils.component.Manager;
import com.cloud.utils.db.GenericDao;
import com.cloud.vm.ItWorkDaoImpl;
import com.cloud.vm.UserVmManagerImpl;
@ -286,6 +287,7 @@ public class DefaultComponentLibrary implements ComponentLibrary {
addManager("EntityManager", EntityManagerImpl.class);
addManager("LoadBalancingRulesManager", LoadBalancingRulesManagerImpl.class);
addManager("RulesManager", RulesManagerImpl.class);
addManager("RemoteAccessVpnManager", RemoteAccessVpnManagerImpl.class);
}
protected <T> List<ComponentInfo<Adapter>> addAdapterChain(Class<T> interphace, List<Pair<String, Class<? extends T>>> adapters) {

View File

@ -125,7 +125,7 @@ public class Db20to21MigrationUtil {
sb.done();
SearchCriteria<DcPod> sc = sb.create();
List<DcPod> results = _dcDao.searchIncludingRemoved(sc, (Filter)null);
List<DcPod> results = _dcDao.customSearchIncludingRemoved(sc, (Filter)null);
if(results.size() > 0) {
System.out.println("We've found following zones are deployed in your database");
for(DcPod cols : results) {

View File

@ -22,10 +22,14 @@ import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.cloud.utils.net.Ip;
/**
* A bean representing a public IP Address
@ -41,8 +45,9 @@ public class IPAddressVO implements IpAddress {
private Long allocatedInDomainId = null;
@Id
@Column(name="public_ip_address")
private String address = null;
@Column(name="public_ip_address")
@Enumerated(value=EnumType.ORDINAL)
private Ip address = null;
@Column(name="data_center_id", updatable=false)
private long dataCenterId;
@ -67,7 +72,7 @@ public class IPAddressVO implements IpAddress {
private long macAddress;
@Column(name="network_id")
private Long associatedNetworkId;
private Long associatedWithNetworkId;
protected IPAddressVO() {
}
@ -77,7 +82,7 @@ public class IPAddressVO implements IpAddress {
return state == State.Allocated;
}
public IPAddressVO(String address, long dataCenterId, long macAddress, long vlanDbId, boolean sourceNat) {
public IPAddressVO(Ip address, long dataCenterId, long macAddress, long vlanDbId, boolean sourceNat) {
this.address = address;
this.dataCenterId = dataCenterId;
this.vlanId = vlanDbId;
@ -99,7 +104,7 @@ public class IPAddressVO implements IpAddress {
}
@Override
public String getAddress() {
public Ip getAddress() {
return address;
}
@ -109,12 +114,12 @@ public class IPAddressVO implements IpAddress {
}
@Override
public Long getAssociatedNetworkId() {
return associatedNetworkId;
public Long getAssociatedWithNetworkId() {
return associatedWithNetworkId;
}
public void setAssociatedNetworkId(Long networkId) {
this.associatedNetworkId = networkId;
public void setAssociatedWithNetworkId(Long networkId) {
this.associatedWithNetworkId = networkId;
}
@Override

View File

@ -32,12 +32,14 @@ import com.cloud.network.Network.Service;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.addr.PublicIp;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.vpn.RemoteAccessVpnElement;
import com.cloud.offering.NetworkOffering.GuestIpType;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.utils.Pair;
import com.cloud.utils.net.Ip;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.Nic;
import com.cloud.vm.NicProfile;
@ -84,7 +86,7 @@ public interface NetworkManager extends NetworkService {
* @param ipAddress
* @return true if it did; false if it didn't
*/
public boolean releasePublicIpAddress(String ipAddress, long ownerId, long userId);
public boolean releasePublicIpAddress(Ip ipAddress, long ownerId, long userId);
/**
* Associates or disassociates a list of public IP address for a router.
@ -115,6 +117,8 @@ public interface NetworkManager extends NetworkService {
void prepare(VirtualMachineProfile<? extends VMInstanceVO> profile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException;
void release(VirtualMachineProfile<? extends VMInstanceVO> vmProfile);
void deallocate(VirtualMachineProfile<? extends VMInstanceVO> vm);
List<? extends Nic> getNics (VirtualMachine vm);
List<AccountVO> getAccountsUsingNetwork(long configurationId);
@ -133,4 +137,7 @@ public interface NetworkManager extends NetworkService {
long getSystemNetworkIdByZoneAndTrafficTypeAndGuestType(long zoneId, TrafficType trafficType, GuestIpType guestType);
List<? extends RemoteAccessVpnElement> getRemoteAccessVpnElements();
PublicIpAddress getPublicIpAddress(Ip ipAddress);
}

View File

@ -44,14 +44,10 @@ import com.cloud.agent.manager.Commands;
import com.cloud.alert.AlertManager;
import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
import com.cloud.api.commands.AddVpnUserCmd;
import com.cloud.api.commands.AssociateIPAddrCmd;
import com.cloud.api.commands.CreateNetworkCmd;
import com.cloud.api.commands.CreateRemoteAccessVpnCmd;
import com.cloud.api.commands.DeleteRemoteAccessVpnCmd;
import com.cloud.api.commands.DisassociateIPAddrCmd;
import com.cloud.api.commands.ListNetworksCmd;
import com.cloud.api.commands.RemoveVpnUserCmd;
import com.cloud.api.commands.RestartNetworkCmd;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.configuration.Config;
@ -73,7 +69,6 @@ import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.EventTypes;
import com.cloud.event.EventUtils;
import com.cloud.event.EventVO;
import com.cloud.event.UsageEventVO;
import com.cloud.event.dao.EventDao;
@ -111,6 +106,7 @@ import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.PortForwardingRuleVO;
import com.cloud.network.rules.RulesManager;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.network.vpn.RemoteAccessVpnElement;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.GuestIpType;
import com.cloud.offerings.NetworkOfferingVO;
@ -251,14 +247,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (vlanUse == VlanType.DirectAttached) {
addr.setState(IpAddress.State.Allocated);
} else {
addr.setAssociatedNetworkId(networkId);
addr.setAssociatedWithNetworkId(networkId);
}
if (!_ipAddressDao.update(addr.getAddress(), addr)) {
throw new CloudRuntimeException("Found address to allocate but unable to update: " + addr);
}
if(!sourceNat){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getAccountId(), dcId, 0, addr.getAddress());
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getAccountId(), dcId, 0, addr.getAddress().toString());
_usageEventDao.persist(usageEvent);
}
@ -365,7 +361,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
boolean sourceNat = false;
Map<VlanVO, ArrayList<IPAddressVO>> vlanIpMap = new HashMap<VlanVO, ArrayList<IPAddressVO>>();
for (final String ipAddress: ipAddrList) {
IPAddressVO ip = _ipAddressDao.findById(ipAddress);
IPAddressVO ip = _ipAddressDao.findById(new Ip(ipAddress));
VlanVO vlan = _vlanDao.findById(ip.getVlanId());
ArrayList<IPAddressVO> ipList = vlanIpMap.get(vlan.getId());
@ -442,7 +438,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
* @return
*/
protected Account getAccountForApiCommand(String accountName, Long domainId) throws InvalidParameterValueException, PermissionDeniedException{
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
if ((account == null) || isAdmin(account.getType())) {
//The admin is making the call, determine if it is for someone else or for himself
@ -496,7 +492,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
for (IPAddressVO addr : userIps) {
if (addr.getState() == IpAddress.State.Allocating) {
addr.setState(IpAddress.State.Allocated);
addr.setAssociatedNetworkId(network.getId());
addr.setAssociatedWithNetworkId(network.getId());
_ipAddressDao.update(addr.getAddress(), addr);
} else if (addr.getState() == IpAddress.State.Releasing) {
_ipAddressDao.unassignIpAddress(addr.getAddress());
@ -522,8 +518,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
String accountName = cmd.getAccountName();
long domainId = cmd.getDomainId();
Long zoneId = cmd.getZoneId();
Account caller = UserContext.current().getAccount();
long userId = UserContext.current().getUserId();
Account caller = UserContext.current().getCaller();
long userId = UserContext.current().getCallerUserId();
Account owner = _accountDao.findActiveAccount(accountName, domainId);
if (owner == null) {
@ -583,7 +579,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
_accountMgr.incrementResourceCount(ownerId, ResourceType.public_ip);
String ipAddress = ip.getAddress();
Ip ipAddress = ip.getAddress();
event.setParameters("address=" + ipAddress + "\nsourceNat=" + false + "\ndcId=" + zoneId);
event.setDescription("Assigned a public IP address: " + ipAddress);
_eventDao.persist(event);
@ -629,19 +625,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
@Override
public boolean releasePublicIpAddress(String ipAddress, long ownerId, long userId) {
IPAddressVO ip = _ipAddressDao.markAsUnavailable(ipAddress, ownerId);
assert (ip != null) : "Unable to mark the ip address " + ipAddress + " owned by " + ownerId + " as unavailable.";
public boolean releasePublicIpAddress(Ip addr, long ownerId, long userId) {
IPAddressVO ip = _ipAddressDao.markAsUnavailable(addr, ownerId);
assert (ip != null) : "Unable to mark the ip address " + addr + " owned by " + ownerId + " as unavailable.";
if (ip == null) {
return true;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing ip " + ipAddress + "; sourceNat = " + ip.isSourceNat());
s_logger.debug("Releasing ip " + addr + "; sourceNat = " + ip.isSourceNat());
}
Ip addr = new Ip(ip.getAddress());
boolean success = true;
try {
if (!_rulesMgr.revokeAllRules(addr, userId)) {
@ -658,8 +652,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
success = false;
}
if (ip.getAssociatedNetworkId() != null) {
Network network = _networksDao.findById(ip.getAssociatedNetworkId());
if (ip.getAssociatedWithNetworkId() != null) {
Network network = _networksDao.findById(ip.getAssociatedWithNetworkId());
try {
if (!applyIpAssociations(network, true)) {
s_logger.warn("Unable to apply ip address associations for " + network);
@ -671,16 +665,26 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
if (success) {
_ipAddressDao.unassignIpAddress(ipAddress);
s_logger.debug("released a public ip: " + ipAddress);
_ipAddressDao.unassignIpAddress(addr);
s_logger.debug("released a public ip: " + addr);
if(!ip.isSourceNat()){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_RELEASE, ownerId, ip.getDataCenterId(), 0, ipAddress);
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_RELEASE, ownerId, ip.getDataCenterId(), 0, addr.toString());
_usageEventDao.persist(usageEvent);
}
}
<<<<<<< HEAD
EventUtils.saveEvent(userId, ip.getAllocatedToAccountId(), EventTypes.EVENT_NET_IP_RELEASE, "released a public ip: " + ipAddress);
=======
final EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(ip.getAllocatedToAccountId());
event.setType(EventTypes.EVENT_NET_IP_RELEASE);
event.setParameters("address=" + addr + "\nsourceNat="+ip.isSourceNat());
event.setDescription("released a public ip: " + addr);
_eventDao.persist(event);
>>>>>>> remote access vpn, user ip address changes
return success;
}
@ -693,42 +697,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return dflt;
}
private void validateRemoteAccessVpnConfiguration() throws ConfigurationException {
String ipRange = _configs.get(Config.RemoteAccessVpnClientIpRange.key());
if (ipRange == null) {
s_logger.warn("Remote Access VPN configuration missing client ip range -- ignoring");
return;
}
Integer pskLength = getIntegerConfigValue(Config.RemoteAccessVpnPskLength.key(), 24);
if (pskLength != null && (pskLength < 8 || pskLength > 256)) {
throw new ConfigurationException("Remote Access VPN: IPSec preshared key length should be between 8 and 256");
} else if (pskLength == null) {
s_logger.warn("Remote Access VPN configuration missing Preshared Key Length -- ignoring");
return;
}
String [] range = ipRange.split("-");
if (range.length != 2) {
throw new ConfigurationException("Remote Access VPN: Invalid ip range " + ipRange);
}
if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])){
throw new ConfigurationException("Remote Access VPN: Invalid ip in range specification " + ipRange);
}
if (!NetUtils.validIpRange(range[0], range[1])){
throw new ConfigurationException("Remote Access VPN: Invalid ip range " + ipRange);
}
String [] guestIpRange = getGuestIpRange();
if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
throw new ConfigurationException("Remote Access VPN: Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]);
}
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name;
_configs = _configDao.getConfiguration("AgentManager", params);
validateRemoteAccessVpnConfiguration();
Integer rateMbps = getIntegerConfigValue(Config.NetworkThrottlingRate.key(), null);
Integer multicastRateMbps = getIntegerConfigValue(Config.MulticastThrottlingRate.key(), null);
_networkGcWait = NumbersUtil.parseInt(_configs.get(Config.NetworkGcWait.key()), 600);
@ -1153,7 +1126,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
(accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
}
private Account findAccountByIpAddress(String ipAddress) {
private Account findAccountByIpAddress(Ip ipAddress) {
IPAddressVO address = _ipAddressDao.findById(ipAddress);
if ((address != null) && (address.getAllocatedToAccountId() != null)) {
return _accountDao.findById(address.getAllocatedToAccountId());
@ -1165,9 +1138,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@DB
public boolean disassociateIpAddress(DisassociateIPAddrCmd cmd) throws PermissionDeniedException, IllegalArgumentException {
Long userId = UserContext.current().getUserId();
Account account = UserContext.current().getAccount();
String ipAddress = cmd.getIpAddress();
Long userId = UserContext.current().getCallerUserId();
Account account = UserContext.current().getCaller();
Ip ipAddress = cmd.getIpAddress();
// Verify input parameters
Account accountByIp = findAccountByIpAddress(ipAddress);
@ -1279,330 +1252,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return setupNetwork(owner, networkOffering, plan, null, null, false);
}
private String [] getGuestIpRange() {
String guestRouterIp = _configs.get(Config.GuestIpNetwork.key());
String guestNetmask = _configs.get(Config.GuestNetmask.key());
return NetUtils.ipAndNetMaskToRange(guestRouterIp, guestNetmask);
}
@Override
@DB
public RemoteAccessVpnVO createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd)
throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException {
return null;
// String publicIp = cmd.getPublicIp();
// IPAddressVO ipAddr = null;
// Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
// if (publicIp == null) {
// List<IPAddressVO> accountAddrs = _ipAddressDao.listByAccount(account.getId());
// for (IPAddressVO addr: accountAddrs){
// if (addr.getSourceNat() && addr.getDataCenterId() == cmd.getZoneId()){
// ipAddr = addr;
// publicIp = ipAddr.getAddress();
// break;
// }
// }
// if (ipAddr == null) {
// throw new InvalidParameterValueException("Account " + account.getAccountName() + " does not have any public ip addresses in zone " + cmd.getZoneId());
// }
// }
//
// // make sure ip address exists
// ipAddr = _ipAddressDao.findById(publicIp);
// if (ipAddr == null) {
// throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address " + publicIp);
// }
//
// VlanVO vlan = _vlanDao.findById(ipAddr.getVlanDbId());
// if (vlan != null) {
// if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) {
// throw new InvalidParameterValueException("Unable to create VPN for IP address " + publicIp + ", only VirtualNetwork type IP addresses can be used for VPN.");
// }
// }
// assert vlan != null:"Inconsistent DB state -- ip address does not belong to any vlan?";
//
// if ((ipAddr.getAccountId() == null) || (ipAddr.getAllocated() == null)) {
// throw new PermissionDeniedException("Unable to create VPN, permission denied for ip " + publicIp);
// }
//
// if (account != null) {
// if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
// if (!_domainDao.isChildDomain(account.getDomainId(), ipAddr.getDomainId())) {
// throw new PermissionDeniedException("Unable to create VPN with public IP address " + publicIp + ", permission denied.");
// }
// } else if (account.getId() != ipAddr.getAccountId().longValue()) {
// throw new PermissionDeniedException("Unable to create VPN for account " + account.getAccountName() + " doesn't own ip address " + publicIp);
// }
// }
//
// RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIp);
// if (vpnVO != null) {
// throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
// }
// //TODO: assumes one virtual network / domr per account per zone
// vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId());
// if (vpnVO != null) {
// throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
// }
// String ipRange = cmd.getIpRange();
// if (ipRange == null) {
// ipRange = _configs.get(Config.RemoteAccessVpnClientIpRange.key());
// }
// String [] range = ipRange.split("-");
// if (range.length != 2) {
// throw new InvalidParameterValueException("Invalid ip range");
// }
// if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])){
// throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
// }
// if (!NetUtils.validIpRange(range[0], range[1])){
// throw new InvalidParameterValueException("Invalid ip range " + ipRange);
// }
// String [] guestIpRange = getGuestIpRange();
// if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
// throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]);
// }
// //TODO: check sufficient range
// //TODO: check overlap with private and public ip ranges in datacenter
//
// long startIp = NetUtils.ip2Long(range[0]);
// String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1];
// String sharedSecret = PasswordGenerator.generatePresharedKey(getIntegerConfigValue(Config.RemoteAccessVpnPskLength.key(), 24));
// Transaction txn = Transaction.currentTxn();
// txn.start();
// boolean locked = false;
// try {
// ipAddr = _ipAddressDao.acquireInLockTable(publicIp);
// if (ipAddr == null) {
// throw new ConcurrentOperationException("Another operation active, unable to create vpn");
// }
// locked = true;
// //check overlap with port forwarding rules on this ip (udp ports 500, 4500)
// List<PortForwardingRuleVO> existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_PORT, NetUtils.UDP_PROTO);
// if (!existing.isEmpty()) {
// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_PORT + " is configured for destination NAT");
// }
// existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_NATT_PORT, NetUtils.UDP_PROTO);
// if (!existing.isEmpty()) {
// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_NATT_PORT + " is configured for destination NAT");
// }
// existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_L2TP_PORT, NetUtils.UDP_PROTO);
// if (!existing.isEmpty()) {
// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_L2TP_PORT + " is configured for destination NAT");
// }
// if (_rulesDao.isPublicIpOneToOneNATted(publicIp)) {
// throw new InvalidParameterValueException("Public Ip " + publicIp + " is configured for destination NAT");
// }
// vpnVO = new RemoteAccessVpnVO(account.getId(), cmd.getZoneId(), publicIp, range[0], newIpRange, sharedSecret);
// vpnVO = _remoteAccessVpnDao.persist(vpnVO);
// PortForwardingRuleVO rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_PORT, guestIpRange[0], NetUtils.VPN_PORT, true, NetUtils.UDP_PROTO, false, null);
// _rulesDao.persist(rule);
// rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_NATT_PORT, guestIpRange[0], NetUtils.VPN_NATT_PORT, true, NetUtils.UDP_PROTO, false, null);
// _rulesDao.persist(rule);
// rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_L2TP_PORT, guestIpRange[0], NetUtils.VPN_L2TP_PORT, true, NetUtils.UDP_PROTO, false, null);
// _rulesDao.persist(rule);
// txn.commit();
// return vpnVO;
// } finally {
// if (locked) {
// _ipAddressDao.releaseFromLockTable(publicIp);
// }
// }
}
@Override
@DB
public RemoteAccessVpnVO startRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException {
Long userId = UserContext.current().getUserId();
Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE, "Creating a Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId(), cmd.getStartEventId());
RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findById(cmd.getEntityId());
String publicIp = vpnVO.getVpnServerAddress();
Long vpnId = vpnVO.getId();
Transaction txn = Transaction.currentTxn();
txn.start();
boolean locked = false;
boolean created = false;
try {
IPAddressVO ipAddr = _ipAddressDao.acquireInLockTable(publicIp);
if (ipAddr == null) {
throw new ConcurrentOperationException("Another operation active, unable to create vpn");
}
locked = true;
vpnVO = _routerMgr.startRemoteAccessVpn(vpnVO);
created = (vpnVO != null);
return vpnVO;
} finally {
if (created) {
EventUtils.saveEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE, "Created a Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId());
} else {
EventUtils.saveEvent(userId, account.getId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE, "Unable to create Remote Access VPN ", account.getAccountName() + " in zone " + cmd.getZoneId());
_remoteAccessVpnDao.remove(vpnId);
}
txn.commit();
if (locked) {
_ipAddressDao.releaseFromLockTable(publicIp);
}
}
}
@Override
@DB
public boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException {
// Long userId = UserContext.current().getUserId();
// Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
// //TODO: assumes one virtual network / domr per account per zone
// RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId());
// if (vpnVO == null) {
// throw new InvalidParameterValueException("No VPN found for account " + account.getAccountName() + " in zone " + cmd.getZoneId());
// }
// EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleting Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId(), cmd.getStartEventId());
// String publicIp = vpnVO.getVpnServerAddress();
// Long vpnId = vpnVO.getId();
// Transaction txn = Transaction.currentTxn();
// txn.start();
// boolean locked = false;
// boolean deleted = false;
// try {
// IPAddressVO ipAddr = _ipAddressDao.acquireInLockTable(publicIp);
// if (ipAddr == null) {
// throw new ConcurrentOperationException("Another operation active, unable to create vpn");
// }
// locked = true;
//
// deleted = _routerMgr.deleteRemoteAccessVpn(vpnVO);
// return deleted;
// } finally {
// if (deleted) {
// _remoteAccessVpnDao.remove(vpnId);
// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_PORT);
// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_NATT_PORT);
// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_L2TP_PORT);
// EventUtils.saveEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleted Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId());
// } else {
// EventUtils.saveEvent(userId, account.getId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Unable to delete Remote Access VPN ", account.getAccountName() + " in zone " + cmd.getZoneId());
// }
// txn.commit();
// if (locked) {
// _ipAddressDao.releaseFromLockTable(publicIp);
// }
// }
return false; // FIXME
}
@Override
@DB
public VpnUserVO addVpnUser(AddVpnUserCmd cmd) throws ConcurrentOperationException, InvalidParameterValueException, AccountLimitException {
Long userId = UserContext.current().getUserId();
Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_VPN_USER_ADD, "Add VPN user for account: " + account.getAccountName(), cmd.getStartEventId());
if (!cmd.getUserName().matches("^[a-zA-Z0-9][a-zA-Z0-9@._-]{2,63}$")) {
throw new InvalidParameterValueException("Username has to be begin with an alphabet have 3-64 characters including alphabets, numbers and the set '@.-_'");
}
if (!cmd.getPassword().matches("^[a-zA-Z0-9][a-zA-Z0-9@#+=._-]{2,31}$")) {
throw new InvalidParameterValueException("Password has to be 3-32 characters including alphabets, numbers and the set '@#+=.-_'");
}
account = _accountDao.acquireInLockTable(account.getId());
if (account == null) {
throw new ConcurrentOperationException("Unable to add vpn user: Another operation active");
}
try {
long userCount = _vpnUsersDao.getVpnUserCount(account.getId());
Integer userLimit = getIntegerConfigValue(Config.RemoteAccessVpnUserLimit.key(), 8);
if (userCount >= userLimit) {
throw new AccountLimitException("Cannot add more than " + userLimit + " remote access vpn users");
}
VpnUserVO user = addRemoveVpnUser(account, cmd.getUserName(), cmd.getPassword(), true);
if (user != null) {
EventUtils.saveEvent(userId, account.getId(), EventTypes.EVENT_VPN_USER_ADD, "Added a VPN user for account: " + account.getAccountName() + " username= " + cmd.getUserName());
return user;
} else {
EventUtils.saveEvent(userId, account.getId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_VPN_USER_ADD, "Unable to add VPN user for account: ", account.getAccountName() + " username= " + cmd.getUserName());
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Unable to add VPN user for account: "+ account.getAccountName() + " username= " + cmd.getUserName());
}
} finally {
if (account != null) {
_accountDao.releaseFromLockTable(account.getId());
}
}
}
@Override
public boolean removeVpnUser(RemoveVpnUserCmd cmd) throws ConcurrentOperationException {
Long userId = UserContext.current().getUserId();
Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_VPN_USER_REMOVE, "Remove VPN user for account: " + account.getAccountName(), cmd.getStartEventId());
VpnUserVO user = addRemoveVpnUser(account, cmd.getUserName(), null, false);
if (user != null) {
EventUtils.saveEvent(userId, account.getId(), EventTypes.EVENT_VPN_USER_REMOVE, "Removed a VPN user for account: " + account.getAccountName() + " username= " + cmd.getUserName());
} else {
EventUtils.saveEvent(userId, account.getId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_VPN_USER_ADD, "Unable to remove VPN user for account: ", account.getAccountName() + " username= " + cmd.getUserName());
}
return (user != null);
}
@DB
protected VpnUserVO addRemoveVpnUser(Account account, String username, String password, boolean add) throws ConcurrentOperationException {
List<RemoteAccessVpnVO> vpnVOList = _remoteAccessVpnDao.findByAccount(account.getId());
Transaction txn = Transaction.currentTxn();
txn.start();
boolean locked = false;
boolean success = true;
VpnUserVO user = null;
final String op = add ? "add" : "remove";
try {
account = _accountDao.acquireInLockTable(account.getId());
if (account == null) {
throw new ConcurrentOperationException("Unable to " + op + " vpn user: Another operation active");
}
locked = true;
List<VpnUserVO> addVpnUsers = new ArrayList<VpnUserVO>();
List<VpnUserVO> removeVpnUsers = new ArrayList<VpnUserVO>();
if (add) {
user = _vpnUsersDao.persist(new VpnUserVO(account.getId(), username, password));
addVpnUsers.add(user);
} else {
user = _vpnUsersDao.findByAccountAndUsername(account.getId(), username);
if (user == null) {
s_logger.debug("Could not find vpn user " + username);
throw new InvalidParameterValueException("Could not find vpn user " + username);
}
_vpnUsersDao.remove(user.getId());
removeVpnUsers.add(user);
}
for (RemoteAccessVpnVO vpn : vpnVOList) {
success = success && _routerMgr.addRemoveVpnUsers(vpn, addVpnUsers, removeVpnUsers);
}
// Note: If the router was successfully updated, we then return the user.
if (success) {
return user;
} else {
return null;
}
} finally {
if (success) {
txn.commit();
} else {
txn.rollback();
}
if (locked) {
_accountDao.releaseFromLockTable(account.getId());
}
}
}
@Override
public List<NetworkOfferingVO> listNetworkOfferings() {
return _networkOfferingDao.listNonSystemNetworkOfferings();
@ -1622,11 +1271,37 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
public Network getNetwork(long id) {
return _networksDao.findById(id);
}
@Override
public List<? extends RemoteAccessVpnElement> getRemoteAccessVpnElements() {
List<RemoteAccessVpnElement> elements = new ArrayList<RemoteAccessVpnElement>();
for (NetworkElement element : _networkElements) {
if (element instanceof RemoteAccessVpnElement) {
elements.add((RemoteAccessVpnElement)element);
}
}
return elements;
}
@Override
public void deallocate(VirtualMachineProfile<? extends VMInstanceVO> vm) {
List<NicVO> nics = _nicDao.listBy(vm.getId());
for (NicVO nic : nics) {
nic.setState(Nic.State.Deallocating);
_nicDao.update(nic.getId(), nic);
NetworkVO network = _networksDao.findById(nic.getNetworkId());
NicProfile profile = new NicProfile(nic, network, null, null);
NetworkGuru guru = _networkGurus.get(network.getGuruName());
guru.deallocate(network, profile, vm);
_nicDao.remove(nic.getId());
}
}
@Override @DB
public Network createNetwork(CreateNetworkCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
Account ctxAccount = UserContext.current().getAccount();
Long userId = UserContext.current().getUserId();
Account ctxAccount = UserContext.current().getCaller();
Long userId = UserContext.current().getCallerUserId();
Long networkOfferingId = cmd.getNetworkOfferingId();
Long zoneId = cmd.getZoneId();
String gateway = cmd.getGateway();
@ -1813,7 +1488,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Long zoneId= cmd.getZoneId();
Account account = UserContext.current().getAccount();
Account account = UserContext.current().getCaller();
Long domainId = cmd.getDomainId();
String accountName = cmd.getAccountName();
String type = cmd.getType();
@ -1901,8 +1576,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Override @DB
public boolean deleteNetwork(long networkId) throws InvalidParameterValueException, PermissionDeniedException{
Long userId = UserContext.current().getUserId();
Account account = UserContext.current().getAccount();
Long userId = UserContext.current().getCallerUserId();
Account account = UserContext.current().getCaller();
//Verify network id
NetworkVO network = _networksDao.findById(networkId);
@ -2094,7 +1769,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
//This method reapplies Ip addresses, LoadBalancer and PortForwarding rules
String accountName = cmd.getAccountName();
long domainId = cmd.getDomainId();
Account caller = UserContext.current().getAccount();
Account caller = UserContext.current().getCaller();
Account owner = _accountDao.findActiveAccount(accountName, domainId);
if (owner == null) {
@ -2206,6 +1881,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
@Override
<<<<<<< HEAD
public long getSystemNetworkIdByZoneAndTrafficTypeAndGuestType(long zoneId, TrafficType trafficType, GuestIpType guestType) {
//find system public network offering
Long networkOfferingId = null;
@ -2228,4 +1904,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return networks.get(0).getId();
}
=======
public PublicIpAddress getPublicIpAddress(Ip ip) {
IPAddressVO addr = _ipAddressDao.findById(ip);
if (addr == null) {
return null;
}
return new PublicIp(addr, _vlanDao.findById(addr.getVlanId()), NetUtils.createSequenceBasedMacAddress(addr.getMacAddress()));
}
>>>>>>> remote access vpn, user ip address changes
}

View File

@ -20,37 +20,29 @@ package com.cloud.network;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import com.cloud.utils.net.Ip;
@Entity
@Table(name=("remote_access_vpn"))
@SecondaryTable(name="account",
pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")})
public class RemoteAccessVpnVO implements RemoteAccessVpn {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="account_id")
private long accountId;
@Column(name="network_id")
private long networkId;
@Column(name="zone_id")
private long zoneId;
@Column(name="account_name", table="account", insertable=false, updatable=false)
private String accountName = null;
@Column(name="domain_id", table="account", insertable=false, updatable=false)
@Column(name="domain_id")
private long domainId;
@Id
@Column(name="vpn_server_addr")
private String vpnServerAddress;
@Enumerated(value=EnumType.ORDINAL)
private Ip serverAddress;
@Column(name="local_ip")
private String localIp;
@ -63,41 +55,24 @@ public class RemoteAccessVpnVO implements RemoteAccessVpn {
public RemoteAccessVpnVO() { }
public RemoteAccessVpnVO(long accountId, long zoneId, String publicIp, String localIp, String ipRange, String presharedKey) {
public RemoteAccessVpnVO(long accountId, long domainId, long networkId, Ip publicIp, String localIp, String ipRange, String presharedKey) {
this.accountId = accountId;
this.vpnServerAddress = publicIp;
this.serverAddress = publicIp;
this.ipRange = ipRange;
this.ipsecPresharedKey = presharedKey;
this.zoneId = zoneId;
this.localIp = localIp;
this.localIp = localIp;
this.domainId = domainId;
this.networkId = networkId;
}
@Override
public long getId() {
return id;
}
@Override
public long getAccountId() {
return accountId;
}
@Override
public String getAccountName() {
return accountName;
}
@Override
public String getVpnServerAddress() {
return vpnServerAddress;
}
@Override
public void setVpnServerAddress(String vpnServerAddress) {
this.vpnServerAddress = vpnServerAddress;
public Ip getServerAddress() {
return serverAddress;
}
@Override
@ -105,7 +80,6 @@ public class RemoteAccessVpnVO implements RemoteAccessVpn {
return ipRange;
}
@Override
public void setIpRange(String ipRange) {
this.ipRange = ipRange;
}
@ -115,26 +89,10 @@ public class RemoteAccessVpnVO implements RemoteAccessVpn {
return ipsecPresharedKey;
}
@Override
public void setIpsecPresharedKey(String ipsecPresharedKey) {
this.ipsecPresharedKey = ipsecPresharedKey;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public void setZoneId(long zoneId) {
this.zoneId = zoneId;
}
@Override
public long getZoneId() {
return zoneId;
}
@Override
public String getLocalIp() {
return localIp;
@ -144,6 +102,9 @@ public class RemoteAccessVpnVO implements RemoteAccessVpn {
public long getDomainId() {
return domainId;
}
@Override
public long getNetworkId() {
return networkId;
}
}

View File

@ -22,12 +22,13 @@ import java.util.Date;
import com.cloud.dc.VlanVO;
import com.cloud.network.IPAddressVO;
import com.cloud.network.PublicIpAddress;
import com.cloud.utils.net.Ip;
import com.cloud.utils.net.NetUtils;
/**
* PublicIp is a combo object of IPAddressVO and VLAN information.
*/
public class PublicIp implements PublicIpAddress{
public class PublicIp implements PublicIpAddress {
IPAddressVO _addr;
VlanVO _vlan;
String macAddress;
@ -39,7 +40,7 @@ public class PublicIp implements PublicIpAddress{
}
@Override
public String getAddress() {
public Ip getAddress() {
return _addr.getAddress();
}
@ -127,8 +128,42 @@ public class PublicIp implements PublicIpAddress{
}
@Override
public Long getAssociatedNetworkId() {
return _addr.getAssociatedNetworkId();
public Long getAssociatedWithNetworkId() {
return _addr.getAssociatedWithNetworkId();
}
@Override
public Long getNetworkId() {
return _vlan.getNetworkId();
}
@Override
public String getVlanGateway() {
return _vlan.getVlanGateway();
}
@Override
public String getVlanNetmask() {
return _vlan.getVlanNetmask();
}
@Override
public String getIpRange() {
return _vlan.getIpRange();
}
@Override
public VlanType getVlanType() {
return _vlan.getVlanType();
}
@Override
public long getId() {
return _vlan.getId();
}
@Override
public String toString() {
return _addr.getAddress().toString();
}
}

View File

@ -22,12 +22,13 @@ import java.util.List;
import com.cloud.network.IPAddressVO;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.net.Ip;
public interface IPAddressDao extends GenericDao<IPAddressVO, String> {
public interface IPAddressDao extends GenericDao<IPAddressVO, Ip> {
IPAddressVO markAsUnavailable(String ipAddress, long ownerId);
IPAddressVO markAsUnavailable(Ip ipAddress, long ownerId);
void unassignIpAddress(String ipAddress);
void unassignIpAddress(Ip ipAddress);
List<IPAddressVO> listByAccount(long accountId);

View File

@ -40,10 +40,11 @@ import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.Ip;
@Local(value = { IPAddressDao.class })
@DB
public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, String> implements IPAddressDao {
public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Ip> implements IPAddressDao {
private static final Logger s_logger = Logger.getLogger(IPAddressDaoImpl.class);
protected final SearchBuilder<IPAddressVO> AllFieldsSearch;
@ -62,7 +63,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, String> implem
AllFieldsSearch.and("vlan", AllFieldsSearch.entity().getVlanId(), Op.EQ);
AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAllocatedToAccountId(), Op.EQ);
AllFieldsSearch.and("sourceNat", AllFieldsSearch.entity().isSourceNat(), Op.EQ);
AllFieldsSearch.and("network", AllFieldsSearch.entity().getAssociatedNetworkId(), Op.EQ);
AllFieldsSearch.and("network", AllFieldsSearch.entity().getAssociatedWithNetworkId(), Op.EQ);
AllFieldsSearch.done();
VlanDbIdSearchUnallocated = createSearchBuilder();
@ -131,7 +132,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, String> implem
if (!update(ip.getAddress(), ip)) {
throw new CloudRuntimeException("Unable to update a locked ip address " + ip.getAddress());
}
ipStringList.add(ip.getAddress());
ipStringList.add(ip.getAddress().toString());
}
txn.commit();
return ipStringList;
@ -174,7 +175,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, String> implem
}
@Override
public void unassignIpAddress(String ipAddress) {
public void unassignIpAddress(Ip ipAddress) {
IPAddressVO address = createForUpdate();
address.setAllocatedToAccountId(null);
address.setAllocatedInDomainId(null);
@ -182,7 +183,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, String> implem
address.setSourceNat(false);
address.setOneToOneNat(false);
address.setState(State.Free);
address.setAssociatedNetworkId(null);
address.setAssociatedWithNetworkId(null);
update(ipAddress, address);
}
@ -253,7 +254,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, String> implem
}
@Override @DB
public IPAddressVO markAsUnavailable(String ipAddress, long ownerId) {
public IPAddressVO markAsUnavailable(Ip ipAddress, long ownerId) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
sc.setParameters("accountId", ownerId);
sc.setParameters("ipAddress", ipAddress);

View File

@ -22,9 +22,10 @@ import java.util.List;
import com.cloud.network.RemoteAccessVpnVO;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.net.Ip;
public interface RemoteAccessVpnDao extends GenericDao<RemoteAccessVpnVO, Long> {
public interface RemoteAccessVpnDao extends GenericDao<RemoteAccessVpnVO, Ip> {
RemoteAccessVpnVO findByPublicIpAddress(String ipAddress);
RemoteAccessVpnVO findByAccountAndZone(Long accountId, Long zoneId);
RemoteAccessVpnVO findByAccountAndNetwork(Long accountId, Long zoneId);
List<RemoteAccessVpnVO> findByAccount(Long accountId);
}

View File

@ -28,49 +28,41 @@ import com.cloud.network.RemoteAccessVpnVO;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.net.Ip;
@Local(value={RemoteAccessVpnDao.class})
public class RemoteAccessVpnDaoImpl extends GenericDaoBase<RemoteAccessVpnVO, Long> implements RemoteAccessVpnDao {
public class RemoteAccessVpnDaoImpl extends GenericDaoBase<RemoteAccessVpnVO, Ip> implements RemoteAccessVpnDao {
private static final Logger s_logger = Logger.getLogger(RemoteAccessVpnDaoImpl.class);
private final SearchBuilder<RemoteAccessVpnVO> ListByIp;
private final SearchBuilder<RemoteAccessVpnVO> AccountAndZoneSearch;
private final SearchBuilder<RemoteAccessVpnVO> AccountSearch;
private final SearchBuilder<RemoteAccessVpnVO> AllFieldsSearch;
protected RemoteAccessVpnDaoImpl() {
ListByIp = createSearchBuilder();
ListByIp.and("ipAddress", ListByIp.entity().getVpnServerAddress(), SearchCriteria.Op.EQ);
ListByIp.done();
AccountAndZoneSearch = createSearchBuilder();
AccountAndZoneSearch.and("accountId", AccountAndZoneSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountAndZoneSearch.and("zoneId", AccountAndZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ);
AccountAndZoneSearch.done();
AccountSearch = createSearchBuilder();
AccountSearch.and("accountId", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountSearch.done();
AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("networkId", AllFieldsSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("ipAddress", AllFieldsSearch.entity().getServerAddress(), SearchCriteria.Op.EQ);
AllFieldsSearch.done();
}
@Override
public RemoteAccessVpnVO findByPublicIpAddress(String ipAddress) {
SearchCriteria<RemoteAccessVpnVO> sc = ListByIp.create();
SearchCriteria<RemoteAccessVpnVO> sc = AllFieldsSearch.create();
sc.setParameters("ipAddress", ipAddress);
return findOneBy(sc);
}
@Override
public RemoteAccessVpnVO findByAccountAndZone(Long accountId, Long zoneId) {
SearchCriteria<RemoteAccessVpnVO> sc = AccountAndZoneSearch.create();
public RemoteAccessVpnVO findByAccountAndNetwork(Long accountId, Long networkId) {
SearchCriteria<RemoteAccessVpnVO> sc = AllFieldsSearch.create();
sc.setParameters("accountId", accountId);
sc.setParameters("zoneId", zoneId);
sc.setParameters("networkId", networkId);
return findOneBy(sc);
}
@Override
public List<RemoteAccessVpnVO> findByAccount(Long accountId) {
SearchCriteria<RemoteAccessVpnVO> sc = AccountSearch.create();
SearchCriteria<RemoteAccessVpnVO> sc = AllFieldsSearch.create();
sc.setParameters("accountId", accountId);
return listBy(sc);
}

View File

@ -22,6 +22,7 @@ import java.util.List;
import javax.ejb.Local;
import com.cloud.network.VpnUser.State;
import com.cloud.network.VpnUserVO;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
@ -49,6 +50,7 @@ public class VpnUserDaoImpl extends GenericDaoBase<VpnUserVO, Long> implements V
VpnUserCount = createSearchBuilder(Long.class);
VpnUserCount.and("accountId", VpnUserCount.entity().getAccountId(), SearchCriteria.Op.EQ);
VpnUserCount.and("state", VpnUserCount.entity().getState(), SearchCriteria.Op.NEQ);
VpnUserCount.select(null, Func.COUNT, null);
VpnUserCount.done();
}
@ -73,7 +75,8 @@ public class VpnUserDaoImpl extends GenericDaoBase<VpnUserVO, Long> implements V
public long getVpnUserCount(Long accountId) {
SearchCriteria<Long> sc = VpnUserCount.create();
sc.setParameters("accountId", accountId);
List<Long> rs = searchIncludingRemoved(sc, null);
sc.setParameters("state", State.Revoke);
List<Long> rs = customSearch(sc, null);
if (rs.size() == 0) {
return 0;
}

View File

@ -93,7 +93,7 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru {
protected void getIp(NicProfile nic, DataCenter dc, VirtualMachineProfile<? extends VirtualMachine> vm, Network network) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException {
if (nic.getIp4Address() == null) {
PublicIp ip = _networkMgr.assignPublicIpAddress(dc.getId(), vm.getOwner(), VlanType.DirectAttached, network.getId());
nic.setIp4Address(ip.getAddress());
nic.setIp4Address(ip.getAddress().toString());
nic.setGateway(ip.getGateway());
nic.setNetmask(ip.getNetmask());
nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag()));

Some files were not shown because too many files have changed in this diff Show More