Fixed format style in a bunch of files (replaced tabs with spaces as a part of it)

This commit is contained in:
Alena Prokharchyk 2012-02-03 13:45:06 -08:00
parent 1f0ea28cc4
commit 1490e45a1c
50 changed files with 5564 additions and 5236 deletions

View File

@ -1,4 +1,5 @@
/** /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
@ -14,113 +15,111 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.cloud.api.commands; package com.cloud.api.commands;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants; import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd; import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper; import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation; import com.cloud.api.Implementation;
import com.cloud.api.Parameter; import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException; import com.cloud.api.ServerApiException;
import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.response.SecurityGroupResponse;
import com.cloud.api.response.SecurityGroupResponse; import com.cloud.network.security.SecurityGroup;
import com.cloud.network.security.SecurityGroup; import com.cloud.user.Account;
import com.cloud.user.Account; import com.cloud.user.UserContext;
import com.cloud.user.UserContext;
@Implementation(responseObject = SecurityGroupResponse.class, description = "Creates a security group")
@Implementation(responseObject=SecurityGroupResponse.class, description="Creates a security group") public class CreateSecurityGroupCmd extends BaseCmd {
public class CreateSecurityGroupCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSecurityGroupCmd.class.getName());
public static final Logger s_logger = Logger.getLogger(CreateSecurityGroupCmd.class.getName());
private static final String s_name = "createsecuritygroupresponse";
private static final String s_name = "createsecuritygroupresponse";
// ///////////////////////////////////////////////////
///////////////////////////////////////////////////// // ////////////// API parameters /////////////////////
//////////////// API parameters ///////////////////// // ///////////////////////////////////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the security group. Must be used with domainId.")
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName;
private String accountName;
@IdentityMapper(entityTableName = "domain")
@IdentityMapper(entityTableName="domain") @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "an optional domainId for the security group. If the account parameter is used, domainId must also be used.")
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") private Long domainId;
private Long domainId;
@Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "the description of the security group")
@Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="the description of the security group") private String description;
private String description;
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the security group")
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="name of the security group")
private String securityGroupName; private String securityGroupName;
@IdentityMapper(entityTableName="projects") @IdentityMapper(entityTableName = "projects")
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Deploy vm for the project") @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "Deploy vm for the project")
private Long projectId; private Long projectId;
// ///////////////////////////////////////////////////
///////////////////////////////////////////////////// // ///////////////// Accessors ///////////////////////
/////////////////// Accessors /////////////////////// // ///////////////////////////////////////////////////
/////////////////////////////////////////////////////
public String getAccountName() {
public String getAccountName() { return accountName;
return accountName;
}
public String getDescription() {
return description;
}
public Long getDomainId() {
return domainId;
}
public String getSecurityGroupName() {
return securityGroupName;
} }
public String getDescription() {
return description;
}
public Long getDomainId() {
return domainId;
}
public String getSecurityGroupName() {
return securityGroupName;
}
public Long getProjectId() { public Long getProjectId() {
return projectId; return projectId;
} }
// ///////////////////////////////////////////////////
///////////////////////////////////////////////////// // ///////////// API Implementation///////////////////
/////////////// API Implementation/////////////////// // ///////////////////////////////////////////////////
/////////////////////////////////////////////////////
@Override
@Override public String getCommandName() {
public String getCommandName() { return s_name;
return s_name; }
}
@Override
@Override public long getEntityOwnerId() {
public long getEntityOwnerId() { Account account = UserContext.current().getCaller();
Account account = UserContext.current().getCaller(); if ((account == null) || isAdmin(account.getType())) {
if ((account == null) || isAdmin(account.getType())) { if ((domainId != null) && (accountName != null)) {
if ((domainId != null) && (accountName != null)) { Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId); if (userAccount != null) {
if (userAccount != null) { return userAccount.getId();
return userAccount.getId(); }
} }
} }
}
if (account != null) {
if (account != null) { return account.getId();
return account.getId(); }
}
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked // tracked
} }
@Override @Override
public void execute(){ public void execute() {
SecurityGroup group = _securityGroupService.createSecurityGroup(this); SecurityGroup group = _securityGroupService.createSecurityGroup(this);
if (group != null) { if (group != null) {
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponse(group); SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponse(group);
response.setResponseName(getCommandName()); response.setResponseName(getCommandName());
this.setResponseObject(response); this.setResponseObject(response);
} else { } else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create security group"); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create security group");
} }
} }
} }

View File

@ -29,33 +29,33 @@ import com.cloud.api.response.InstanceGroupResponse;
import com.cloud.user.UserContext; import com.cloud.user.UserContext;
import com.cloud.vm.InstanceGroup; import com.cloud.vm.InstanceGroup;
@Implementation(description="Creates a vm group", responseObject=InstanceGroupResponse.class) @Implementation(description = "Creates a vm group", responseObject = InstanceGroupResponse.class)
public class CreateVMGroupCmd extends BaseCmd{ public class CreateVMGroupCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CreateVMGroupCmd.class.getName()); public static final Logger s_logger = Logger.getLogger(CreateVMGroupCmd.class.getName());
private static final String s_name = "createinstancegroupresponse"; private static final String s_name = "createinstancegroupresponse";
///////////////////////////////////////////////////// // ///////////////////////////////////////////////////
//////////////// API parameters ///////////////////// // ////////////// API parameters /////////////////////
///////////////////////////////////////////////////// // ///////////////////////////////////////////////////
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the instance group") @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the instance group")
private String groupName; private String groupName;
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account of the instance group. The account parameter must be used with the domainId parameter.") @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account of the instance group. The account parameter must be used with the domainId parameter.")
private String accountName; private String accountName;
@IdentityMapper(entityTableName="domain") @IdentityMapper(entityTableName = "domain")
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of account owning the instance group") @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "the domain ID of account owning the instance group")
private Long domainId; private Long domainId;
@IdentityMapper(entityTableName="projects") @IdentityMapper(entityTableName = "projects")
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="The project of the instance group") @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "The project of the instance group")
private Long projectId; private Long projectId;
///////////////////////////////////////////////////// // ///////////////////////////////////////////////////
/////////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
///////////////////////////////////////////////////// // ///////////////////////////////////////////////////
public String getGroupName() { public String getGroupName() {
return groupName; return groupName;
@ -68,32 +68,32 @@ public class CreateVMGroupCmd extends BaseCmd{
public Long getDomainId() { public Long getDomainId() {
return domainId; return domainId;
} }
public Long getProjectId() { public Long getProjectId() {
return projectId; return projectId;
} }
///////////////////////////////////////////////////// // ///////////////////////////////////////////////////
/////////////// API Implementation/////////////////// // ///////////// API Implementation///////////////////
///////////////////////////////////////////////////// // ///////////////////////////////////////////////////
@Override @Override
public String getCommandName() { public String getCommandName() {
return s_name; return s_name;
} }
@Override @Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); Long accountId = finalyzeAccountId(accountName, domainId, projectId, true);
if (accountId == null) { if (accountId == null) {
return UserContext.current().getCaller().getId(); return UserContext.current().getCaller().getId();
} }
return accountId; return accountId;
} }
@Override @Override
public void execute(){ public void execute() {
InstanceGroup result = _userVmService.createVmGroup(this); InstanceGroup result = _userVmService.createVmGroup(this);
if (result != null) { if (result != null) {
InstanceGroupResponse response = _responseGenerator.createInstanceGroupResponse(result); InstanceGroupResponse response = _responseGenerator.createInstanceGroupResponse(result);

View File

@ -68,7 +68,8 @@ public interface ConfigurationService {
* Create a service offering through the API * Create a service offering through the API
* *
* @param cmd * @param cmd
* the command object that specifies the name, number of cpu cores, amount of RAM, etc. for the service offering * the command object that specifies the name, number of cpu cores, amount of RAM, etc. for the service
* offering
* @return the newly created service offering if successful, null otherwise * @return the newly created service offering if successful, null otherwise
*/ */
ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd); ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd);
@ -130,13 +131,21 @@ public interface ConfigurationService {
/** /**
* Creates a new pod based on the parameters specified in the command object * Creates a new pod based on the parameters specified in the command object
* @param zoneId TODO *
* @param name TODO * @param zoneId
* @param startIp TODO * TODO
* @param endIp TODO * @param name
* @param gateway TODO * TODO
* @param netmask TODO * @param startIp
* @param allocationState TODO * TODO
* @param endIp
* TODO
* @param gateway
* TODO
* @param netmask
* TODO
* @param allocationState
* TODO
* @return the new pod if successful, null otherwise * @return the new pod if successful, null otherwise
* @throws * @throws
* @throws * @throws
@ -188,12 +197,14 @@ public interface ConfigurationService {
boolean deleteZone(DeleteZoneCmd cmd); boolean deleteZone(DeleteZoneCmd cmd);
/** /**
* Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on the * Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on
* the
* virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs * virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs
* *
* @param userId * @param userId
* @param vlanType * @param vlanType
* - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be directly * - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be
* directly
* attached to UserVMs) * attached to UserVMs)
* @param zoneId * @param zoneId
* @param accountId * @param accountId

View File

@ -18,12 +18,12 @@
package com.cloud.configuration; package com.cloud.configuration;
public interface ResourceLimit extends Resource{ public interface ResourceLimit extends Resource {
public Long getId(); public Long getId();
public Long getMax(); public Long getMax();
public void setMax(Long max); public void setMax(Long max);
} }

View File

@ -84,7 +84,7 @@ public interface NetworkService {
Integer getNetworkRate(long networkId, Long vmId); Integer getNetworkRate(long networkId, Long vmId);
Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType);
Map<Service, Set<Provider>> getNetworkOfferingServiceProvidersMap(long networkOfferingId); Map<Service, Set<Provider>> getNetworkOfferingServiceProvidersMap(long networkOfferingId);
PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List<String> isolationMethods, String broadcastDomainRange, Long domainId, List<String> tags, String name); PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List<String> isolationMethods, String broadcastDomainRange, Long domainId, List<String> tags, String name);
@ -114,7 +114,7 @@ public interface NetworkService {
PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(Long providerId); PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(Long providerId);
PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId); PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId);
long findPhysicalNetworkId(long zoneId, String tag); long findPhysicalNetworkId(long zoneId, String tag);
PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan); PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan);
@ -128,8 +128,9 @@ public interface NetworkService {
List<? extends PhysicalNetworkTrafficType> listTrafficTypes(Long physicalNetworkId); List<? extends PhysicalNetworkTrafficType> listTrafficTypes(Long physicalNetworkId);
PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType);
Network getExclusiveGuestNetwork(long zoneId); Network getExclusiveGuestNetwork(long zoneId);
List<Pair<TrafficType, String>> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd); List<Pair<TrafficType, String>> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd);
} }

View File

@ -10,18 +10,22 @@ import com.cloud.user.Account;
public interface FirewallService { public interface FirewallService {
FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException; FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException;
List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd); List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd);
/** /**
* Revokes a firewall rule * Revokes a firewall rule
* @param ruleId the id of the rule to revoke. *
* @param ruleId
* the id of the rule to revoke.
* @return * @return
*/ */
boolean revokeFirewallRule(long ruleId, boolean apply); boolean revokeFirewallRule(long ruleId, boolean apply);
boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException; boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException;
FirewallRule getFirewallRule(long ruleId); FirewallRule getFirewallRule(long ruleId);
boolean revokeRelatedFirewallRule(long ruleId, boolean apply); boolean revokeRelatedFirewallRule(long ruleId, boolean apply);
} }

View File

@ -18,57 +18,66 @@
package com.cloud.network.lb; package com.cloud.network.lb;
import java.util.List; import java.util.List;
import com.cloud.api.commands.CreateLBStickinessPolicyCmd; import com.cloud.api.commands.CreateLBStickinessPolicyCmd;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd; import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.api.commands.ListLBStickinessPoliciesCmd; import com.cloud.api.commands.ListLBStickinessPoliciesCmd;
import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd; import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd;
import com.cloud.api.commands.ListLoadBalancerRulesCmd; import com.cloud.api.commands.ListLoadBalancerRulesCmd;
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd; import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.rules.StickinessPolicy;
import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.LoadBalancer;
import com.cloud.network.rules.StickinessPolicy;
import com.cloud.uservm.UserVm; import com.cloud.uservm.UserVm;
public interface LoadBalancingRulesService { public interface LoadBalancingRulesService {
/** /**
* Create a load balancer rule from the given ipAddress/port to the given private port * Create a load balancer rule from the given ipAddress/port to the given private port
* @param openFirewall TODO *
* @param cmd the command specifying the ip address, public port, protocol, private port, and algorithm * @param openFirewall
* TODO
* @param cmd
* the command specifying the ip address, public port, protocol, private port, and algorithm
* @return the newly created LoadBalancerVO if successful, null otherwise * @return the newly created LoadBalancerVO if successful, null otherwise
* @throws InsufficientAddressCapacityException * @throws InsufficientAddressCapacityException
*/ */
LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException, InsufficientAddressCapacityException; LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException, InsufficientAddressCapacityException;
LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd); LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd);
boolean deleteLoadBalancerRule(long lbRuleId, boolean apply); boolean deleteLoadBalancerRule(long lbRuleId, boolean apply);
/** /**
* Create a stickiness policy to a load balancer from the given stickiness method name and parameters in (name,value) pairs. * Create a stickiness policy to a load balancer from the given stickiness method name and parameters in
* @param cmd the command specifying the stickiness method name, params (name,value pairs), policy name and description. * (name,value) pairs.
*
* @param cmd
* the command specifying the stickiness method name, params (name,value pairs), policy name and
* description.
* @return the newly created stickiness policy if successfull, null otherwise * @return the newly created stickiness policy if successfull, null otherwise
* @thows NetworkRuleConflictException * @thows NetworkRuleConflictException
*/ */
public StickinessPolicy createLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws NetworkRuleConflictException; public StickinessPolicy createLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws NetworkRuleConflictException;
public boolean applyLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws ResourceUnavailableException; public boolean applyLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws ResourceUnavailableException;
boolean deleteLBStickinessPolicy(long stickinessPolicyId); boolean deleteLBStickinessPolicy(long stickinessPolicyId);
/** /**
* Assign a virtual machine, or list of virtual machines, to a load balancer. * Assign a virtual machine, or list of virtual machines, to a load balancer.
*/ */
boolean assignToLoadBalancer(long lbRuleId, List<Long> vmIds); boolean assignToLoadBalancer(long lbRuleId, List<Long> vmIds);
boolean removeFromLoadBalancer(long lbRuleId, List<Long> vmIds); boolean removeFromLoadBalancer(long lbRuleId, List<Long> vmIds);
boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException; boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException;
/** /**
* List instances that have either been applied to a load balancer or are eligible to be assigned to a load balancer. * List instances that have either been applied to a load balancer or are eligible to be assigned to a load
* balancer.
*
* @param cmd * @param cmd
* @return list of vm instances that have been or can be applied to a load balancer * @return list of vm instances that have been or can be applied to a load balancer
*/ */
@ -76,21 +85,26 @@ public interface LoadBalancingRulesService {
/** /**
* List load balancer rules based on the given criteria * List load balancer rules based on the given criteria
* @param cmd the command that specifies the criteria to use for listing load balancers. Load balancers can be listed *
* @param cmd
* the command that specifies the criteria to use for listing load balancers. Load balancers can be
* listed
* by id, name, public ip, and vm instance id * by id, name, public ip, and vm instance id
* @return list of load balancers that match the criteria * @return list of load balancers that match the criteria
*/ */
List<? extends LoadBalancer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd); List<? extends LoadBalancer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd);
/** /**
* List stickiness policies based on the given criteria * List stickiness policies based on the given criteria
* @param cmd the command specifies the load balancing rule id. *
* @param cmd
* the command specifies the load balancing rule id.
* @return list of stickiness policies that match the criteria. * @return list of stickiness policies that match the criteria.
*/ */
List<? extends StickinessPolicy> searchForLBStickinessPolicies(ListLBStickinessPoliciesCmd cmd); List<? extends StickinessPolicy> searchForLBStickinessPolicies(ListLBStickinessPoliciesCmd cmd);
List<LoadBalancingRule> listByNetworkId(long networkId); List<LoadBalancingRule> listByNetworkId(long networkId);
LoadBalancer findById(long LoadBalancer); LoadBalancer findById(long LoadBalancer);
} }

View File

@ -26,50 +26,61 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.user.Account; import com.cloud.user.Account;
public interface RulesService { public interface RulesService {
List<? extends FirewallRule> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll); List<? extends FirewallRule> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll);
/** /**
* Creates a port forwarding rule between two ip addresses or between * Creates a port forwarding rule between two ip addresses or between
* an ip address and a virtual machine. * an ip address and a virtual machine.
* @param rule rule to be created. *
* @param vmId vm to be linked to. If specified the destination ip address is ignored. * @param rule
* @param openFirewall TODO * rule to be created.
* @param vmId
* vm to be linked to. If specified the destination ip address is ignored.
* @param openFirewall
* TODO
* @return PortForwardingRule if created. * @return PortForwardingRule if created.
* @throws NetworkRuleConflictException if conflicts in the network rules are detected. * @throws NetworkRuleConflictException
* if conflicts in the network rules are detected.
*/ */
PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException; PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException;
/** /**
* Revokes a port forwarding rule * Revokes a port forwarding rule
* @param ruleId the id of the rule to revoke. *
* @param caller * @param ruleId
* the id of the rule to revoke.
* @param caller
* @return * @return
*/ */
boolean revokePortForwardingRule(long ruleId, boolean apply); boolean revokePortForwardingRule(long ruleId, boolean apply);
/** /**
* List port forwarding rules assigned to an ip address * List port forwarding rules assigned to an ip address
* @param cmd the command object holding the criteria for listing port forwarding rules (the ipAddress) *
* @param cmd
* the command object holding the criteria for listing port forwarding rules (the ipAddress)
* @return list of port forwarding rules on the given address, empty list if no rules exist * @return list of port forwarding rules on the given address, empty list if no rules exist
*/ */
public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd); public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd);
boolean applyPortForwardingRules(long ipAdddressId, Account caller) throws ResourceUnavailableException; boolean applyPortForwardingRules(long ipAdddressId, Account caller) throws ResourceUnavailableException;
boolean enableStaticNat(long ipAddressId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException; boolean enableStaticNat(long ipAddressId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException;
PortForwardingRule getPortForwardigRule(long ruleId); PortForwardingRule getPortForwardigRule(long ruleId);
FirewallRule getFirewallRule(long ruleId); FirewallRule getFirewallRule(long ruleId);
StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException; StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException;
boolean revokeStaticNatRule(long ruleId, boolean apply); boolean revokeStaticNatRule(long ruleId, boolean apply);
boolean applyStaticNatRules(long ipAdddressId, Account caller) throws ResourceUnavailableException; boolean applyStaticNatRules(long ipAdddressId, Account caller) throws ResourceUnavailableException;
StaticNatRule buildStaticNatRule(FirewallRule rule); StaticNatRule buildStaticNatRule(FirewallRule rule);
List<String> getSourceCidrs(long ruleId); List<String> getSourceCidrs(long ruleId);
boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException; boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException;
} }

View File

@ -22,29 +22,29 @@ import com.cloud.network.Networks.TrafficType;
/** /**
* Describes network offering * Describes network offering
* *
*/ */
public interface NetworkOffering { public interface NetworkOffering {
public enum Availability { public enum Availability {
Required, Required,
Optional Optional
} }
public enum State { public enum State {
Disabled, Disabled,
Enabled Enabled
} }
public final static String SystemPublicNetwork = "System-Public-Network"; public final static String SystemPublicNetwork = "System-Public-Network";
public final static String SystemControlNetwork = "System-Control-Network"; public final static String SystemControlNetwork = "System-Control-Network";
public final static String SystemManagementNetwork = "System-Management-Network"; public final static String SystemManagementNetwork = "System-Management-Network";
public final static String SystemStorageNetwork = "System-Storage-Network"; public final static String SystemStorageNetwork = "System-Storage-Network";
public final static String DefaultSharedNetworkOfferingWithSGService = "DefaultSharedNetworkOfferingWithSGService"; public final static String DefaultSharedNetworkOfferingWithSGService = "DefaultSharedNetworkOfferingWithSGService";
public final static String DefaultIsolatedNetworkOfferingWithSourceNatService = "DefaultIsolatedNetworkOfferingWithSourceNatService"; public final static String DefaultIsolatedNetworkOfferingWithSourceNatService = "DefaultIsolatedNetworkOfferingWithSourceNatService";
public final static String DefaultSharedNetworkOffering = "DefaultSharedNetworkOffering"; public final static String DefaultSharedNetworkOffering = "DefaultSharedNetworkOffering";
public final static String DefaultIsolatedNetworkOffering= "DefaultIsolatedNetworkOffering"; public final static String DefaultIsolatedNetworkOffering = "DefaultIsolatedNetworkOffering";
public final static String DefaultSharedEIPandELBNetworkOffering = "DefaultSharedNetscalerEIPandELBNetworkOffering"; public final static String DefaultSharedEIPandELBNetworkOffering = "DefaultSharedNetscalerEIPandELBNetworkOffering";
long getId(); long getId();
@ -53,32 +53,32 @@ public interface NetworkOffering {
* @return name for the network offering. * @return name for the network offering.
*/ */
String getName(); String getName();
/** /**
* @return text to display to the end user. * @return text to display to the end user.
*/ */
String getDisplayText(); String getDisplayText();
/** /**
* @return the rate in megabits per sec to which a VM's network interface is throttled to * @return the rate in megabits per sec to which a VM's network interface is throttled to
*/ */
Integer getRateMbps(); Integer getRateMbps();
/** /**
* @return the rate megabits per sec to which a VM's multicast&broadcast traffic is throttled to * @return the rate megabits per sec to which a VM's multicast&broadcast traffic is throttled to
*/ */
Integer getMulticastRateMbps(); Integer getMulticastRateMbps();
TrafficType getTrafficType(); TrafficType getTrafficType();
boolean getSpecifyVlan(); boolean getSpecifyVlan();
String getTags(); String getTags();
boolean isDefault(); boolean isDefault();
boolean isSystemOnly(); boolean isSystemOnly();
Availability getAvailability(); Availability getAvailability();
String getUniqueName(); String getUniqueName();
@ -86,22 +86,23 @@ public interface NetworkOffering {
void setState(State state); void setState(State state);
State getState(); State getState();
GuestType getGuestType(); GuestType getGuestType();
Long getServiceOfferingId(); Long getServiceOfferingId();
boolean getDedicatedLB(); boolean getDedicatedLB();
boolean getSharedSourceNat(); boolean getSharedSourceNat();
boolean getRedundantRouter(); boolean getRedundantRouter();
boolean isConserveMode(); boolean isConserveMode();
boolean getElasticIp(); boolean getElasticIp();
boolean getElasticLb(); boolean getElasticLb();
boolean getSpecifyIpRanges();
boolean getSpecifyIpRanges();
} }

View File

@ -27,9 +27,9 @@ import com.cloud.exception.PermissionDeniedException;
public interface DomainService { public interface DomainService {
Domain createDomain(String name, Long parentId, String networkDomain); Domain createDomain(String name, Long parentId, String networkDomain);
Domain getDomain(long id); Domain getDomain(long id);
/** /**
* Return whether a domain is a child domain of a given domain. * Return whether a domain is a child domain of a given domain.
* *
@ -41,9 +41,10 @@ public interface DomainService {
boolean deleteDomain(long domainId, Boolean cleanup); boolean deleteDomain(long domainId, Boolean cleanup);
List<? extends Domain> searchForDomains(ListDomainsCmd cmd) List<? extends Domain> searchForDomains(ListDomainsCmd cmd)
throws PermissionDeniedException; throws PermissionDeniedException;
List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
throws PermissionDeniedException;
List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
throws PermissionDeniedException;
} }

View File

@ -26,13 +26,18 @@ import com.cloud.domain.Domain;
import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceAllocationException;
public interface ResourceLimitService { public interface ResourceLimitService {
/** /**
* Updates an existing resource limit with the specified details. If a limit doesn't exist, will create one. * Updates an existing resource limit with the specified details. If a limit doesn't exist, will create one.
* @param accountId TODO *
* @param domainId TODO * @param accountId
* @param resourceType TODO * TODO
* @param max TODO * @param domainId
* TODO
* @param resourceType
* TODO
* @param max
* TODO
* *
* @return the updated/created resource limit * @return the updated/created resource limit
*/ */
@ -40,26 +45,36 @@ public interface ResourceLimitService {
/** /**
* Updates an existing resource count details for the account/domain * Updates an existing resource count details for the account/domain
* @param accountId TODO *
* @param domainId TODO * @param accountId
* @param typeId TODO * TODO
* @param domainId
* TODO
* @param typeId
* TODO
* @return the updated/created resource counts * @return the updated/created resource counts
*/ */
List<? extends ResourceCount> recalculateResourceCount(Long accountId, Long domainId, Integer typeId); List<? extends ResourceCount> recalculateResourceCount(Long accountId, Long domainId, Integer typeId);
/** /**
* Search for resource limits for the given id and/or account and/or type and/or domain. * Search for resource limits for the given id and/or account and/or type and/or domain.
* @param id TODO *
* @param accountId TODO * @param id
* @param domainId TODO * TODO
* @param type TODO * @param accountId
* TODO
* @param domainId
* TODO
* @param type
* TODO
* @return a list of limits that match the criteria * @return a list of limits that match the criteria
*/ */
public List<? extends ResourceLimit> searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal); public List<? extends ResourceLimit> searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal);
/** /**
* Finds the resource limit for a specified account and type. If the account has an infinite limit, will check * Finds the resource limit for a specified account and type. If the account has an infinite limit, will check
* the account's parent domain, and if that limit is also infinite, will return the ROOT domain's limit. * the account's parent domain, and if that limit is also infinite, will return the ROOT domain's limit.
*
* @param account * @param account
* @param type * @param type
* @return resource limit * @return resource limit
@ -69,6 +84,7 @@ public interface ResourceLimitService {
/** /**
* Finds the resource limit for a specified domain and type. If the domain has an infinite limit, will check * Finds the resource limit for a specified domain and type. If the domain has an infinite limit, will check
* up the domain hierarchy * up the domain hierarchy
*
* @param account * @param account
* @param type * @param type
* @return resource limit * @return resource limit
@ -77,31 +93,37 @@ public interface ResourceLimitService {
/** /**
* Increments the resource count * Increments the resource count
*
* @param accountId * @param accountId
* @param type * @param type
* @param delta * @param delta
*/ */
public void incrementResourceCount(long accountId, ResourceType type, Long...delta); public void incrementResourceCount(long accountId, ResourceType type, Long... delta);
/** /**
* Decrements the resource count * Decrements the resource count
*
* @param accountId * @param accountId
* @param type * @param type
* @param delta * @param delta
*/ */
public void decrementResourceCount(long accountId, ResourceType type, Long...delta); public void decrementResourceCount(long accountId, ResourceType type, Long... delta);
/** /**
* Checks if a limit has been exceeded for an account * Checks if a limit has been exceeded for an account
*
* @param account * @param account
* @param type * @param type
* @param count the number of resources being allocated, count will be added to current allocation and compared against maximum allowed allocation * @param count
* @throws ResourceAllocationException * the number of resources being allocated, count will be added to current allocation and compared
* against maximum allowed allocation
* @throws ResourceAllocationException
*/ */
public void checkResourceLimit(Account account, ResourceCount.ResourceType type, long...count) throws ResourceAllocationException; public void checkResourceLimit(Account account, ResourceCount.ResourceType type, long... count) throws ResourceAllocationException;
/** /**
* Gets the count of resources for a resource type and account * Gets the count of resources for a resource type and account
*
* @param account * @param account
* @param type * @param type
* @return count of resources * @return count of resources

View File

@ -28,100 +28,101 @@ import javax.persistence.Id;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name="resource_limit") @Table(name = "resource_limit")
public class ResourceLimitVO implements ResourceLimit { public class ResourceLimitVO implements ResourceLimit {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id") @Column(name = "id")
private Long id = null; private Long id = null;
@Column(name="type") @Column(name = "type")
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private ResourceCount.ResourceType type; private ResourceCount.ResourceType type;
@Column(name="domain_id") @Column(name = "domain_id")
private Long domainId; private Long domainId;
@Column(name="account_id") @Column(name = "account_id")
private Long accountId; private Long accountId;
@Column(name="max") @Column(name = "max")
private Long max; private Long max;
public ResourceLimitVO() {} public ResourceLimitVO() {
}
public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) {
this.type = type; public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) {
this.max = max; this.type = type;
this.max = max;
if (ownerType == ResourceOwnerType.Account) {
if (ownerType == ResourceOwnerType.Account) {
this.accountId = ownerId; this.accountId = ownerId;
} else if (ownerType == ResourceOwnerType.Domain) { } else if (ownerType == ResourceOwnerType.Domain) {
this.domainId = ownerId; this.domainId = ownerId;
} }
} }
@Override @Override
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
@Override @Override
public ResourceType getType() { public ResourceType getType() {
return type; return type;
} }
public void setType(ResourceCount.ResourceType type) { public void setType(ResourceCount.ResourceType type) {
this.type = type; this.type = type;
} }
public Long getDomainId() { public Long getDomainId() {
return domainId; return domainId;
} }
public Long getAccountId() { public Long getAccountId() {
return accountId; return accountId;
} }
@Override @Override
public Long getMax() { public Long getMax() {
return max; return max;
} }
@Override @Override
public void setMax(Long max) { public void setMax(Long max) {
this.max = max; this.max = max;
} }
@Override @Override
public long getOwnerId() { public long getOwnerId() {
if (accountId != null) { if (accountId != null) {
return accountId; return accountId;
} }
return domainId; return domainId;
} }
@Override
public ResourceOwnerType getResourceOwnerType() {
if (accountId != null) {
return ResourceOwnerType.Account;
} else {
return ResourceOwnerType.Domain;
}
}
public void setDomainId(Long domainId) { @Override
this.domainId = domainId; public ResourceOwnerType getResourceOwnerType() {
if (accountId != null) {
return ResourceOwnerType.Account;
} else {
return ResourceOwnerType.Domain;
}
} }
public void setAccountId(Long accountId) { public void setDomainId(Long domainId) {
this.accountId = accountId; this.domainId = domainId;
} }
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
/** /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
@ -142,7 +143,7 @@ public class ApiServer implements HttpRequestHandler {
private static List<String> s_allCommands = null; private static List<String> s_allCommands = null;
private static List<String> s_pluggableServiceCommands = null; private static List<String> s_pluggableServiceCommands = null;
private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer")); private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer"));
static { static {
@ -172,45 +173,45 @@ public class ApiServer implements HttpRequestHandler {
public Properties get_apiCommands() { public Properties get_apiCommands() {
return _apiCommands; return _apiCommands;
} }
public static boolean isPluggableServiceCommand(String cmdClassName){ public static boolean isPluggableServiceCommand(String cmdClassName) {
if(s_pluggableServiceCommands != null){ if (s_pluggableServiceCommands != null) {
if(s_pluggableServiceCommands.contains(cmdClassName)){ if (s_pluggableServiceCommands.contains(cmdClassName)) {
return true; return true;
} }
} }
return false; return false;
} }
private String[] getPluggableServicesApiConfigs(){ private String[] getPluggableServicesApiConfigs() {
List<String> pluggableServicesApiConfigs = new ArrayList<String>(); List<String> pluggableServicesApiConfigs = new ArrayList<String>();
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
List<PluggableService> services = locator.getAllPluggableServices(); List<PluggableService> services = locator.getAllPluggableServices();
for(PluggableService service : services){ for (PluggableService service : services) {
pluggableServicesApiConfigs.add(service.getPropertiesFile()); pluggableServicesApiConfigs.add(service.getPropertiesFile());
} }
return pluggableServicesApiConfigs.toArray(new String[0]); return pluggableServicesApiConfigs.toArray(new String[0]);
} }
private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig){ private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig) {
try{ try {
if(_apiCommands == null){ if (_apiCommands == null) {
_apiCommands = new Properties(); _apiCommands = new Properties();
} }
Properties preProcessedCommands = new Properties(); Properties preProcessedCommands = new Properties();
if (apiConfig != null) { if (apiConfig != null) {
for (String configFile : apiConfig) { for (String configFile : apiConfig) {
File commandsFile = PropertiesUtil.findConfigFile(configFile); File commandsFile = PropertiesUtil.findConfigFile(configFile);
if(commandsFile != null){ if (commandsFile != null) {
try{ try {
preProcessedCommands.load(new FileInputStream(commandsFile)); preProcessedCommands.load(new FileInputStream(commandsFile));
}catch (FileNotFoundException fnfex) { } catch (FileNotFoundException fnfex) {
//in case of a file within a jar in classpath, try to open stream using url // in case of a file within a jar in classpath, try to open stream using url
InputStream stream = PropertiesUtil.openStreamFromURL(configFile); InputStream stream = PropertiesUtil.openStreamFromURL(configFile);
if(stream != null){ if (stream != null) {
preProcessedCommands.load(stream); preProcessedCommands.load(stream);
}else{ } else {
s_logger.error("Unable to find properites file", fnfex); s_logger.error("Unable to find properites file", fnfex);
} }
} }
@ -220,11 +221,11 @@ public class ApiServer implements HttpRequestHandler {
String preProcessedCommand = preProcessedCommands.getProperty((String) key); String preProcessedCommand = preProcessedCommands.getProperty((String) key);
String[] commandParts = preProcessedCommand.split(";"); String[] commandParts = preProcessedCommand.split(";");
_apiCommands.put(key, commandParts[0]); _apiCommands.put(key, commandParts[0]);
if(pluggableServicesConfig){ if (pluggableServicesConfig) {
s_pluggableServiceCommands.add(commandParts[0]); s_pluggableServiceCommands.add(commandParts[0]);
} }
if (commandParts.length > 1) { if (commandParts.length > 1) {
try { try {
short cmdPermissions = Short.parseShort(commandParts[1]); short cmdPermissions = Short.parseShort(commandParts[1]);
@ -245,7 +246,7 @@ public class ApiServer implements HttpRequestHandler {
} }
} }
} }
s_allCommands.addAll(s_adminCommands); s_allCommands.addAll(s_adminCommands);
s_allCommands.addAll(s_resourceDomainAdminCommands); s_allCommands.addAll(s_resourceDomainAdminCommands);
s_allCommands.addAll(s_userCommands); s_allCommands.addAll(s_userCommands);
@ -257,13 +258,13 @@ public class ApiServer implements HttpRequestHandler {
s_logger.error("Exception loading properties file", ioex); s_logger.error("Exception loading properties file", ioex);
} }
} }
public void init(String[] apiConfig) { public void init(String[] apiConfig) {
BaseCmd.setComponents(new ApiResponseHelper()); BaseCmd.setComponents(new ApiResponseHelper());
BaseListCmd.configure(); BaseListCmd.configure();
processConfigFiles(apiConfig, false); processConfigFiles(apiConfig, false);
//get commands for all pluggable services // get commands for all pluggable services
String[] pluggableServicesApiConfigs = getPluggableServicesApiConfigs(); String[] pluggableServicesApiConfigs = getPluggableServicesApiConfigs();
processConfigFiles(pluggableServicesApiConfigs, true); processConfigFiles(pluggableServicesApiConfigs, true);
@ -284,9 +285,9 @@ public class ApiServer implements HttpRequestHandler {
ConfigurationVO apiPortConfig = values.get(0); ConfigurationVO apiPortConfig = values.get(0);
apiPort = Integer.parseInt(apiPortConfig.getValue()); apiPort = Integer.parseInt(apiPortConfig.getValue());
} }
encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())); encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key()));
String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key()); String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key());
if (jsonType != null) { if (jsonType != null) {
jsonContentType = jsonType; jsonContentType = jsonType;
@ -333,7 +334,8 @@ public class ApiServer implements HttpRequestHandler {
if ("response".equalsIgnoreCase(paramValue[0])) { if ("response".equalsIgnoreCase(paramValue[0])) {
responseType = paramValue[1]; responseType = paramValue[1];
} else { } else {
// according to the servlet spec, the parameter map should be in the form (name=String, value=String[]), so // according to the servlet spec, the parameter map should be in the form (name=String,
// value=String[]), so
// parameter values will be stored in an array // parameter values will be stored in an array
parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] }); parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] });
} }
@ -501,7 +503,7 @@ public class ApiServer implements HttpRequestHandler {
SerializationContext.current().setUuidTranslation(true); SerializationContext.current().setUuidTranslation(true);
return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objectId, objectEntityTable); return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objectId, objectEntityTable);
} }
SerializationContext.current().setUuidTranslation(true); SerializationContext.current().setUuidTranslation(true);
return ApiResponseSerializer.toSerializedString(asyncCmd.getResponse(jobId), asyncCmd.getResponseType()); return ApiResponseSerializer.toSerializedString(asyncCmd.getResponse(jobId), asyncCmd.getResponseType());
} else { } else {
@ -512,9 +514,9 @@ public class ApiServer implements HttpRequestHandler {
if (cmdObj instanceof BaseListCmd) { if (cmdObj instanceof BaseListCmd) {
buildAsyncListResponse((BaseListCmd) cmdObj, caller); buildAsyncListResponse((BaseListCmd) cmdObj, caller);
} }
SerializationContext.current().setUuidTranslation(true); SerializationContext.current().setUuidTranslation(true);
return ApiResponseSerializer.toSerializedString((ResponseObject) cmdObj.getResponseObject(), cmdObj.getResponseType()); return ApiResponseSerializer.toSerializedString((ResponseObject) cmdObj.getResponseObject(), cmdObj.getResponseType());
} }
} }
@ -557,10 +559,13 @@ public class ApiServer implements HttpRequestHandler {
auditTrailSb.append(" " + HttpServletResponse.SC_OK + " "); auditTrailSb.append(" " + HttpServletResponse.SC_OK + " ");
auditTrailSb.append(result); auditTrailSb.append(result);
/* /*
* if (command.equals("queryAsyncJobResult")){ //For this command we need to also log job status and job resultcode for * if (command.equals("queryAsyncJobResult")){ //For this command we need to also log job status and job
* resultcode for
* (Pair<String,Object> pair : resultValues){ String key = pair.first(); if (key.equals("jobstatus")){ * (Pair<String,Object> pair : resultValues){ String key = pair.first(); if (key.equals("jobstatus")){
* auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("="); auditTrailSb.append(pair.second()); * auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("=");
* }else if (key.equals("jobresultcode")){ auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("="); * auditTrailSb.append(pair.second());
* }else if (key.equals("jobresultcode")){ auditTrailSb.append(" "); auditTrailSb.append(key);
* auditTrailSb.append("=");
* auditTrailSb.append(pair.second()); } } }else { for (Pair<String,Object> pair : resultValues){ if * auditTrailSb.append(pair.second()); } } }else { for (Pair<String,Object> pair : resultValues){ if
* (pair.first().equals("jobid")){ // Its an async job so report the jobid auditTrailSb.append(" "); * (pair.first().equals("jobid")){ // Its an async job so report the jobid auditTrailSb.append(" ");
* auditTrailSb.append(pair.first()); auditTrailSb.append("="); auditTrailSb.append(pair.second()); } } } * auditTrailSb.append(pair.first()); auditTrailSb.append("="); auditTrailSb.append(pair.second()); } } }
@ -619,7 +624,7 @@ public class ApiServer implements HttpRequestHandler {
String signatureVersion = null; String signatureVersion = null;
String expires = null; String expires = null;
for (String paramName : parameterNames) { for (String paramName : parameterNames) {
// parameters come as name/value pairs in the form String/String[] // parameters come as name/value pairs in the form String/String[]
String paramValue = ((String[]) requestParameters.get(paramName))[0]; String paramValue = ((String[]) requestParameters.get(paramName))[0];
@ -631,11 +636,11 @@ public class ApiServer implements HttpRequestHandler {
apiKey = paramValue; apiKey = paramValue;
} }
else if ("signatureversion".equalsIgnoreCase(paramName)) { else if ("signatureversion".equalsIgnoreCase(paramName)) {
signatureVersion = paramValue; signatureVersion = paramValue;
} else if ("expires".equalsIgnoreCase(paramName)) { } else if ("expires".equalsIgnoreCase(paramName)) {
expires = paramValue; expires = paramValue;
} }
if (unsignedRequest == null) { if (unsignedRequest == null) {
unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
} else { } else {
@ -653,27 +658,27 @@ public class ApiServer implements HttpRequestHandler {
} }
Date expiresTS = null; Date expiresTS = null;
if("3".equals(signatureVersion)){ if ("3".equals(signatureVersion)) {
// New signature authentication. Check for expire parameter and its validity // New signature authentication. Check for expire parameter and its validity
if(expires == null){ if (expires == null) {
s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey);
return false; return false;
} }
synchronized (_dateFormat) { synchronized (_dateFormat) {
try{ try {
expiresTS = _dateFormat.parse(expires); expiresTS = _dateFormat.parse(expires);
} catch (ParseException pe){ } catch (ParseException pe) {
s_logger.info("Incorrect date format for Expires parameter", pe); s_logger.info("Incorrect date format for Expires parameter", pe);
return false; return false;
} }
} }
Date now = new Date(System.currentTimeMillis()); Date now = new Date(System.currentTimeMillis());
if(expiresTS.before(now)){ if (expiresTS.before(now)) {
s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey); s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
return false; return false;
} }
} }
Transaction txn = Transaction.open(Transaction.CLOUD_DB); Transaction txn = Transaction.open(Transaction.CLOUD_DB);
txn.close(); txn.close();
User user = null; User user = null;
@ -861,7 +866,8 @@ public class ApiServer implements HttpRequestHandler {
// FIXME: the following two threads are copied from // FIXME: the following two threads are copied from
// http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java // http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java
// we have to cite a license if we are using this code directly, so we need to add the appropriate citation or modify the // we have to cite a license if we are using this code directly, so we need to add the appropriate citation or
// modify the
// code to be very specific to our needs // code to be very specific to our needs
static class ListenerThread extends Thread { static class ListenerThread extends Thread {
private HttpService _httpService = null; private HttpService _httpService = null;
@ -970,25 +976,25 @@ public class ApiServer implements HttpRequestHandler {
if (errorCode == BaseCmd.UNSUPPORTED_ACTION_ERROR || apiCommandParams == null || apiCommandParams.isEmpty()) { if (errorCode == BaseCmd.UNSUPPORTED_ACTION_ERROR || apiCommandParams == null || apiCommandParams.isEmpty()) {
responseName = "errorresponse"; responseName = "errorresponse";
} else { } else {
Object cmdObj = apiCommandParams.get("command"); Object cmdObj = apiCommandParams.get("command");
//cmd name can be null when "command" parameter is missing in the request // cmd name can be null when "command" parameter is missing in the request
if (cmdObj != null) { if (cmdObj != null) {
String cmdName = ((String[])cmdObj) [0]; String cmdName = ((String[]) cmdObj)[0];
cmdClassName = _apiCommands.getProperty(cmdName); cmdClassName = _apiCommands.getProperty(cmdName);
if (cmdClassName != null) { if (cmdClassName != null) {
Class<?> claz = Class.forName(cmdClassName); Class<?> claz = Class.forName(cmdClassName);
responseName = ((BaseCmd) claz.newInstance()).getCommandName(); responseName = ((BaseCmd) claz.newInstance()).getCommandName();
} else { } else {
responseName = "errorresponse"; responseName = "errorresponse";
} }
} }
} }
ExceptionResponse apiResponse = new ExceptionResponse(); ExceptionResponse apiResponse = new ExceptionResponse();
apiResponse.setErrorCode(errorCode); apiResponse.setErrorCode(errorCode);
apiResponse.setErrorText(errorText); apiResponse.setErrorText(errorText);
apiResponse.setResponseName(responseName); apiResponse.setResponseName(responseName);
SerializationContext.current().setUuidTranslation(true); SerializationContext.current().setUuidTranslation(true);
responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType); responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType);

View File

@ -48,66 +48,75 @@ import com.cloud.utils.component.Manager;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
/** /**
* ConfigurationManager handles adding pods/zones, changing IP ranges, enabling external firewalls, and editing configuration values * ConfigurationManager handles adding pods/zones, changing IP ranges, enabling external firewalls, and editing
* * configuration values
*
*/ */
public interface ConfigurationManager extends ConfigurationService, Manager { public interface ConfigurationManager extends ConfigurationService, Manager {
/**
* Updates a configuration entry with a new value
* @param userId
* @param name
* @param value
*/
void updateConfiguration(long userId, String name, String category, String value);
/** /**
* Creates a new service offering * Updates a configuration entry with a new value
* @param name *
* @param cpu * @param userId
* @param ramSize * @param name
* @param speed * @param value
* @param displayText */
* @param localStorageRequired void updateConfiguration(long userId, String name, String category, String value);
* @param offerHA
* @param domainId /**
* @param hostTag * Creates a new service offering
* @param networkRate TODO *
* @param id * @param name
* @param useVirtualNetwork * @param cpu
* @return ID * @param ramSize
*/ * @param speed
ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vm_typeType, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired, boolean offerHA, boolean limitResourceUse, String tags, Long domainId, String hostTag, Integer networkRate); * @param displayText
* @param localStorageRequired
/** * @param offerHA
* Creates a new disk offering * @param domainId
* @param domainId * @param hostTag
* @param name * @param networkRate
* @param description * TODO
* @param numGibibytes * @param id
* @param tags * @param useVirtualNetwork
* @param isCustomized * @return ID
* @return newly created disk offering */
*/ ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vm_typeType, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired,
DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized); boolean offerHA, boolean limitResourceUse, String tags, Long domainId, String hostTag, Integer networkRate);
/** /**
* Creates a new pod * Creates a new disk offering
* @param userId *
* @param podName * @param domainId
* @param zoneId * @param name
* @param gateway * @param description
* @param cidr * @param numGibibytes
* @param startIp * @param tags
* @param endIp * @param isCustomized
* @param allocationState * @return newly created disk offering
* @param skipGatewayOverlapCheck (true if it is ok to not validate that gateway IP address overlap with Start/End IP of the POD) */
* @return Pod DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized);
*/
HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationState, boolean skipGatewayOverlapCheck); /**
* Creates a new pod
*
* @param userId
* @param podName
* @param zoneId
* @param gateway
* @param cidr
* @param startIp
* @param endIp
* @param allocationState
* @param skipGatewayOverlapCheck
* (true if it is ok to not validate that gateway IP address overlap with Start/End IP of the POD)
* @return Pod
*/
HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationState, boolean skipGatewayOverlapCheck);
/** /**
* Creates a new zone * Creates a new zone
*
* @param userId * @param userId
* @param zoneName * @param zoneName
* @param dns1 * @param dns1
@ -116,108 +125,129 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
* @param internalDns2 * @param internalDns2
* @param zoneType * @param zoneType
* @param allocationState * @param allocationState
* @param networkDomain TODO * @param networkDomain
* @param isSecurityGroupEnabled TODO * TODO
* @param isSecurityGroupEnabled
* TODO
* @return * @return
* @throws * @throws
* @throws * @throws
*/ */
DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String domain, Long domainId, NetworkType zoneType, String allocationState, String networkDomain, boolean isSecurityGroupEnabled); DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String domain, Long domainId, NetworkType zoneType, String allocationState,
String networkDomain, boolean isSecurityGroupEnabled);
/** /**
* Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated IP addresses. * Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated
* @param userId * IP addresses.
* @param vlanDbId *
* @return success/failure * @param userId
*/ * @param vlanDbId
boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId); * @return success/failure
*/
boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId);
/**
/** * Adds/deletes private IPs
* Adds/deletes private IPs *
* @param add - either true or false * @param add
* @param podId * - either true or false
* @param startIP * @param podId
* @param endIP * @param startIP
* @return Message to display to user * @param endIP
* @throws if unable to add private ip range * @return Message to display to user
*/ * @throws if
String changePrivateIPRange(boolean add, long podId, String startIP, String endIP); * unable to add private ip range
*/
/** String changePrivateIPRange(boolean add, long podId, String startIP, String endIP);
* Converts a comma separated list of tags to a List
* @param tags
* @return List of tags
*/
List<String> csvTagsToList(String tags);
/**
* Converts a List of tags to a comma separated list
* @param tags
* @return String containing a comma separated list of tags
*/
String listToCsvTags(List<String> tags);
void checkAccess(Account caller, DataCenter zone) /**
throws PermissionDeniedException; * Converts a comma separated list of tags to a List
*
* @param tags
* @return List of tags
*/
List<String> csvTagsToList(String tags);
void checkServiceOfferingAccess(Account caller, ServiceOffering so) /**
throws PermissionDeniedException; * Converts a List of tags to a comma separated list
*
* @param tags
* @return String containing a comma separated list of tags
*/
String listToCsvTags(List<String> tags);
void checkDiskOfferingAccess(Account caller, DiskOffering dof) void checkAccess(Account caller, DataCenter zone)
throws PermissionDeniedException; throws PermissionDeniedException;
void checkServiceOfferingAccess(Account caller, ServiceOffering so)
/** throws PermissionDeniedException;
void checkDiskOfferingAccess(Account caller, DiskOffering dof)
throws PermissionDeniedException;
/**
* Creates a new network offering * Creates a new network offering
* @param name *
* @param displayText * @param name
* @param trafficType * @param displayText
* @param tags * @param trafficType
* @param networkRate TODO * @param tags
* @param serviceProviderMap TODO * @param networkRate
* @param isDefault TODO * TODO
* @param type TODO * @param serviceProviderMap
* @param systemOnly TODO * TODO
* @param serviceOfferingId * @param isDefault
* @param specifyIpRanges TODO * TODO
* @param id * @param type
* @param specifyVlan; * TODO
* @param conserveMode; * @param systemOnly
* @return network offering object * TODO
* @param serviceOfferingId
* @param specifyIpRanges
* TODO
* @param id
* @param specifyVlan
* ;
* @param conserveMode
* ;
* @return network offering object
*/ */
NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, Integer networkRate, Map<Service, Set<Provider>> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode, Map<Service, Map<Capability, String>> serviceCapabilityMap, boolean specifyIpRanges); NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, Integer networkRate,
Map<Service, Set<Provider>> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode,
Map<Service, Map<Capability, String>> serviceCapabilityMap, boolean specifyIpRanges);
Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, long networkId,
Long physicalNetworkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException;
Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, long networkId, Long physicalNetworkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException;
void createDefaultSystemNetworks(long zoneId) throws ConcurrentOperationException; void createDefaultSystemNetworks(long zoneId) throws ConcurrentOperationException;
HostPodVO getPod(long id); HostPodVO getPod(long id);
ClusterVO getCluster(long id); ClusterVO getCluster(long id);
boolean deleteAccountSpecificVirtualRanges(long accountId); boolean deleteAccountSpecificVirtualRanges(long accountId);
DataCenterVO getZone(long id); DataCenterVO getZone(long id);
/** /**
* Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system. * Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system.
*
* @param id * @param id
* @param name * @param name
* @param startIp * @param startIp
* @param endIp * @param endIp
* @param gateway * @param gateway
* @param netmask * @param netmask
* @param allocationState * @param allocationState
* @return Pod * @return Pod
* @throws * @throws
* @throws * @throws
*/ */
Pod editPod(long id, String name, String startIp, String endIp, String gateway, String netmask, String allocationStateStr); Pod editPod(long id, String name, String startIp, String endIp, String gateway, String netmask, String allocationStateStr);
void checkPodCidrSubnets(long zoneId, Long podIdToBeSkipped, String cidr); void checkPodCidrSubnets(long zoneId, Long podIdToBeSkipped, String cidr);
void checkCidrVlanOverlap(long zoneId, String cidr); void checkCidrVlanOverlap(long zoneId, String cidr);
} }

View File

@ -26,9 +26,12 @@ import com.cloud.configuration.ResourceLimitVO;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
public interface ResourceLimitDao extends GenericDao<ResourceLimitVO, Long> { public interface ResourceLimitDao extends GenericDao<ResourceLimitVO, Long> {
List<ResourceLimitVO> listByOwner(Long ownerId, ResourceOwnerType ownerType); List<ResourceLimitVO> listByOwner(Long ownerId, ResourceOwnerType ownerType);
boolean update(Long id, Long max);
ResourceCount.ResourceType getLimitType(String type); boolean update(Long id, Long max);
ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type);
ResourceCount.ResourceType getLimitType(String type);
ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type);
} }

View File

@ -32,23 +32,23 @@ import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@Local(value={ResourceLimitDao.class}) @Local(value = { ResourceLimitDao.class })
public class ResourceLimitDaoImpl extends GenericDaoBase<ResourceLimitVO, Long> implements ResourceLimitDao { public class ResourceLimitDaoImpl extends GenericDaoBase<ResourceLimitVO, Long> implements ResourceLimitDao {
private SearchBuilder<ResourceLimitVO> IdTypeSearch; private SearchBuilder<ResourceLimitVO> IdTypeSearch;
public ResourceLimitDaoImpl () { public ResourceLimitDaoImpl() {
IdTypeSearch = createSearchBuilder(); IdTypeSearch = createSearchBuilder();
IdTypeSearch.and("type", IdTypeSearch.entity().getType(), SearchCriteria.Op.EQ); IdTypeSearch.and("type", IdTypeSearch.entity().getType(), SearchCriteria.Op.EQ);
IdTypeSearch.and("domainId", IdTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ); IdTypeSearch.and("domainId", IdTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
IdTypeSearch.and("accountId", IdTypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ); IdTypeSearch.and("accountId", IdTypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
IdTypeSearch.done(); IdTypeSearch.done();
} }
@Override @Override
public List<ResourceLimitVO> listByOwner(Long ownerId, ResourceOwnerType ownerType) { public List<ResourceLimitVO> listByOwner(Long ownerId, ResourceOwnerType ownerType) {
SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create(); SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create();
if (ownerType == ResourceOwnerType.Account) { if (ownerType == ResourceOwnerType.Account) {
sc.setParameters("accountId", ownerId); sc.setParameters("accountId", ownerId);
return listBy(sc); return listBy(sc);
} else if (ownerType == ResourceOwnerType.Domain) { } else if (ownerType == ResourceOwnerType.Domain) {
@ -57,44 +57,43 @@ public class ResourceLimitDaoImpl extends GenericDaoBase<ResourceLimitVO, Long>
} else { } else {
return new ArrayList<ResourceLimitVO>(); return new ArrayList<ResourceLimitVO>();
} }
} }
@Override
@Override public boolean update(Long id, Long max) {
public boolean update(Long id, Long max) {
ResourceLimitVO limit = findById(id); ResourceLimitVO limit = findById(id);
if (max != null) if (max != null)
limit.setMax(max); limit.setMax(max);
else else
limit.setMax(new Long(-1)); limit.setMax(new Long(-1));
return update(id, limit); return update(id, limit);
} }
@Override @Override
public ResourceCount.ResourceType getLimitType(String type) { public ResourceCount.ResourceType getLimitType(String type) {
ResourceType[] validTypes = Resource.ResourceType.values(); ResourceType[] validTypes = Resource.ResourceType.values();
for (ResourceType validType : validTypes) { for (ResourceType validType : validTypes) {
if (validType.getName().equals(type)) { if (validType.getName().equals(type)) {
return validType; return validType;
} }
} }
return null; return null;
} }
@Override @Override
public ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type) { public ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type) {
SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create(); SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create();
sc.setParameters("type", type); sc.setParameters("type", type);
if (ownerType == ResourceOwnerType.Account) { if (ownerType == ResourceOwnerType.Account) {
sc.setParameters("accountId", ownerId); sc.setParameters("accountId", ownerId);
return findOneBy(sc); return findOneBy(sc);
} else if (ownerType == ResourceOwnerType.Domain) { } else if (ownerType == ResourceOwnerType.Domain) {
sc.setParameters("domainId", ownerId); sc.setParameters("domainId", ownerId);
return findOneBy(sc); return findOneBy(sc);
} else { } else {
return null; return null;
} }
} }
} }

View File

@ -1,6 +1,6 @@
/** /**
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved * * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
* *
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
* *
@ -149,7 +149,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
AgentManager _agentMgr; AgentManager _agentMgr;
@Inject @Inject
ResourceManager _resourceMgr; ResourceManager _resourceMgr;
@Inject @Inject
IPAddressDao _ipAddressDao; IPAddressDao _ipAddressDao;
@Inject @Inject
VlanDao _vlanDao; VlanDao _vlanDao;
@ -157,29 +157,29 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
NetworkOfferingDao _networkOfferingDao; NetworkOfferingDao _networkOfferingDao;
@Inject @Inject
AccountDao _accountDao; AccountDao _accountDao;
@Inject @Inject
PhysicalNetworkDao _physicalNetworkDao; PhysicalNetworkDao _physicalNetworkDao;
@Inject @Inject
PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao;
@Inject @Inject
AccountManager _accountMgr; AccountManager _accountMgr;
@Inject @Inject
UserStatisticsDao _userStatsDao; UserStatisticsDao _userStatsDao;
@Inject @Inject
NetworkDao _networkDao; NetworkDao _networkDao;
@Inject @Inject
DomainRouterDao _routerDao; DomainRouterDao _routerDao;
@Inject @Inject
LoadBalancerDao _loadBalancerDao; LoadBalancerDao _loadBalancerDao;
@Inject @Inject
PortForwardingRulesDao _portForwardingRulesDao; PortForwardingRulesDao _portForwardingRulesDao;
@Inject @Inject
ConfigurationDao _configDao; ConfigurationDao _configDao;
@Inject @Inject
HostDetailsDao _hostDetailDao; HostDetailsDao _hostDetailDao;
@Inject @Inject
NetworkExternalLoadBalancerDao _networkLBDao; NetworkExternalLoadBalancerDao _networkLBDao;
@Inject @Inject
NetworkServiceMapDao _ntwkSrvcProviderDao; NetworkServiceMapDao _ntwkSrvcProviderDao;
@Inject @Inject
NetworkExternalFirewallDao _networkExternalFirewallDao; NetworkExternalFirewallDao _networkExternalFirewallDao;
@ -187,7 +187,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
ExternalFirewallDeviceDao _externalFirewallDeviceDao; ExternalFirewallDeviceDao _externalFirewallDeviceDao;
@Inject @Inject
protected HostPodDao _podDao = null; protected HostPodDao _podDao = null;
ScheduledExecutorService _executor; ScheduledExecutorService _executor;
private int _externalNetworkStatsInterval; private int _externalNetworkStatsInterval;
private long _defaultLbCapacity; private long _defaultLbCapacity;
@ -198,12 +198,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource) { public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, String deviceName, ServerResource resource) {
String guid; String guid;
PhysicalNetworkVO pNetwork=null; PhysicalNetworkVO pNetwork = null;
NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName);
Transaction txn = null; Transaction txn = null;
long zoneId; long zoneId;
if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null) ) { if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) {
throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," +
" server resource, zone id/physical network id) is not specified or a valid parameter."); " server resource, zone id/physical network id) is not specified or a valid parameter.");
} }
@ -215,12 +215,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
zoneId = pNetwork.getDataCenterId(); zoneId = pNetwork.getDataCenterId();
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder());
if (ntwkSvcProvider == null ) { if (ntwkSvcProvider == null) {
throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() +
" is not enabled in the physical network: " + physicalNetworkId + "to add this device" ); " is not enabled in the physical network: " + physicalNetworkId + "to add this device");
} else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() +
" is in shutdown state in the physical network: " + physicalNetworkId + "to add this device" ); " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device");
} }
URI uri; URI uri;
@ -258,7 +258,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false;
boolean inline = (configParams.get(ApiConstants.INLINE) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.INLINE)) : false; boolean inline = (configParams.get(ApiConstants.INLINE) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.INLINE)) : false;
long capacity = NumbersUtil.parseLong((String)configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); long capacity = NumbersUtil.parseLong((String) configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0);
ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetwork.getId(), ntwkSvcProvider.getProviderName(), ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetwork.getId(), ntwkSvcProvider.getProviderName(),
deviceName, capacity, dedicatedUse, inline); deviceName, capacity, dedicatedUse, inline);
@ -300,7 +300,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
_hostDao.update(hostId, externalLoadBalancer); _hostDao.update(hostId, externalLoadBalancer);
_resourceMgr.deleteHost(hostId, false, false); _resourceMgr.deleteHost(hostId, false, false);
// delete the external load balancer entry // delete the external load balancer entry
_externalLoadBalancerDeviceDao.remove(lbDeviceId); _externalLoadBalancerDeviceDao.remove(lbDeviceId);
return true; return true;
@ -314,19 +314,19 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
public List<Host> listExternalLoadBalancers(long physicalNetworkId, String deviceName) { public List<Host> listExternalLoadBalancers(long physicalNetworkId, String deviceName) {
List<Host> lbHosts = new ArrayList<Host>(); List<Host> lbHosts = new ArrayList<Host>();
NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName);
PhysicalNetworkVO pNetwork=null; PhysicalNetworkVO pNetwork = null;
pNetwork = _physicalNetworkDao.findById(physicalNetworkId); pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if ((pNetwork == null) || (lbNetworkDevice == null)) { if ((pNetwork == null) || (lbNetworkDevice == null)) {
throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid.");
} }
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(),
lbNetworkDevice.getNetworkServiceProvder()); lbNetworkDevice.getNetworkServiceProvder());
//if provider not configured in to physical network, then there can be no instances // if provider not configured in to physical network, then there can be no instances
if (ntwkSvcProvider == null) { if (ntwkSvcProvider == null) {
return null; return null;
} }
List<ExternalLoadBalancerDeviceVO> lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, List<ExternalLoadBalancerDeviceVO> lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId,
@ -359,7 +359,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if (lbDeviceForNetwork != null) { if (lbDeviceForNetwork != null) {
long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId();
ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId);
assert(lbDeviceVo != null); assert (lbDeviceVo != null);
return lbDeviceVo; return lbDeviceVo;
} }
return null; return null;
@ -380,17 +380,18 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb);
while (retry) { while (retry) {
GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock");
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
if (deviceMapLock.lock(120)) { if (deviceMapLock.lock(120)) {
try { try {
boolean dedicatedLB = offering.getDedicatedLB(); // does network offering supports a dedicated load balancer? boolean dedicatedLB = offering.getDedicatedLB(); // does network offering supports a dedicated
// load balancer?
long lbDeviceId; long lbDeviceId;
txn.start(); txn.start();
try { try {
// FIXME: should the device allocation be done during network implement phase or do a // FIXME: should the device allocation be done during network implement phase or do a
// lazy allocation when first rule for the network is configured?? // lazy allocation when first rule for the network is configured??
// find a load balancer device for this network as per the network offering // find a load balancer device for this network as per the network offering
@ -398,7 +399,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
lbDeviceId = lbDevice.getId(); lbDeviceId = lbDevice.getId();
// persist the load balancer device id that will be used for this network. Once a network // persist the load balancer device id that will be used for this network. Once a network
// is implemented on a LB device then later on all rules will be programmed on to same device // is implemented on a LB device then later on all rules will be programmed on to same
// device
NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId);
_networkExternalLBDao.persist(networkLB); _networkExternalLBDao.persist(networkLB);
@ -412,14 +414,16 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
tryLbProvisioning = false; tryLbProvisioning = false;
retry = false; retry = false;
} catch (InsufficientCapacityException exception) { } catch (InsufficientCapacityException exception) {
// if already attempted to provision load balancer then throw out of capacity exception, // if already attempted to provision load balancer then throw out of capacity exception,
if (tryLbProvisioning) { if (tryLbProvisioning) {
retry = false; retry = false;
//TODO: throwing warning instead of error for now as its possible another provider can service this network // TODO: throwing warning instead of error for now as its possible another provider can
// service this network
s_logger.warn("There are no load balancer device with the capacity for implementing this network"); s_logger.warn("There are no load balancer device with the capacity for implementing this network");
throw exception; throw exception;
} else { } else {
tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network tryLbProvisioning = true; // if possible provision a LB appliance in to the physical
// network
} }
} }
} finally { } finally {
@ -433,14 +437,16 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
deviceMapLock.releaseRef(); deviceMapLock.releaseRef();
} }
// there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance // there are no LB devices or there is no free capacity on the devices in the physical network so provision
// a new LB appliance
if (tryLbProvisioning) { if (tryLbProvisioning) {
// check if LB appliance can be dynamically provisioned // check if LB appliance can be dynamically provisioned
List<ExternalLoadBalancerDeviceVO> providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); List<ExternalLoadBalancerDeviceVO> providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider);
if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) {
for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) {
if (lbProviderDevice.getState() == LBDeviceState.Enabled) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) {
// acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, // acquire a private IP from the data center which will be used as management IP of
// provisioned LB appliance,
DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid());
if (dcPrivateIp == null) { if (dcPrivateIp == null) {
throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() +
@ -470,10 +476,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
String publicIf = createLbAnswer.getPublicInterface(); String publicIf = createLbAnswer.getPublicInterface();
String privateIf = createLbAnswer.getPrivateInterface(); String privateIf = createLbAnswer.getPrivateInterface();
//we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer // we have provisioned load balancer so add the appliance as cloudstack provisioned external
String dedicatedLb = offering.getDedicatedLB()?"true":"false"; // load balancer
String dedicatedLb = offering.getDedicatedLB() ? "true" : "false";
//acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) // acquire a public IP to associate with lb appliance (used as subnet IP to make the
// appliance part of private network)
PublicIp publicIp = _networkMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false); PublicIp publicIp = _networkMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false);
String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPNetmask = publicIp.getVlanNetmask();
String publicIPgateway = publicIp.getVlanGateway(); String publicIPgateway = publicIp.getVlanGateway();
@ -481,7 +489,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
String publicIP = publicIp.getAddress().toString(); String publicIP = publicIp.getAddress().toString();
String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb +
"&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&publicipvlan="+ publicIPVlanTag + "&publicipgateway=" + publicIPgateway; "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway;
ExternalLoadBalancerDeviceVO lbAppliance = null; ExternalLoadBalancerDeviceVO lbAppliance = null;
try { try {
lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource()); lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource());
@ -490,7 +498,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
if (lbAppliance != null) { if (lbAppliance != null) {
// mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned // mark the load balancer as cloudstack managed and set parent host id on which lb
// appliance is provisioned
ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId());
managedLb.setIsManagedDevice(true); managedLb.setIsManagedDevice(true);
managedLb.setParentHostId(lbProviderDevice.getHostId()); managedLb.setParentHostId(lbProviderDevice.getHostId());
@ -504,7 +513,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
s_logger.warn("Failed to destroy load balancer appliance created"); s_logger.warn("Failed to destroy load balancer appliance created");
} else { } else {
// release the public & private IP back to dc pool, as the load balancer appliance is now destroyed // release the public & private IP back to dc pool, as the load balancer
// appliance is now destroyed
_dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null);
_networkMgr.releasePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); _networkMgr.releasePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount());
} }
@ -524,9 +534,9 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
@Override @Override
public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException {
long physicalNetworkId = network.getPhysicalNetworkId(); long physicalNetworkId = network.getPhysicalNetworkId();
List<ExternalLoadBalancerDeviceVO> lbDevices =null; List<ExternalLoadBalancerDeviceVO> lbDevices = null;
String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb);
assert(provider != null); assert (provider != null);
if (dedicatedLb) { if (dedicatedLb) {
lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free);
@ -534,7 +544,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
// return first device that is free, fully configured and meant for dedicated use // return first device that is free, fully configured and meant for dedicated use
for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) {
if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) {
return lbdevice; return lbdevice;
} }
} }
} }
@ -547,24 +557,24 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null;
long maxFreeCapacity = 0; long maxFreeCapacity = 0;
// loop through the LB device in the physical network and pick the one with maximum free capacity // loop through the LB device in the physical network and pick the one with maximum free capacity
for (ExternalLoadBalancerDeviceVO lbdevice: lbDevices) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) {
// skip if device is not enabled // skip if device is not enabled
if (lbdevice.getState() != LBDeviceState.Enabled) { if (lbdevice.getState() != LBDeviceState.Enabled) {
continue; continue;
} }
// get the used capacity from the list of guest networks that are mapped to this load balancer // get the used capacity from the list of guest networks that are mapped to this load balancer
List<NetworkExternalLoadBalancerVO> mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); List<NetworkExternalLoadBalancerVO> mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId());
long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty()))? 0 : mappedNetworks.size(); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size();
// get the configured capacity for this device // get the configured capacity for this device
long fullCapacity = lbdevice.getCapacity(); long fullCapacity = lbdevice.getCapacity();
if (fullCapacity == 0) { if (fullCapacity == 0) {
fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default
} }
long freeCapacity = fullCapacity - usedCapacity; long freeCapacity = fullCapacity - usedCapacity;
if (freeCapacity > 0) { if (freeCapacity > 0) {
if (maxFreeCapacityLbdevice == null) { if (maxFreeCapacityLbdevice == null) {
@ -583,7 +593,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
} }
// if we are here then there are no existing LB devices in shared use or the devices in shared use has no free capacity left // if we are here then there are no existing LB devices in shared use or the devices in shared use has no
// free capacity left
// so allocate a new load balancer configured for shared use from the pool of free LB devices // so allocate a new load balancer configured for shared use from the pool of free LB devices
lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free);
if (lbDevices != null && !lbDevices.isEmpty()) { if (lbDevices != null && !lbDevices.isEmpty()) {
@ -603,7 +614,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
@DB @DB
protected boolean freeLoadBalancerForNetwork(Network guestConfig) { protected boolean freeLoadBalancerForNetwork(Network guestConfig) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock");
try { try {
if (deviceMapLock.lock(120)) { if (deviceMapLock.lock(120)) {
@ -619,12 +630,13 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
boolean lbCloudManaged = lbDevice.getIsManagedDevice(); boolean lbCloudManaged = lbDevice.getIsManagedDevice();
if (!lbInUse && !lbCloudManaged) { if (!lbInUse && !lbCloudManaged) {
// this is the last network mapped to the load balancer device so set device allocation state to be free // this is the last network mapped to the load balancer device so set device allocation state to be
// free
lbDevice.setAllocationState(LBDeviceAllocationState.Free); lbDevice.setAllocationState(LBDeviceAllocationState.Free);
_externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice);
} }
//commit the changes before sending agent command to destroy cloudstack managed LB // commit the changes before sending agent command to destroy cloudstack managed LB
txn.commit(); txn.commit();
if (!lbInUse && lbCloudManaged) { if (!lbInUse && lbCloudManaged) {
@ -669,7 +681,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} catch (Exception exception) { } catch (Exception exception) {
txn.rollback(); txn.rollback();
s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage());
}finally { } finally {
deviceMapLock.releaseRef(); deviceMapLock.releaseRef();
} }
@ -680,16 +692,16 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
HostVO fwHost = null; HostVO fwHost = null;
// get the firewall provider (could be either virtual router or external firewall device) for the network // get the firewall provider (could be either virtual router or external firewall device) for the network
String fwProvider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Firewall); String fwProvider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Firewall);
if (fwProvider.equalsIgnoreCase("VirtualRouter")) { if (fwProvider.equalsIgnoreCase("VirtualRouter")) {
//FIXME: use network service provider container framework support to implement on virtual router // FIXME: use network service provider container framework support to implement on virtual router
} else { } else {
NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId()); NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId());
assert (fwDeviceForNetwork != null) : "Why firewall provider is not ready for the network to apply static nat rules?"; assert (fwDeviceForNetwork != null) : "Why firewall provider is not ready for the network to apply static nat rules?";
long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId(); long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId();
ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId); ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId);
fwHost = _hostDao.findById(fwDevice.getHostId()); fwHost = _hostDao.findById(fwDevice.getHostId());
} }
return fwHost; return fwHost;
@ -707,7 +719,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
nic.setState(State.Reserved); nic.setState(State.Reserved);
return _nicDao.persist(nic); return _nicDao.persist(nic);
} }
private NicVO getPlaceholderNic(Network network) { private NicVO getPlaceholderNic(Network network) {
List<NicVO> guestIps = _nicDao.listByNetworkId(network.getId()); List<NicVO> guestIps = _nicDao.listByNetworkId(network.getId());
for (NicVO guestIp : guestIps) { for (NicVO guestIp : guestIps) {
@ -730,7 +742,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
StaticNatRule rule = new StaticNatRuleImpl(fwRule, privateIp); StaticNatRule rule = new StaticNatRuleImpl(fwRule, privateIp);
StaticNatRuleTO ruleTO = new StaticNatRuleTO(rule, vlan.getVlanTag(), publicIp, privateIp); StaticNatRuleTO ruleTO = new StaticNatRuleTO(rule, vlan.getVlanTag(), publicIp, privateIp);
staticNatRules.add(ruleTO); staticNatRules.add(ruleTO);
applyStaticNatRules(staticNatRules, network, firewallHost.getId()); applyStaticNatRules(staticNatRules, network, firewallHost.getId());
} }
@ -765,7 +777,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
return true; return true;
} }
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
if (lbDeviceVO == null) { if (lbDeviceVO == null) {
s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning");
return true; return true;
@ -805,7 +817,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if (mapping == null) { if (mapping == null) {
// Acquire a new guest IP address and save it as the load balancing IP address // Acquire a new guest IP address and save it as the load balancing IP address
String loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null); String loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null);
if (loadBalancingIpAddress == null) { if (loadBalancingIpAddress == null) {
String msg = "Ran out of guest IP addresses."; String msg = "Ran out of guest IP addresses.";
s_logger.error(msg); s_logger.error(msg);
@ -815,14 +827,15 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
// If a NIC doesn't exist for the load balancing IP address, create one // If a NIC doesn't exist for the load balancing IP address, create one
loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId());
if (loadBalancingIpNic == null) { if (loadBalancingIpNic == null) {
loadBalancingIpNic = savePlaceholderNic(network, loadBalancingIpAddress); loadBalancingIpNic = savePlaceholderNic(network, loadBalancingIpAddress);
} }
// Save a mapping between the source IP address and the load balancing IP address NIC // Save a mapping between the source IP address and the load balancing IP address NIC
mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId()); mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId());
_inlineLoadBalancerNicMapDao.persist(mapping); _inlineLoadBalancerNicMapDao.persist(mapping);
// On the firewall provider for the network, create a static NAT rule between the source IP address and the load balancing IP address // On the firewall provider for the network, create a static NAT rule between the source IP
// address and the load balancing IP address
applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address()); applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address());
} else { } else {
loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); loadBalancingIpNic = _nicDao.findById(mapping.getNicId());
@ -832,7 +845,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
// Find the NIC that the mapping refers to // Find the NIC that the mapping refers to
loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); loadBalancingIpNic = _nicDao.findById(mapping.getNicId());
// On the firewall provider for the network, delete the static NAT rule between the source IP address and the load balancing IP address // On the firewall provider for the network, delete the static NAT rule between the source IP
// address and the load balancing IP address
applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address()); applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address());
// Delete the mapping between the source IP address and the load balancing IP address // Delete the mapping between the source IP address and the load balancing IP address
@ -857,7 +871,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
if (loadBalancersToApply.size() > 0) { if (loadBalancersToApply.size() > 0) {
int numLoadBalancersForCommand = loadBalancersToApply.size(); int numLoadBalancersForCommand = loadBalancersToApply.size();
LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand);
long guestVlanTag = Integer.parseInt(network.getBroadcastUri().getHost()); long guestVlanTag = Integer.parseInt(network.getBroadcastUri().getHost());
@ -899,7 +913,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig);
if (lbDeviceVO == null) { if (lbDeviceVO == null) {
s_logger.warn("network shutdwon requested on external load balancer, which did not implement the network." + s_logger.warn("network shutdwon requested on external load balancer, which did not implement the network." +
" Either network implement failed half way through or already network shutdown is completed. So just returning."); " Either network implement failed half way through or already network shutdown is completed. So just returning.");
return true; return true;
} }
@ -923,7 +937,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
} else { } else {
// get the self-ip used by the load balancer // get the self-ip used by the load balancer
NicVO selfipNic = getPlaceholderNic(guestConfig); NicVO selfipNic = getPlaceholderNic(guestConfig);
selfIp = selfipNic.getIp4Address(); selfIp = selfipNic.getIp4Address();
} }
@ -946,7 +960,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
savePlaceholderNic(guestConfig, selfIp); savePlaceholderNic(guestConfig, selfIp);
} else { } else {
// release the self-ip obtained from guest network // release the self-ip obtained from guest network
NicVO selfipNic = getPlaceholderNic(guestConfig); NicVO selfipNic = getPlaceholderNic(guestConfig);
_nicDao.remove(selfipNic.getId()); _nicDao.remove(selfipNic.getId());
// release the load balancer allocated for the network // release the load balancer allocated for the network
@ -970,7 +984,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params); super.configure(name, params);
_externalNetworkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ExternalNetworkStatsInterval.key()), 300); _externalNetworkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ExternalNetworkStatsInterval.key()), 300);
if (_externalNetworkStatsInterval > 0){ if (_externalNetworkStatsInterval > 0) {
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ExternalNetworkMonitor")); _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ExternalNetworkMonitor"));
} }
@ -981,7 +995,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
@Override @Override
public boolean start() { public boolean start() {
if (_externalNetworkStatsInterval > 0){ if (_externalNetworkStatsInterval > 0) {
_executor.scheduleAtFixedRate(new ExternalLoadBalancerDeviceNetworkUsageTask(), _externalNetworkStatsInterval, _externalNetworkStatsInterval, TimeUnit.SECONDS); _executor.scheduleAtFixedRate(new ExternalLoadBalancerDeviceNetworkUsageTask(), _externalNetworkStatsInterval, _externalNetworkStatsInterval, TimeUnit.SECONDS);
} }
return true; return true;
@ -1026,17 +1040,17 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
Map<Long, ExternalNetworkResourceUsageAnswer> lbDeviceUsageAnswerMap = new HashMap<Long, ExternalNetworkResourceUsageAnswer>(); Map<Long, ExternalNetworkResourceUsageAnswer> lbDeviceUsageAnswerMap = new HashMap<Long, ExternalNetworkResourceUsageAnswer>();
List<Long> accountsProcessed = new ArrayList<Long>(); List<Long> accountsProcessed = new ArrayList<Long>();
for (DomainRouterVO domainRouter : domainRoutersInZone) { for (DomainRouterVO domainRouter : domainRoutersInZone) {
long accountId = domainRouter.getAccountId(); long accountId = domainRouter.getAccountId();
if(accountsProcessed.contains(new Long(accountId))){ if (accountsProcessed.contains(new Long(accountId))) {
if(s_logger.isTraceEnabled()){ if (s_logger.isTraceEnabled()) {
s_logger.trace("Networks for Account " + accountId + " are already processed for external network usage, so skipping usage check."); s_logger.trace("Networks for Account " + accountId + " are already processed for external network usage, so skipping usage check.");
} }
continue; continue;
} }
long zoneId = zone.getId(); long zoneId = zone.getId();
List<NetworkVO> networksForAccount = _networkDao.listBy(accountId, zoneId, Network.GuestType.Isolated); List<NetworkVO> networksForAccount = _networkDao.listBy(accountId, zoneId, Network.GuestType.Isolated);
@ -1050,7 +1064,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
continue; continue;
} }
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
if (lbDeviceVO == null) { if (lbDeviceVO == null) {
continue; continue;
} }
@ -1060,7 +1074,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
if (externalLoadBalancer != null) { if (externalLoadBalancer != null) {
Long lbDeviceId = new Long(externalLoadBalancer.getId()); Long lbDeviceId = new Long(externalLoadBalancer.getId());
if(!lbDeviceUsageAnswerMap.containsKey(lbDeviceId)){ if (!lbDeviceUsageAnswerMap.containsKey(lbDeviceId)) {
ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand(); ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand();
lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd);
if (lbAnswer == null || !lbAnswer.getResult()) { if (lbAnswer == null || !lbAnswer.getResult()) {
@ -1070,9 +1084,9 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
continue; continue;
} }
lbDeviceUsageAnswerMap.put(lbDeviceId, lbAnswer); lbDeviceUsageAnswerMap.put(lbDeviceId, lbAnswer);
}else{ } else {
if(s_logger.isTraceEnabled()){ if (s_logger.isTraceEnabled()) {
s_logger.trace("Reusing usage Answer for device id "+ lbDeviceId + "for Network " + network.getId()); s_logger.trace("Reusing usage Answer for device id " + lbDeviceId + "for Network " + network.getId());
} }
lbAnswer = lbDeviceUsageAnswerMap.get(lbDeviceId); lbAnswer = lbDeviceUsageAnswerMap.get(lbDeviceId);
} }
@ -1090,7 +1104,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
manageStatsEntries(false, accountId, zoneId, network, externalLoadBalancer, lbAnswer); manageStatsEntries(false, accountId, zoneId, network, externalLoadBalancer, lbAnswer);
} }
accountsProcessed.add(new Long(accountId)); accountsProcessed.add(new Long(accountId));
} }
} }
@ -1102,23 +1116,23 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
long oldCurrentBytesSent = userStats.getCurrentBytesSent(); long oldCurrentBytesSent = userStats.getCurrentBytesSent();
long oldCurrentBytesReceived = userStats.getCurrentBytesReceived(); long oldCurrentBytesReceived = userStats.getCurrentBytesReceived();
String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + "."; String warning = "Received an external network stats byte count that was less than the stored value. Zone ID: " + userStats.getDataCenterId() + ", account ID: " + userStats.getAccountId() + ".";
userStats.setCurrentBytesSent(newCurrentBytesSent); userStats.setCurrentBytesSent(newCurrentBytesSent);
if (oldCurrentBytesSent > newCurrentBytesSent) { if (oldCurrentBytesSent > newCurrentBytesSent) {
s_logger.warn(warning + "Stored bytes sent: " + oldCurrentBytesSent + ", new bytes sent: " + newCurrentBytesSent + "."); s_logger.warn(warning + "Stored bytes sent: " + oldCurrentBytesSent + ", new bytes sent: " + newCurrentBytesSent + ".");
userStats.setNetBytesSent(oldNetBytesSent + oldCurrentBytesSent); userStats.setNetBytesSent(oldNetBytesSent + oldCurrentBytesSent);
} }
userStats.setCurrentBytesReceived(newCurrentBytesReceived); userStats.setCurrentBytesReceived(newCurrentBytesReceived);
if (oldCurrentBytesReceived > newCurrentBytesReceived) { if (oldCurrentBytesReceived > newCurrentBytesReceived) {
s_logger.warn(warning + "Stored bytes received: " + oldCurrentBytesReceived + ", new bytes received: " + newCurrentBytesReceived + "."); s_logger.warn(warning + "Stored bytes received: " + oldCurrentBytesReceived + ", new bytes received: " + newCurrentBytesReceived + ".");
userStats.setNetBytesReceived(oldNetBytesReceived + oldCurrentBytesReceived); userStats.setNetBytesReceived(oldNetBytesReceived + oldCurrentBytesReceived);
} }
return _userStatsDao.update(userStats.getId(), userStats); return _userStatsDao.update(userStats.getId(), userStats);
} }
//Creates a new stats entry for the specified parameters, if one doesn't already exist. // Creates a new stats entry for the specified parameters, if one doesn't already exist.
private boolean createStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId) { private boolean createStatsEntry(long accountId, long zoneId, long networkId, String publicIp, long hostId) {
HostVO host = _hostDao.findById(hostId); HostVO host = _hostDao.findById(hostId);
UserStatisticsVO userStats = _userStatsDao.findBy(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); UserStatisticsVO userStats = _userStatsDao.findBy(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString());
@ -1135,24 +1149,24 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
DataCenterVO zone = _dcDao.findById(zoneId); DataCenterVO zone = _dcDao.findById(zoneId);
NetworkVO network = _networkDao.findById(networkId); NetworkVO network = _networkDao.findById(networkId);
HostVO host = _hostDao.findById(hostId); HostVO host = _hostDao.findById(hostId);
String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + host.getName(); String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + host.getName();
long newCurrentBytesSent = 0; long newCurrentBytesSent = 0;
long newCurrentBytesReceived = 0; long newCurrentBytesReceived = 0;
if (publicIp != null) { if (publicIp != null) {
long[] bytesSentAndReceived = null; long[] bytesSentAndReceived = null;
statsEntryIdentifier += ", public IP: " + publicIp; statsEntryIdentifier += ", public IP: " + publicIp;
if (host.getType().equals(Host.Type.ExternalLoadBalancer) && externalLoadBalancerIsInline(host)) { if (host.getType().equals(Host.Type.ExternalLoadBalancer) && externalLoadBalancerIsInline(host)) {
// Look up stats for the guest IP address that's mapped to the public IP address // Look up stats for the guest IP address that's mapped to the public IP address
InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp);
if (mapping != null) { if (mapping != null) {
NicVO nic = _nicDao.findById(mapping.getNicId()); NicVO nic = _nicDao.findById(mapping.getNicId());
String loadBalancingIpAddress = nic.getIp4Address(); String loadBalancingIpAddress = nic.getIp4Address();
bytesSentAndReceived = answer.ipBytes.get(loadBalancingIpAddress); bytesSentAndReceived = answer.ipBytes.get(loadBalancingIpAddress);
if (bytesSentAndReceived != null) { if (bytesSentAndReceived != null) {
bytesSentAndReceived[0] = 0; bytesSentAndReceived[0] = 0;
} }
@ -1160,7 +1174,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} else { } else {
bytesSentAndReceived = answer.ipBytes.get(publicIp); bytesSentAndReceived = answer.ipBytes.get(publicIp);
} }
if (bytesSentAndReceived == null) { if (bytesSentAndReceived == null) {
s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp); s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp);
} else { } else {
@ -1174,17 +1188,17 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
return true; return true;
} else { } else {
long vlanTag = Integer.parseInt(broadcastURI.getHost()); long vlanTag = Integer.parseInt(broadcastURI.getHost());
long[] bytesSentAndReceived = answer.guestVlanBytes.get(String.valueOf(vlanTag)); long[] bytesSentAndReceived = answer.guestVlanBytes.get(String.valueOf(vlanTag));
if (bytesSentAndReceived == null) { if (bytesSentAndReceived == null) {
s_logger.warn("Didn't get an external network usage answer for guest VLAN " + vlanTag); s_logger.warn("Didn't get an external network usage answer for guest VLAN " + vlanTag);
} else { } else {
newCurrentBytesSent += bytesSentAndReceived[0]; newCurrentBytesSent += bytesSentAndReceived[0];
newCurrentBytesReceived += bytesSentAndReceived[1]; newCurrentBytesReceived += bytesSentAndReceived[1];
} }
} }
} }
UserStatisticsVO userStats; UserStatisticsVO userStats;
try { try {
userStats = _userStatsDao.lock(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString()); userStats = _userStatsDao.lock(accountId, zoneId, networkId, publicIp, hostId, host.getType().toString());
@ -1212,10 +1226,11 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
/* /*
* Creates/updates all necessary stats entries for an account and zone. * Creates/updates all necessary stats entries for an account and zone.
* Stats entries are created for source NAT IP addresses, static NAT rules, port forwarding rules, and load balancing rules * Stats entries are created for source NAT IP addresses, static NAT rules, port forwarding rules, and load
* balancing rules
*/ */
private boolean manageStatsEntries(boolean create, long accountId, long zoneId, Network network, private boolean manageStatsEntries(boolean create, long accountId, long zoneId, Network network,
HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) { HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) {
String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId; String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId;
Transaction txn = Transaction.open(Transaction.CLOUD_DB); Transaction txn = Transaction.open(Transaction.CLOUD_DB);
try { try {
@ -1390,4 +1405,5 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
return new DeleteHostAnswer(true); return new DeleteHostAnswer(true);
} }
} }

View File

@ -35,7 +35,6 @@ import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.ResourceUnavailableException;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.Network.Capability; import com.cloud.network.Network.Capability;
@ -73,11 +72,14 @@ public interface NetworkManager extends NetworkService {
* @param owner * @param owner
* @param type * @param type
* @param networkId * @param networkId
* @param requestedIp TODO * @param requestedIp
* @param allocatedBy TODO * TODO
* @param allocatedBy
* TODO
* @return * @return
* @throws InsufficientAddressCapacityException * @throws InsufficientAddressCapacityException
*/ */
PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isElastic) throws InsufficientAddressCapacityException; PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isElastic) throws InsufficientAddressCapacityException;
/** /**
@ -129,7 +131,7 @@ public interface NetworkManager extends NetworkService {
void allocate(VirtualMachineProfile<? extends VMInstanceVO> vm, List<Pair<NetworkVO, NicProfile>> networks) throws InsufficientCapacityException, ConcurrentOperationException; void allocate(VirtualMachineProfile<? extends VMInstanceVO> vm, List<Pair<NetworkVO, NicProfile>> networks) throws InsufficientCapacityException, ConcurrentOperationException;
void prepare(VirtualMachineProfile<? extends VMInstanceVO> profile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, void prepare(VirtualMachineProfile<? extends VMInstanceVO> profile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException,
ResourceUnavailableException; ResourceUnavailableException;
void release(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, boolean forced); void release(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, boolean forced);
@ -144,7 +146,7 @@ public interface NetworkManager extends NetworkService {
String getNextAvailableMacAddressInNetwork(long networkConfigurationId) throws InsufficientAddressCapacityException; String getNextAvailableMacAddressInNetwork(long networkConfigurationId) throws InsufficientAddressCapacityException;
boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError) throws ResourceUnavailableException; boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError) throws ResourceUnavailableException;
public boolean validateRule(FirewallRule rule); public boolean validateRule(FirewallRule rule);
List<? extends RemoteAccessVPNServiceProvider> getRemoteAccessVpnElements(); List<? extends RemoteAccessVPNServiceProvider> getRemoteAccessVpnElements();
@ -154,7 +156,7 @@ public interface NetworkManager extends NetworkService {
List<? extends Vlan> listPodVlans(long podId); List<? extends Vlan> listPodVlans(long podId);
Pair<NetworkGuru, NetworkVO> implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, Pair<NetworkGuru, NetworkVO> implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException; InsufficientCapacityException;
List<NetworkVO> listNetworksUsedByVm(long vmId, boolean isSystem); List<NetworkVO> listNetworksUsedByVm(long vmId, boolean isSystem);
@ -169,7 +171,8 @@ public interface NetworkManager extends NetworkService {
/** /**
* @throws InsufficientCapacityException * @throws InsufficientCapacityException
* Associates an ip address list to an account. The list of ip addresses are all addresses associated with the * Associates an ip address list to an account. The list of ip addresses are all addresses associated
* with the
* given vlan id. * given vlan id.
* @param userId * @param userId
* @param accountId * @param accountId
@ -179,7 +182,7 @@ public interface NetworkManager extends NetworkService {
* @throws * @throws
*/ */
boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network networkToAssociateWith) throws InsufficientCapacityException, ConcurrentOperationException, boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network networkToAssociateWith) throws InsufficientCapacityException, ConcurrentOperationException,
ResourceUnavailableException; ResourceUnavailableException;
Nic getNicInNetwork(long vmId, long networkId); Nic getNicInNetwork(long vmId, long networkId);
@ -252,50 +255,50 @@ public interface NetworkManager extends NetworkService {
Long getPhysicalNetworkId(Network network); Long getPhysicalNetworkId(Network network);
boolean getAllowSubdomainAccessGlobal(); boolean getAllowSubdomainAccessGlobal();
boolean isProviderForNetwork(Provider provider, long networkId);
boolean isProviderForNetworkOffering(Provider provider, long networkOfferingId);
void canProviderSupportServices(Map<Provider, Set<Service>> providersMap); boolean isProviderForNetwork(Provider provider, long networkId);
PhysicalNetworkServiceProvider addDefaultSecurityGroupProviderToPhysicalNetwork( boolean isProviderForNetworkOffering(Provider provider, long networkOfferingId);
long physicalNetworkId);
void canProviderSupportServices(Map<Provider, Set<Service>> providersMap);
PhysicalNetworkServiceProvider addDefaultSecurityGroupProviderToPhysicalNetwork(
long physicalNetworkId);
List<PhysicalNetworkSetupInfo> getPhysicalNetworkInfo(long dcId,
HypervisorType hypervisorType);
boolean canAddDefaultSecurityGroup();
List<Service> listNetworkOfferingServices(long networkOfferingId);
boolean areServicesEnabledInZone(long zoneId, long networkOfferingId, String tags, List<Service> services);
List<PhysicalNetworkSetupInfo> getPhysicalNetworkInfo(long dcId,
HypervisorType hypervisorType);
boolean canAddDefaultSecurityGroup();
List<Service> listNetworkOfferingServices(long networkOfferingId);
boolean areServicesEnabledInZone(long zoneId, long networkOfferingId, String tags, List<Service> services);
public Map<PublicIp, Set<Service>> getIpToServices(List<PublicIp> publicIps, boolean rulesRevoked, boolean includingFirewall); public Map<PublicIp, Set<Service>> getIpToServices(List<PublicIp> publicIps, boolean rulesRevoked, boolean includingFirewall);
public Map<Provider, ArrayList<PublicIp>> getProviderToIpList(Network network, Map<PublicIp, Set<Service>> ipToServices); public Map<Provider, ArrayList<PublicIp>> getProviderToIpList(Network network, Map<PublicIp, Set<Service>> ipToServices);
public boolean checkIpForService(IPAddressVO ip, Service service); public boolean checkIpForService(IPAddressVO ip, Service service);
void checkVirtualNetworkCidrOverlap(Long zoneId, String cidr); void checkVirtualNetworkCidrOverlap(Long zoneId, String cidr);
void checkCapabilityForProvider(Set<Provider> providers, Service service, void checkCapabilityForProvider(Set<Provider> providers, Service service,
Capability cap, String capValue); Capability cap, String capValue);
Provider getDefaultUniqueProviderForService(String serviceName); Provider getDefaultUniqueProviderForService(String serviceName);
IpAddress assignElasticIp(long networkId, Account owner, IpAddress assignElasticIp(long networkId, Account owner,
boolean forElasticLb, boolean forElasticIp) boolean forElasticLb, boolean forElasticIp)
throws InsufficientAddressCapacityException; throws InsufficientAddressCapacityException;
boolean handleElasticIpRelease(IpAddress ip); boolean handleElasticIpRelease(IpAddress ip);
void checkNetworkPermissions(Account owner, Network network); void checkNetworkPermissions(Account owner, Network network);
void allocateDirectIp(NicProfile nic, DataCenter dc, void allocateDirectIp(NicProfile nic, DataCenter dc,
VirtualMachineProfile<? extends VirtualMachine> vm, VirtualMachineProfile<? extends VirtualMachine> vm,
Network network, String requestedIp) Network network, String requestedIp)
throws InsufficientVirtualNetworkCapcityException, throws InsufficientVirtualNetworkCapcityException,
InsufficientAddressCapacityException; InsufficientAddressCapacityException;
} }

File diff suppressed because it is too large Load Diff

View File

@ -16,44 +16,45 @@
* *
*/ */
package com.cloud.network.dao; package com.cloud.network.dao;
import java.util.List; import java.util.List;
import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
/* /*
* Data Access Object for user_ip_address and ip_forwarding tables * Data Access Object for user_ip_address and ip_forwarding tables
*/ */
public interface FirewallRulesDao extends GenericDao<FirewallRuleVO, Long> { public interface FirewallRulesDao extends GenericDao<FirewallRuleVO, Long> {
List<FirewallRuleVO> listByIpAndPurposeAndNotRevoked(long ipAddressId, FirewallRule.Purpose purpose); List<FirewallRuleVO> listByIpAndPurposeAndNotRevoked(long ipAddressId, FirewallRule.Purpose purpose);
List<FirewallRuleVO> listByNetworkAndPurposeAndNotRevoked(long networkId, FirewallRule.Purpose purpose); List<FirewallRuleVO> listByNetworkAndPurposeAndNotRevoked(long networkId, FirewallRule.Purpose purpose);
boolean setStateToAdd(FirewallRuleVO rule); boolean setStateToAdd(FirewallRuleVO rule);
boolean revoke(FirewallRuleVO rule); boolean revoke(FirewallRuleVO rule);
boolean releasePorts(long ipAddressId, String protocol, FirewallRule.Purpose purpose, int[] ports); boolean releasePorts(long ipAddressId, String protocol, FirewallRule.Purpose purpose, int[] ports);
List<FirewallRuleVO> listByIpAndPurpose(long ipAddressId, FirewallRule.Purpose purpose); List<FirewallRuleVO> listByIpAndPurpose(long ipAddressId, FirewallRule.Purpose purpose);
List<FirewallRuleVO> listByNetworkAndPurpose(long networkId, FirewallRule.Purpose purpose); List<FirewallRuleVO> listByNetworkAndPurpose(long networkId, FirewallRule.Purpose purpose);
List<FirewallRuleVO> listStaticNatByVmId(long vmId); List<FirewallRuleVO> listStaticNatByVmId(long vmId);
List<FirewallRuleVO> listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose); List<FirewallRuleVO> listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose);
FirewallRuleVO findByRelatedId(long ruleId); FirewallRuleVO findByRelatedId(long ruleId);
List<FirewallRuleVO> listSystemRules(); List<FirewallRuleVO> listSystemRules();
List<FirewallRuleVO> listByIp(long ipAddressId); List<FirewallRuleVO> listByIp(long ipAddressId);
List<FirewallRuleVO> listByIpAndNotRevoked(long ipAddressId); List<FirewallRuleVO> listByIpAndNotRevoked(long ipAddressId);
long countRulesByIpId(long sourceIpId); long countRulesByIpId(long sourceIpId);
}
}

View File

@ -16,8 +16,8 @@
* *
*/ */
package com.cloud.network.dao; package com.cloud.network.dao;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
@ -38,22 +38,23 @@ import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
@Local(value=FirewallRulesDao.class) @DB(txn=false) @Local(value = FirewallRulesDao.class)
public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> implements FirewallRulesDao { @DB(txn = false)
public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> implements FirewallRulesDao {
protected final SearchBuilder<FirewallRuleVO> AllFieldsSearch; protected final SearchBuilder<FirewallRuleVO> AllFieldsSearch;
protected final SearchBuilder<FirewallRuleVO> NotRevokedSearch; protected final SearchBuilder<FirewallRuleVO> NotRevokedSearch;
protected final SearchBuilder<FirewallRuleVO> ReleaseSearch; protected final SearchBuilder<FirewallRuleVO> ReleaseSearch;
protected SearchBuilder<FirewallRuleVO> VmSearch; protected SearchBuilder<FirewallRuleVO> VmSearch;
protected final SearchBuilder<FirewallRuleVO> SystemRuleSearch; protected final SearchBuilder<FirewallRuleVO> SystemRuleSearch;
protected final GenericSearchBuilder<FirewallRuleVO, Long> RulesByIpCount; protected final GenericSearchBuilder<FirewallRuleVO, Long> RulesByIpCount;
protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class); protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class);
protected FirewallRulesDaoImpl() { protected FirewallRulesDaoImpl() {
super(); super();
AllFieldsSearch = createSearchBuilder(); AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("ipId", AllFieldsSearch.entity().getSourceIpAddressId(), Op.EQ); AllFieldsSearch.and("ipId", AllFieldsSearch.entity().getSourceIpAddressId(), Op.EQ);
AllFieldsSearch.and("protocol", AllFieldsSearch.entity().getProtocol(), Op.EQ); AllFieldsSearch.and("protocol", AllFieldsSearch.entity().getProtocol(), Op.EQ);
@ -65,7 +66,7 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
AllFieldsSearch.and("networkId", AllFieldsSearch.entity().getNetworkId(), Op.EQ); AllFieldsSearch.and("networkId", AllFieldsSearch.entity().getNetworkId(), Op.EQ);
AllFieldsSearch.and("related", AllFieldsSearch.entity().getRelated(), Op.EQ); AllFieldsSearch.and("related", AllFieldsSearch.entity().getRelated(), Op.EQ);
AllFieldsSearch.done(); AllFieldsSearch.done();
NotRevokedSearch = createSearchBuilder(); NotRevokedSearch = createSearchBuilder();
NotRevokedSearch.and("ipId", NotRevokedSearch.entity().getSourceIpAddressId(), Op.EQ); NotRevokedSearch.and("ipId", NotRevokedSearch.entity().getSourceIpAddressId(), Op.EQ);
NotRevokedSearch.and("state", NotRevokedSearch.entity().getState(), Op.NEQ); NotRevokedSearch.and("state", NotRevokedSearch.entity().getState(), Op.NEQ);
@ -75,32 +76,32 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
NotRevokedSearch.and("sourcePortEnd", NotRevokedSearch.entity().getSourcePortEnd(), Op.EQ); NotRevokedSearch.and("sourcePortEnd", NotRevokedSearch.entity().getSourcePortEnd(), Op.EQ);
NotRevokedSearch.and("networkId", NotRevokedSearch.entity().getNetworkId(), Op.EQ); NotRevokedSearch.and("networkId", NotRevokedSearch.entity().getNetworkId(), Op.EQ);
NotRevokedSearch.done(); NotRevokedSearch.done();
ReleaseSearch = createSearchBuilder(); ReleaseSearch = createSearchBuilder();
ReleaseSearch.and("protocol", ReleaseSearch.entity().getProtocol(), Op.EQ); ReleaseSearch.and("protocol", ReleaseSearch.entity().getProtocol(), Op.EQ);
ReleaseSearch.and("ipId", ReleaseSearch.entity().getSourceIpAddressId(), Op.EQ); ReleaseSearch.and("ipId", ReleaseSearch.entity().getSourceIpAddressId(), Op.EQ);
ReleaseSearch.and("purpose", ReleaseSearch.entity().getPurpose(), Op.EQ); ReleaseSearch.and("purpose", ReleaseSearch.entity().getPurpose(), Op.EQ);
ReleaseSearch.and("ports", ReleaseSearch.entity().getSourcePortStart(), Op.IN); ReleaseSearch.and("ports", ReleaseSearch.entity().getSourcePortStart(), Op.IN);
ReleaseSearch.done(); ReleaseSearch.done();
SystemRuleSearch = createSearchBuilder(); SystemRuleSearch = createSearchBuilder();
SystemRuleSearch.and("type", SystemRuleSearch.entity().getType(), Op.EQ); SystemRuleSearch.and("type", SystemRuleSearch.entity().getType(), Op.EQ);
SystemRuleSearch.and("ipId", SystemRuleSearch.entity().getSourceIpAddressId(), Op.NULL); SystemRuleSearch.and("ipId", SystemRuleSearch.entity().getSourceIpAddressId(), Op.NULL);
SystemRuleSearch.done(); SystemRuleSearch.done();
RulesByIpCount = createSearchBuilder(Long.class); RulesByIpCount = createSearchBuilder(Long.class);
RulesByIpCount.select(null, Func.COUNT, RulesByIpCount.entity().getId()); RulesByIpCount.select(null, Func.COUNT, RulesByIpCount.entity().getId());
RulesByIpCount.and("ipAddressId", RulesByIpCount.entity().getSourceIpAddressId(), Op.EQ); RulesByIpCount.and("ipAddressId", RulesByIpCount.entity().getSourceIpAddressId(), Op.EQ);
RulesByIpCount.done(); RulesByIpCount.done();
} }
@Override @Override
public List<FirewallRuleVO> listSystemRules() { public List<FirewallRuleVO> listSystemRules() {
SearchCriteria<FirewallRuleVO> sc = SystemRuleSearch.create(); SearchCriteria<FirewallRuleVO> sc = SystemRuleSearch.create();
sc.setParameters("type", FirewallRuleType.System.toString()); sc.setParameters("type", FirewallRuleType.System.toString());
return listBy(sc); return listBy(sc);
} }
@Override @Override
public boolean releasePorts(long ipId, String protocol, FirewallRule.Purpose purpose, int[] ports) { public boolean releasePorts(long ipId, String protocol, FirewallRule.Purpose purpose, int[] ports) {
SearchCriteria<FirewallRuleVO> sc = ReleaseSearch.create(); SearchCriteria<FirewallRuleVO> sc = ReleaseSearch.create();
@ -108,17 +109,17 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
sc.setParameters("ipId", ipId); sc.setParameters("ipId", ipId);
sc.setParameters("purpose", purpose); sc.setParameters("purpose", purpose);
sc.setParameters("ports", ports); sc.setParameters("ports", ports);
int results = remove(sc); int results = remove(sc);
return results == ports.length; return results == ports.length;
} }
@Override @Override
public List<FirewallRuleVO> listByIpAndPurpose(long ipId, FirewallRule.Purpose purpose) { public List<FirewallRuleVO> listByIpAndPurpose(long ipId, FirewallRule.Purpose purpose) {
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create(); SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
sc.setParameters("ipId", ipId); sc.setParameters("ipId", ipId);
sc.setParameters("purpose", purpose); sc.setParameters("purpose", purpose);
return listBy(sc); return listBy(sc);
} }
@ -127,123 +128,122 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create(); SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
sc.setParameters("ipId", ipId); sc.setParameters("ipId", ipId);
sc.setParameters("state", State.Revoke); sc.setParameters("state", State.Revoke);
if (purpose != null) { if (purpose != null) {
sc.setParameters("purpose", purpose); sc.setParameters("purpose", purpose);
} }
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<FirewallRuleVO> listByNetworkAndPurposeAndNotRevoked(long networkId, FirewallRule.Purpose purpose) { public List<FirewallRuleVO> listByNetworkAndPurposeAndNotRevoked(long networkId, FirewallRule.Purpose purpose) {
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create(); SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
sc.setParameters("networkId", networkId); sc.setParameters("networkId", networkId);
sc.setParameters("state", State.Revoke); sc.setParameters("state", State.Revoke);
if (purpose != null) { if (purpose != null) {
sc.setParameters("purpose", purpose); sc.setParameters("purpose", purpose);
} }
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<FirewallRuleVO> listByNetworkAndPurpose(long networkId, FirewallRule.Purpose purpose) { public List<FirewallRuleVO> listByNetworkAndPurpose(long networkId, FirewallRule.Purpose purpose) {
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create(); SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
sc.setParameters("purpose", purpose); sc.setParameters("purpose", purpose);
sc.setParameters("networkId", networkId); sc.setParameters("networkId", networkId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public boolean setStateToAdd(FirewallRuleVO rule) { public boolean setStateToAdd(FirewallRuleVO rule) {
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create(); SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
sc.setParameters("id", rule.getId()); sc.setParameters("id", rule.getId());
sc.setParameters("state", State.Staged); sc.setParameters("state", State.Staged);
rule.setState(State.Add); rule.setState(State.Add);
return update(rule, sc) > 0; return update(rule, sc) > 0;
} }
@Override @Override
public boolean revoke(FirewallRuleVO rule) { public boolean revoke(FirewallRuleVO rule) {
rule.setState(State.Revoke); rule.setState(State.Revoke);
return update(rule.getId(), rule); return update(rule.getId(), rule);
} }
@Override @Override
public List<FirewallRuleVO> listStaticNatByVmId(long vmId) { public List<FirewallRuleVO> listStaticNatByVmId(long vmId) {
IPAddressDao _ipDao = ComponentLocator.getLocator("management-server").getDao(IPAddressDao.class); IPAddressDao _ipDao = ComponentLocator.getLocator("management-server").getDao(IPAddressDao.class);
if (VmSearch == null) { if (VmSearch == null) {
SearchBuilder<IPAddressVO> IpSearch = _ipDao.createSearchBuilder(); SearchBuilder<IPAddressVO> IpSearch = _ipDao.createSearchBuilder();
IpSearch.and("associatedWithVmId", IpSearch.entity().getAssociatedWithVmId(), SearchCriteria.Op.EQ); IpSearch.and("associatedWithVmId", IpSearch.entity().getAssociatedWithVmId(), SearchCriteria.Op.EQ);
IpSearch.and("oneToOneNat", IpSearch.entity().isOneToOneNat(), SearchCriteria.Op.NNULL); IpSearch.and("oneToOneNat", IpSearch.entity().isOneToOneNat(), SearchCriteria.Op.NNULL);
VmSearch = createSearchBuilder(); VmSearch = createSearchBuilder();
VmSearch.and("purpose", VmSearch.entity().getPurpose(), Op.EQ); VmSearch.and("purpose", VmSearch.entity().getPurpose(), Op.EQ);
VmSearch.join("ipSearch", IpSearch, VmSearch.entity().getSourceIpAddressId(), IpSearch.entity().getId(), JoinBuilder.JoinType.INNER); VmSearch.join("ipSearch", IpSearch, VmSearch.entity().getSourceIpAddressId(), IpSearch.entity().getId(), JoinBuilder.JoinType.INNER);
VmSearch.done(); VmSearch.done();
} }
SearchCriteria<FirewallRuleVO> sc = VmSearch.create(); SearchCriteria<FirewallRuleVO> sc = VmSearch.create();
sc.setParameters("purpose", Purpose.StaticNat); sc.setParameters("purpose", Purpose.StaticNat);
sc.setJoinParameters("ipSearch", "associatedWithVmId", vmId); sc.setJoinParameters("ipSearch", "associatedWithVmId", vmId);
return listBy(sc); return listBy(sc);
} }
@Override @DB @Override
public FirewallRuleVO persist(FirewallRuleVO firewallRule) { @DB
public FirewallRuleVO persist(FirewallRuleVO firewallRule) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
FirewallRuleVO dbfirewallRule = super.persist(firewallRule); FirewallRuleVO dbfirewallRule = super.persist(firewallRule);
saveSourceCidrs(firewallRule, firewallRule.getSourceCidrList()); saveSourceCidrs(firewallRule, firewallRule.getSourceCidrList());
txn.commit(); txn.commit();
return dbfirewallRule; return dbfirewallRule;
} }
public void saveSourceCidrs(FirewallRuleVO firewallRule, List<String> cidrList) { public void saveSourceCidrs(FirewallRuleVO firewallRule, List<String> cidrList) {
if (cidrList == null) { if (cidrList == null) {
return; return;
} }
_firewallRulesCidrsDao.persist(firewallRule.getId(), cidrList); _firewallRulesCidrsDao.persist(firewallRule.getId(), cidrList);
} }
@Override @Override
public List<FirewallRuleVO> listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose) { public List<FirewallRuleVO> listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose) {
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create(); SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
sc.setParameters("ipId", ipAddressId); sc.setParameters("ipId", ipAddressId);
sc.setParameters("state", State.Revoke); sc.setParameters("state", State.Revoke);
if (purpose != null) { if (purpose != null) {
sc.setParameters("purpose", purpose); sc.setParameters("purpose", purpose);
} }
if (protocol != null) { if (protocol != null) {
sc.setParameters("protocol", protocol); sc.setParameters("protocol", protocol);
} }
sc.setParameters("sourcePortStart", startPort); sc.setParameters("sourcePortStart", startPort);
sc.setParameters("sourcePortEnd", endPort); sc.setParameters("sourcePortEnd", endPort);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public FirewallRuleVO findByRelatedId(long ruleId) { public FirewallRuleVO findByRelatedId(long ruleId) {
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create(); SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
sc.setParameters("related", ruleId); sc.setParameters("related", ruleId);
sc.setParameters("purpose", Purpose.Firewall); sc.setParameters("purpose", Purpose.Firewall);
return findOneBy(sc); return findOneBy(sc);
} }
@ -251,23 +251,24 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
public List<FirewallRuleVO> listByIp(long ipId) { public List<FirewallRuleVO> listByIp(long ipId) {
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create(); SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
sc.setParameters("ipId", ipId); sc.setParameters("ipId", ipId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<FirewallRuleVO> listByIpAndNotRevoked(long ipId) { public List<FirewallRuleVO> listByIpAndNotRevoked(long ipId) {
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create(); SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
sc.setParameters("ipId", ipId); sc.setParameters("ipId", ipId);
sc.setParameters("state", State.Revoke); sc.setParameters("state", State.Revoke);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public long countRulesByIpId(long sourceIpId) { public long countRulesByIpId(long sourceIpId) {
SearchCriteria<Long> sc = RulesByIpCount.create(); SearchCriteria<Long> sc = RulesByIpCount.create();
sc.setParameters("ipAddressId", sourceIpId); sc.setParameters("ipAddressId", sourceIpId);
return customSearch(sc, null).get(0); return customSearch(sc, null).get(0);
} }
}
}

View File

@ -16,18 +16,24 @@
* *
*/ */
package com.cloud.network.dao; package com.cloud.network.dao;
import java.util.List; import java.util.List;
import com.cloud.network.LoadBalancerVO; import com.cloud.network.LoadBalancerVO;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
public interface LoadBalancerDao extends GenericDao<LoadBalancerVO, Long> { public interface LoadBalancerDao extends GenericDao<LoadBalancerVO, Long> {
List<Long> listInstancesByLoadBalancer(long loadBalancerId); List<Long> listInstancesByLoadBalancer(long loadBalancerId);
List<LoadBalancerVO> listByIpAddress(long ipAddressId);
List<LoadBalancerVO> listByIpAddress(long ipAddressId);
LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort); LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort);
LoadBalancerVO findByAccountAndName(Long accountId, String name); LoadBalancerVO findByAccountAndName(Long accountId, String name);
List<LoadBalancerVO> listByNetworkId(long networkId); List<LoadBalancerVO> listByNetworkId(long networkId);
List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId);
} List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId);
}

View File

@ -16,8 +16,8 @@
* *
*/ */
package com.cloud.network.dao; package com.cloud.network.dao;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.util.ArrayList; import java.util.ArrayList;
@ -35,88 +35,88 @@ import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
@Local(value={LoadBalancerDao.class}) @Local(value = { LoadBalancerDao.class })
public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> implements LoadBalancerDao { public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> implements LoadBalancerDao {
private static final Logger s_logger = Logger.getLogger(LoadBalancerDaoImpl.class); private static final Logger s_logger = Logger.getLogger(LoadBalancerDaoImpl.class);
private static final String LIST_INSTANCES_BY_LOAD_BALANCER = "SELECT vm.id " + private static final String LIST_INSTANCES_BY_LOAD_BALANCER = "SELECT vm.id " +
" FROM vm_instance vm, load_balancer lb, ip_forwarding fwd, user_ip_address ip " + " FROM vm_instance vm, load_balancer lb, ip_forwarding fwd, user_ip_address ip " +
" WHERE lb.id = ? AND " + " WHERE lb.id = ? AND " +
" fwd.group_id = lb.id AND " + " fwd.group_id = lb.id AND " +
" fwd.forwarding = 0 AND " + " fwd.forwarding = 0 AND " +
" fwd.private_ip_address = vm.private_ip_address AND " + " fwd.private_ip_address = vm.private_ip_address AND " +
" lb.ip_address = ip.public_ip_address AND " + " lb.ip_address = ip.public_ip_address AND " +
" ip.data_center_id = vm.data_center_id "; " ip.data_center_id = vm.data_center_id ";
private final SearchBuilder<LoadBalancerVO> ListByIp; private final SearchBuilder<LoadBalancerVO> ListByIp;
private final SearchBuilder<LoadBalancerVO> IpAndPublicPortSearch; private final SearchBuilder<LoadBalancerVO> IpAndPublicPortSearch;
private final SearchBuilder<LoadBalancerVO> AccountAndNameSearch; private final SearchBuilder<LoadBalancerVO> AccountAndNameSearch;
protected final SearchBuilder<LoadBalancerVO> TransitionStateSearch; protected final SearchBuilder<LoadBalancerVO> TransitionStateSearch;
protected final FirewallRulesCidrsDaoImpl _portForwardingRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class); protected final FirewallRulesCidrsDaoImpl _portForwardingRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class);
protected LoadBalancerDaoImpl() { protected LoadBalancerDaoImpl() {
ListByIp = createSearchBuilder(); ListByIp = createSearchBuilder();
ListByIp.and("ipAddressId", ListByIp.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ); ListByIp.and("ipAddressId", ListByIp.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
ListByIp.and("networkId", ListByIp.entity().getNetworkId(), SearchCriteria.Op.EQ); ListByIp.and("networkId", ListByIp.entity().getNetworkId(), SearchCriteria.Op.EQ);
ListByIp.done(); ListByIp.done();
IpAndPublicPortSearch = createSearchBuilder(); IpAndPublicPortSearch = createSearchBuilder();
IpAndPublicPortSearch.and("ipAddressId", IpAndPublicPortSearch.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ); IpAndPublicPortSearch.and("ipAddressId", IpAndPublicPortSearch.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
IpAndPublicPortSearch.and("publicPort", IpAndPublicPortSearch.entity().getSourcePortStart(), SearchCriteria.Op.EQ); IpAndPublicPortSearch.and("publicPort", IpAndPublicPortSearch.entity().getSourcePortStart(), SearchCriteria.Op.EQ);
IpAndPublicPortSearch.done(); IpAndPublicPortSearch.done();
AccountAndNameSearch = createSearchBuilder(); AccountAndNameSearch = createSearchBuilder();
AccountAndNameSearch.and("accountId", AccountAndNameSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountAndNameSearch.and("accountId", AccountAndNameSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountAndNameSearch.and("name", AccountAndNameSearch.entity().getName(), SearchCriteria.Op.EQ); AccountAndNameSearch.and("name", AccountAndNameSearch.entity().getName(), SearchCriteria.Op.EQ);
AccountAndNameSearch.done(); AccountAndNameSearch.done();
TransitionStateSearch = createSearchBuilder(); TransitionStateSearch = createSearchBuilder();
TransitionStateSearch.and("networkId", TransitionStateSearch.entity().getNetworkId(), Op.EQ); TransitionStateSearch.and("networkId", TransitionStateSearch.entity().getNetworkId(), Op.EQ);
TransitionStateSearch.and("state", TransitionStateSearch.entity().getState(), Op.IN); TransitionStateSearch.and("state", TransitionStateSearch.entity().getState(), Op.IN);
TransitionStateSearch.done(); TransitionStateSearch.done();
}
@Override
public List<Long> listInstancesByLoadBalancer(long loadBalancerId) {
Transaction txn = Transaction.currentTxn();
String sql = LIST_INSTANCES_BY_LOAD_BALANCER;
PreparedStatement pstmt = null;
List<Long> instanceList = new ArrayList<Long>();
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, loadBalancerId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Long vmId = rs.getLong(1);
instanceList.add(vmId);
}
} catch (Exception ex) {
s_logger.error("error getting recent usage network stats", ex);
}
return instanceList;
}
@Override
public List<LoadBalancerVO> listByIpAddress(long ipAddressId) {
SearchCriteria<LoadBalancerVO> sc = ListByIp.create();
sc.setParameters("ipAddressId", ipAddressId);
return listBy(sc);
} }
@Override
public List<Long> listInstancesByLoadBalancer(long loadBalancerId) {
Transaction txn = Transaction.currentTxn();
String sql = LIST_INSTANCES_BY_LOAD_BALANCER;
PreparedStatement pstmt = null;
List<Long> instanceList = new ArrayList<Long>();
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, loadBalancerId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Long vmId = rs.getLong(1);
instanceList.add(vmId);
}
} catch (Exception ex) {
s_logger.error("error getting recent usage network stats", ex);
}
return instanceList;
}
@Override
public List<LoadBalancerVO> listByIpAddress(long ipAddressId) {
SearchCriteria<LoadBalancerVO> sc = ListByIp.create();
sc.setParameters("ipAddressId", ipAddressId);
return listBy(sc);
}
@Override @Override
public List<LoadBalancerVO> listByNetworkId(long networkId) { public List<LoadBalancerVO> listByNetworkId(long networkId) {
SearchCriteria<LoadBalancerVO> sc = ListByIp.create(); SearchCriteria<LoadBalancerVO> sc = ListByIp.create();
sc.setParameters("networkId", networkId); sc.setParameters("networkId", networkId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort) { public LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort) {
SearchCriteria<LoadBalancerVO> sc = IpAndPublicPortSearch.create(); SearchCriteria<LoadBalancerVO> sc = IpAndPublicPortSearch.create();
sc.setParameters("ipAddressId", ipAddressId); sc.setParameters("ipAddressId", ipAddressId);
sc.setParameters("publicPort", publicPort); sc.setParameters("publicPort", publicPort);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
@ -126,12 +126,13 @@ public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> im
sc.setParameters("name", name); sc.setParameters("name", name);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId) { public List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId) {
SearchCriteria<LoadBalancerVO> sc = TransitionStateSearch.create(); SearchCriteria<LoadBalancerVO> sc = TransitionStateSearch.create();
sc.setParameters("networkId", networkId); sc.setParameters("networkId", networkId);
sc.setParameters("state", State.Add.toString(), State.Revoke.toString()); sc.setParameters("state", State.Add.toString(), State.Revoke.toString());
return listBy(sc); return listBy(sc);
} }
}
}

View File

@ -46,7 +46,7 @@ public interface NetworkDao extends GenericDao<NetworkVO, Long> {
@Override @Override
@Deprecated @Deprecated
NetworkVO persist(NetworkVO vo); NetworkVO persist(NetworkVO vo);
/** /**
* Retrieves the next available mac address in this network configuration. * Retrieves the next available mac address in this network configuration.
* *
@ -86,9 +86,10 @@ public interface NetworkDao extends GenericDao<NetworkVO, Long> {
List<NetworkVO> listByPhysicalNetworkAndProvider(long physicalNetworkId, String providerName); List<NetworkVO> listByPhysicalNetworkAndProvider(long physicalNetworkId, String providerName);
void persistNetworkServiceProviders(long networkId, Map<String, String> serviceProviderMap); void persistNetworkServiceProviders(long networkId, Map<String, String> serviceProviderMap);
boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap); boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap);
List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType); List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType);
} }

View File

@ -49,7 +49,8 @@ import com.cloud.utils.db.SequenceFetcher;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
@Local(value=NetworkDao.class) @DB(txn=false) @Local(value = NetworkDao.class)
@DB(txn = false)
public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements NetworkDao { public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements NetworkDao {
final SearchBuilder<NetworkVO> AllFieldsSearch; final SearchBuilder<NetworkVO> AllFieldsSearch;
final SearchBuilder<NetworkVO> AccountSearch; final SearchBuilder<NetworkVO> AccountSearch;
@ -60,7 +61,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
final GenericSearchBuilder<NetworkVO, Long> CountByOfferingId; final GenericSearchBuilder<NetworkVO, Long> CountByOfferingId;
final SearchBuilder<NetworkVO> PhysicalNetworkSearch; final SearchBuilder<NetworkVO> PhysicalNetworkSearch;
final SearchBuilder<NetworkVO> securityGroupSearch; final SearchBuilder<NetworkVO> securityGroupSearch;
NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class); NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class);
NetworkDomainDaoImpl _domainsDao = ComponentLocator.inject(NetworkDomainDaoImpl.class); NetworkDomainDaoImpl _domainsDao = ComponentLocator.inject(NetworkDomainDaoImpl.class);
NetworkOpDaoImpl _opDao = ComponentLocator.inject(NetworkOpDaoImpl.class); NetworkOpDaoImpl _opDao = ComponentLocator.inject(NetworkOpDaoImpl.class);
@ -82,7 +83,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ); AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ);
AllFieldsSearch.and("related", AllFieldsSearch.entity().getRelated(), Op.EQ); AllFieldsSearch.and("related", AllFieldsSearch.entity().getRelated(), Op.EQ);
AllFieldsSearch.and("guestType", AllFieldsSearch.entity().getGuestType(), Op.EQ); AllFieldsSearch.and("guestType", AllFieldsSearch.entity().getGuestType(), Op.EQ);
AllFieldsSearch.and("physicalNetwork", AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); AllFieldsSearch.and("physicalNetwork", AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ);
AllFieldsSearch.done(); AllFieldsSearch.done();
AccountSearch = createSearchBuilder(); AccountSearch = createSearchBuilder();
@ -109,7 +110,6 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
AccountNetworkSearch.join("networkSearch", mapJoin, AccountNetworkSearch.entity().getId(), mapJoin.entity().getNetworkId(), JoinBuilder.JoinType.INNER); AccountNetworkSearch.join("networkSearch", mapJoin, AccountNetworkSearch.entity().getId(), mapJoin.entity().getNetworkId(), JoinBuilder.JoinType.INNER);
AccountNetworkSearch.done(); AccountNetworkSearch.done();
ZoneBroadcastUriSearch = createSearchBuilder(); ZoneBroadcastUriSearch = createSearchBuilder();
ZoneBroadcastUriSearch.and("dataCenterId", ZoneBroadcastUriSearch.entity().getDataCenterId(), Op.EQ); ZoneBroadcastUriSearch.and("dataCenterId", ZoneBroadcastUriSearch.entity().getDataCenterId(), Op.EQ);
ZoneBroadcastUriSearch.and("broadcastUri", ZoneBroadcastUriSearch.entity().getBroadcastUri(), Op.EQ); ZoneBroadcastUriSearch.and("broadcastUri", ZoneBroadcastUriSearch.entity().getBroadcastUri(), Op.EQ);
@ -121,24 +121,23 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
join1.and("service", join1.entity().getService(), Op.EQ); join1.and("service", join1.entity().getService(), Op.EQ);
ZoneSecurityGroupSearch.join("services", join1, ZoneSecurityGroupSearch.entity().getId(), join1.entity().getNetworkId(), JoinBuilder.JoinType.INNER); ZoneSecurityGroupSearch.join("services", join1, ZoneSecurityGroupSearch.entity().getId(), join1.entity().getNetworkId(), JoinBuilder.JoinType.INNER);
ZoneSecurityGroupSearch.done(); ZoneSecurityGroupSearch.done();
CountByOfferingId = createSearchBuilder(Long.class); CountByOfferingId = createSearchBuilder(Long.class);
CountByOfferingId.select(null, Func.COUNT, CountByOfferingId.entity().getId()); CountByOfferingId.select(null, Func.COUNT, CountByOfferingId.entity().getId());
CountByOfferingId.and("offeringId", CountByOfferingId.entity().getNetworkOfferingId(), Op.EQ); CountByOfferingId.and("offeringId", CountByOfferingId.entity().getNetworkOfferingId(), Op.EQ);
CountByOfferingId.and("removed", CountByOfferingId.entity().getRemoved(), Op.NULL); CountByOfferingId.and("removed", CountByOfferingId.entity().getRemoved(), Op.NULL);
CountByOfferingId.done(); CountByOfferingId.done();
PhysicalNetworkSearch = createSearchBuilder(); PhysicalNetworkSearch = createSearchBuilder();
PhysicalNetworkSearch.and("physicalNetworkId", PhysicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ); PhysicalNetworkSearch.and("physicalNetworkId", PhysicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ);
PhysicalNetworkSearch.done(); PhysicalNetworkSearch.done();
securityGroupSearch = createSearchBuilder(); securityGroupSearch = createSearchBuilder();
SearchBuilder<NetworkServiceMapVO> join3 = _ntwkSvcMap.createSearchBuilder(); SearchBuilder<NetworkServiceMapVO> join3 = _ntwkSvcMap.createSearchBuilder();
join3.and("service", join3.entity().getService(), Op.EQ); join3.and("service", join3.entity().getService(), Op.EQ);
securityGroupSearch.join("services", join3, securityGroupSearch.entity().getId(), join3.entity().getNetworkId(), JoinBuilder.JoinType.INNER); securityGroupSearch.join("services", join3, securityGroupSearch.entity().getId(), join3.entity().getNetworkId(), JoinBuilder.JoinType.INNER);
securityGroupSearch.done(); securityGroupSearch.done();
_tgMacAddress = _tgs.get("macAddress"); _tgMacAddress = _tgs.get("macAddress");
} }
@ -184,51 +183,52 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
return listBy(sc); return listBy(sc);
} }
@Override @DB @Override
@DB
public NetworkVO persist(NetworkVO network, boolean gc, Map<String, String> serviceProviderMap) { public NetworkVO persist(NetworkVO network, boolean gc, Map<String, String> serviceProviderMap) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
//1) create network // 1) create network
NetworkVO newNetwork = super.persist(network); NetworkVO newNetwork = super.persist(network);
//2) add account to the network // 2) add account to the network
addAccountToNetwork(network.getId(), network.getAccountId(), true); addAccountToNetwork(network.getId(), network.getAccountId(), true);
//3) add network to gc monitor table // 3) add network to gc monitor table
NetworkOpVO op = new NetworkOpVO(network.getId(), gc); NetworkOpVO op = new NetworkOpVO(network.getId(), gc);
_opDao.persist(op); _opDao.persist(op);
//4) add services/providers for the network // 4) add services/providers for the network
persistNetworkServiceProviders(newNetwork.getId(), serviceProviderMap); persistNetworkServiceProviders(newNetwork.getId(), serviceProviderMap);
txn.commit(); txn.commit();
return newNetwork; return newNetwork;
} }
@Override
@Override @DB @DB
public boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap) { public boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
super.update(networkId, network); super.update(networkId, network);
if (serviceProviderMap != null) { if (serviceProviderMap != null) {
_ntwkSvcMap.deleteByNetworkId(networkId); _ntwkSvcMap.deleteByNetworkId(networkId);
persistNetworkServiceProviders(networkId, serviceProviderMap); persistNetworkServiceProviders(networkId, serviceProviderMap);
} }
txn.commit(); txn.commit();
return true; return true;
} }
@Override @Override
@DB @DB
public void persistNetworkServiceProviders(long networkId, Map<String, String> serviceProviderMap) { public void persistNetworkServiceProviders(long networkId, Map<String, String> serviceProviderMap) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
for (String service : serviceProviderMap.keySet()) { for (String service : serviceProviderMap.keySet()) {
NetworkServiceMapVO serviceMap = new NetworkServiceMapVO(networkId, Service.getService(service), Provider.getProvider(serviceProviderMap.get(service))); NetworkServiceMapVO serviceMap = new NetworkServiceMapVO(networkId, Service.getService(service), Provider.getProvider(serviceProviderMap.get(service)));
_ntwkSvcMap.persist(serviceMap); _ntwkSvcMap.persist(serviceMap);
} }
txn.commit(); txn.commit();
} }
protected void addAccountToNetwork(long networkId, long accountId, boolean isOwner) { protected void addAccountToNetwork(long networkId, long accountId, boolean isOwner) {
@ -255,7 +255,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
SequenceFetcher fetch = SequenceFetcher.getInstance(); SequenceFetcher fetch = SequenceFetcher.getInstance();
long seq = fetch.getNextSequence(Long.class, _tgMacAddress, networkConfigId); long seq = fetch.getNextSequence(Long.class, _tgMacAddress, networkConfigId);
seq = seq | _prefix << 40| ((_rand.nextInt(Short.MAX_VALUE) << 16) & 0x00000000ffff0000l); seq = seq | _prefix << 40 | ((_rand.nextInt(Short.MAX_VALUE) << 16) & 0x00000000ffff0000l);
return NetUtils.long2Mac(seq); return NetUtils.long2Mac(seq);
} }
@ -350,9 +350,9 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
sc.setParameters("physicalNetworkId", physicalNetworkId); sc.setParameters("physicalNetworkId", physicalNetworkId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<NetworkVO> listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType){ public List<NetworkVO> listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType) {
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create(); SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
sc.setParameters("trafficType", trafficType); sc.setParameters("trafficType", trafficType);
sc.setParameters("physicalNetworkId", physicalNetworkId); sc.setParameters("physicalNetworkId", physicalNetworkId);
@ -375,7 +375,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<NetworkVO> listBy(long accountId, long dataCenterId, Network.GuestType type, TrafficType trafficType) { public List<NetworkVO> listBy(long accountId, long dataCenterId, Network.GuestType type, TrafficType trafficType) {
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create(); SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
@ -383,16 +383,17 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
sc.setParameters("account", accountId); sc.setParameters("account", accountId);
sc.setParameters("guestType", type); sc.setParameters("guestType", type);
sc.setParameters("trafficType", trafficType); sc.setParameters("trafficType", trafficType);
return listBy(sc, null); return listBy(sc, null);
} }
@Override @Override
public List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType) { public List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType) {
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create(); SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
sc.setParameters("datacenter", zoneId); sc.setParameters("datacenter", zoneId);
sc.setParameters("trafficType", trafficType); sc.setParameters("trafficType", trafficType);
return listBy(sc, null); return listBy(sc, null);
} }
} }

View File

@ -1,6 +1,6 @@
/** /**
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved * * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
* *
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
* *
@ -79,49 +79,60 @@ import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
@Local(value = NetworkElement.class)
@Local(value=NetworkElement.class)
public class CloudZonesNetworkElement extends AdapterBase implements NetworkElement, UserDataServiceProvider { public class CloudZonesNetworkElement extends AdapterBase implements NetworkElement, UserDataServiceProvider {
private static final Logger s_logger = Logger.getLogger(CloudZonesNetworkElement.class); private static final Logger s_logger = Logger.getLogger(CloudZonesNetworkElement.class);
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities(); private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@Inject NetworkDao _networkConfigDao; @Inject
@Inject NetworkManager _networkMgr; NetworkDao _networkConfigDao;
@Inject VirtualNetworkApplianceManager _routerMgr; @Inject
@Inject UserVmManager _userVmMgr; NetworkManager _networkMgr;
@Inject UserVmDao _userVmDao; @Inject
@Inject DomainRouterDao _routerDao; VirtualNetworkApplianceManager _routerMgr;
@Inject ConfigurationManager _configMgr; @Inject
@Inject DataCenterDao _dcDao; UserVmManager _userVmMgr;
@Inject AgentManager _agentManager; @Inject
@Inject ServiceOfferingDao _serviceOfferingDao; UserVmDao _userVmDao;
@Inject
DomainRouterDao _routerDao;
@Inject
ConfigurationManager _configMgr;
@Inject
DataCenterDao _dcDao;
@Inject
AgentManager _agentManager;
@Inject
ServiceOfferingDao _serviceOfferingDao;
private boolean canHandle(DeployDestination dest, TrafficType trafficType) { private boolean canHandle(DeployDestination dest, TrafficType trafficType) {
DataCenterVO dc = (DataCenterVO)dest.getDataCenter(); DataCenterVO dc = (DataCenterVO) dest.getDataCenter();
if (dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName())){ if (dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName())) {
_dcDao.loadDetails(dc); _dcDao.loadDetails(dc);
String dhcpStrategy = dc.getDetail(ZoneConfig.DhcpStrategy.key()); String dhcpStrategy = dc.getDetail(ZoneConfig.DhcpStrategy.key());
if ("external".equalsIgnoreCase(dhcpStrategy)) { if ("external".equalsIgnoreCase(dhcpStrategy)) {
return true; return true;
} }
} }
return false; return false;
} }
@Override @Override
public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientCapacityException {
if (!canHandle(dest, offering.getTrafficType())) { if (!canHandle(dest, offering.getTrafficType())) {
return false; return false;
} }
return true; return true;
} }
@Override @Override
public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientCapacityException, ResourceUnavailableException {
return true; return true;
} }
@ -129,39 +140,39 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) { public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) {
return true; return true;
} }
@Override @Override
public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
return false; //assume that the agent will remove userdata etc return false; // assume that the agent will remove userdata etc
} }
@Override @Override
public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException{ public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException {
return false; //assume that the agent will remove userdata etc return false; // assume that the agent will remove userdata etc
} }
@Override @Override
public Provider getProvider() { public Provider getProvider() {
return Provider.ExternalDhcpServer; return Provider.ExternalDhcpServer;
} }
@Override @Override
public Map<Service, Map<Capability, String>> getCapabilities() { public Map<Service, Map<Capability, String>> getCapabilities() {
return capabilities; return capabilities;
} }
private static Map<Service, Map<Capability, String>> setCapabilities() { private static Map<Service, Map<Capability, String>> setCapabilities() {
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>(); Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
capabilities.put(Service.UserData, null); capabilities.put(Service.UserData, null);
return capabilities; return capabilities;
} }
private VmDataCommand generateVmDataCommand( String vmPrivateIpAddress, private VmDataCommand generateVmDataCommand(String vmPrivateIpAddress,
String userData, String serviceOffering, String zoneName, String guestIpAddress, String vmName, String vmInstanceName, long vmId, String publicKey) { String userData, String serviceOffering, String zoneName, String guestIpAddress, String vmName, String vmInstanceName, long vmId, String publicKey) {
VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName); VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName);
cmd.addVmData("userdata", "user-data", userData); cmd.addVmData("userdata", "user-data", userData);
cmd.addVmData("metadata", "service-offering", serviceOffering); cmd.addVmData("metadata", "service-offering", serviceOffering);
cmd.addVmData("metadata", "availability-zone", zoneName); cmd.addVmData("metadata", "availability-zone", zoneName);
@ -197,14 +208,14 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
public boolean addPasswordAndUserdata(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) public boolean addPasswordAndUserdata(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
if (canHandle(dest, network.getTrafficType())) { if (canHandle(dest, network.getTrafficType())) {
if (vm.getType() != VirtualMachine.Type.User) { if (vm.getType() != VirtualMachine.Type.User) {
return false; return false;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm; VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
_userVmDao.loadDetails((UserVmVO) uservm.getVirtualMachine()); _userVmDao.loadDetails((UserVmVO) uservm.getVirtualMachine());
String password = (String)uservm.getParameter(VirtualMachineProfile.Param.VmPassword); String password = (String) uservm.getParameter(VirtualMachineProfile.Param.VmPassword);
String userData = uservm.getVirtualMachine().getUserData(); String userData = uservm.getVirtualMachine().getUserData();
String sshPublicKey = uservm.getVirtualMachine().getDetail("SSH.PublicKey"); String sshPublicKey = uservm.getVirtualMachine().getDetail("SSH.PublicKey");
@ -219,7 +230,8 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
cmds.addCommand( cmds.addCommand(
"vmdata", "vmdata",
generateVmDataCommand(nic.getIp4Address(), userData, serviceOffering, zoneName, nic.getIp4Address(), uservm.getVirtualMachine().getHostName(), uservm.getVirtualMachine().getInstanceName(), uservm.getId(), sshPublicKey)); generateVmDataCommand(nic.getIp4Address(), userData, serviceOffering, zoneName, nic.getIp4Address(), uservm.getVirtualMachine().getHostName(), uservm.getVirtualMachine().getInstanceName(),
uservm.getId(), sshPublicKey));
try { try {
_agentManager.send(dest.getHost().getId(), cmds); _agentManager.send(dest.getHost().getId(), cmds);
} catch (OperationTimedoutException e) { } catch (OperationTimedoutException e) {
@ -242,9 +254,10 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
@Override @Override
public boolean verifyServicesCombination(List<String> services) { public boolean verifyServicesCombination(List<String> services) {
return true; return true;
} }
} }

View File

@ -1,6 +1,6 @@
/** /**
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved * * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
* *
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
* *
@ -52,73 +52,73 @@ import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;
@Local(value=NetworkElement.class) @Local(value = NetworkElement.class)
public class ExternalDhcpElement extends AdapterBase implements NetworkElement, DhcpServiceProvider { public class ExternalDhcpElement extends AdapterBase implements NetworkElement, DhcpServiceProvider {
private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class); private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class);
@Inject ExternalDhcpManager _dhcpMgr; @Inject
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities(); ExternalDhcpManager _dhcpMgr;
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) {
DataCenter dc = dest.getDataCenter();
Pod pod = dest.getPod();
if ((pod != null && pod.getExternalDhcp()) && dc.getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest
&& networkType == Network.GuestType.Shared) {
s_logger.debug("External DHCP can handle");
return true;
}
return false; private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) {
} DataCenter dc = dest.getDataCenter();
Pod pod = dest.getPod();
if ((pod != null && pod.getExternalDhcp()) && dc.getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest
&& networkType == Network.GuestType.Shared) {
s_logger.debug("External DHCP can handle");
return true;
}
return false;
}
private static Map<Service, Map<Capability, String>> setCapabilities() { private static Map<Service, Map<Capability, String>> setCapabilities() {
//No external dhcp support for Acton release // No external dhcp support for Acton release
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>(); Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
// capabilities.put(Service.Dhcp, null); // capabilities.put(Service.Dhcp, null);
return capabilities; return capabilities;
} }
@Override
public Map<Service, Map<Capability, String>> getCapabilities() {
return capabilities;
}
@Override @Override
public Provider getProvider() { public Map<Service, Map<Capability, String>> getCapabilities() {
return Provider.ExternalDhcpServer; return capabilities;
} }
@Override @Override
public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) public Provider getProvider() {
throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { return Provider.ExternalDhcpServer;
if (!canHandle(dest, offering.getTrafficType(), network.getGuestType())) { }
return false;
}
return true;
}
@Override @Override
public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context)
ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
return true; if (!canHandle(dest, offering.getTrafficType(), network.getGuestType())) {
} return false;
}
return true;
}
@Override @Override
public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest,
throws ConcurrentOperationException, ResourceUnavailableException { ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
return true; return true;
} }
@Override @Override
public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context)
return true; throws ConcurrentOperationException, ResourceUnavailableException {
} return true;
}
@Override @Override
public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
return true; return true;
} }
@Override
public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException {
return true;
}
@Override @Override
public boolean isReady(PhysicalNetworkServiceProvider provider) { public boolean isReady(PhysicalNetworkServiceProvider provider) {
@ -142,12 +142,12 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement,
throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
Host host = dest.getHost(); Host host = dest.getHost();
if (host.getHypervisorType() == HypervisorType.BareMetal || !canHandle(dest, network.getTrafficType(), network.getGuestType())) { if (host.getHypervisorType() == HypervisorType.BareMetal || !canHandle(dest, network.getTrafficType(), network.getGuestType())) {
//BareMetalElement or DhcpElement handle this // BareMetalElement or DhcpElement handle this
return false; return false;
} }
return _dhcpMgr.addVirtualMachineIntoNetwork(network, nic, vm, dest, context); return _dhcpMgr.addVirtualMachineIntoNetwork(network, nic, vm, dest, context);
} }
@Override @Override
public boolean verifyServicesCombination(List<String> services) { public boolean verifyServicesCombination(List<String> services) {
return true; return true;

View File

@ -1,6 +1,6 @@
/** /**
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved * * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
* *
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
* *
@ -41,7 +41,6 @@ import com.cloud.api.response.F5LoadBalancerResponse;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO; import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeployDestination;
@ -57,15 +56,15 @@ import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.ExternalLoadBalancerDeviceManager; import com.cloud.network.ExternalLoadBalancerDeviceManager;
import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl;
import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.ExternalLoadBalancerDeviceVO;
import com.cloud.network.NetworkExternalLoadBalancerVO;
import com.cloud.network.NetworkVO;
import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.network.Network.Capability; import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service; import com.cloud.network.Network.Service;
import com.cloud.network.NetworkExternalLoadBalancerVO;
import com.cloud.network.NetworkManager; import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PhysicalNetworkVO;
@ -91,36 +90,47 @@ import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;
import com.google.gson.Gson; import com.google.gson.Gson;
@Local(value=NetworkElement.class) @Local(value = NetworkElement.class)
public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, IpDeployer, F5ExternalLoadBalancerElementService, ExternalLoadBalancerDeviceManager { public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, IpDeployer, F5ExternalLoadBalancerElementService, ExternalLoadBalancerDeviceManager {
private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class); private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class);
@Inject NetworkManager _networkManager; @Inject
@Inject ConfigurationManager _configMgr; NetworkManager _networkManager;
@Inject NetworkServiceMapDao _ntwkSrvcDao; @Inject
@Inject DataCenterDao _dcDao; ConfigurationManager _configMgr;
@Inject PhysicalNetworkDao _physicalNetworkDao; @Inject
@Inject HostDao _hostDao; NetworkServiceMapDao _ntwkSrvcDao;
@Inject ExternalLoadBalancerDeviceDao _lbDeviceDao; @Inject
@Inject NetworkExternalLoadBalancerDao _networkLBDao; DataCenterDao _dcDao;
@Inject NetworkDao _networkDao; @Inject
@Inject HostDetailsDao _detailsDao; PhysicalNetworkDao _physicalNetworkDao;
@Inject ConfigurationDao _configDao; @Inject
HostDao _hostDao;
@Inject
ExternalLoadBalancerDeviceDao _lbDeviceDao;
@Inject
NetworkExternalLoadBalancerDao _networkLBDao;
@Inject
NetworkDao _networkDao;
@Inject
HostDetailsDao _detailsDao;
@Inject
ConfigurationDao _configDao;
private boolean canHandle(Network config) { private boolean canHandle(Network config) {
if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) { if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) {
s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType()); s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType());
return false; return false;
} }
return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), Service.Lb, Network.Provider.F5BigIp));
_ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), Service.Lb, Network.Provider.F5BigIp));
} }
@Override @Override
public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientNetworkCapacityException { public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientNetworkCapacityException {
if (!canHandle(guestConfig)) { if (!canHandle(guestConfig)) {
return false; return false;
} }
@ -128,18 +138,20 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
try { try {
return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig); return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig);
} catch (InsufficientCapacityException capacityException) { } catch (InsufficientCapacityException capacityException) {
// TODO: handle out of capacity exception in graceful manner when multiple providers are avaialble for the network // TODO: handle out of capacity exception in graceful manner when multiple providers are avaialble for the
// network
return false; return false;
} }
} }
@Override @Override
public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientNetworkCapacityException, ResourceUnavailableException {
return true; return true;
} }
@Override @Override
public boolean release(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) { public boolean release(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) {
return true; return true;
} }
@ -148,75 +160,75 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
if (!canHandle(guestConfig)) { if (!canHandle(guestConfig)) {
return false; return false;
} }
try { try {
return manageGuestNetworkWithExternalLoadBalancer(false, guestConfig); return manageGuestNetworkWithExternalLoadBalancer(false, guestConfig);
} catch (InsufficientCapacityException capacityException) { } catch (InsufficientCapacityException capacityException) {
// TODO: handle out of capacity exception // TODO: handle out of capacity exception
return false; return false;
} }
} }
@Override @Override
public boolean destroy(Network config) { public boolean destroy(Network config) {
return true; return true;
} }
@Override @Override
public boolean validateLBRule(Network network, LoadBalancingRule rule) { public boolean validateLBRule(Network network, LoadBalancingRule rule) {
return true; return true;
} }
@Override @Override
public boolean applyLBRules(Network config, List<LoadBalancingRule> rules) throws ResourceUnavailableException { public boolean applyLBRules(Network config, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
if (!canHandle(config)) { if (!canHandle(config)) {
return false; return false;
} }
return applyLoadBalancerRules(config, rules); return applyLoadBalancerRules(config, rules);
} }
@Override @Override
public Map<Service, Map<Capability, String>> getCapabilities() { public Map<Service, Map<Capability, String>> getCapabilities() {
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>(); Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
// Set capabilities for LB service
Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
// Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn");
// specifies that F5 BIG IP network element can provide shared mode only // Set capabilities for LB service
lbCapabilities.put(Capability.SupportedLBIsolation, "shared"); Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
// Specifies that load balancing rules can be made for either TCP or UDP traffic // Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp"); lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn");
// Specifies that this element can measure network usage on a per public IP basis
lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
// Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs
lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional");
LbStickinessMethod method; // specifies that F5 BIG IP network element can provide shared mode only
List <LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>(); lbCapabilities.put(Capability.SupportedLBIsolation, "shared");
method = new LbStickinessMethod(StickinessMethodType.LBCookieBased,"This is cookie based sticky method, can be used only for http");
methodList.add(method);
method.addParam("holdtime", false, "time period for which persistence is in effect.",false);
method = new LbStickinessMethod(StickinessMethodType.SourceBased,"This is source based sticky method, can be used for any type of protocol."); // Specifies that load balancing rules can be made for either TCP or UDP traffic
methodList.add(method); lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
method.addParam("holdtime", false, "time period for which persistence is in effect.",false);
Gson gson = new Gson(); // Specifies that this element can measure network usage on a per public IP basis
String stickyMethodList = gson.toJson(methodList); lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
lbCapabilities.put(Capability.SupportedStickinessMethods,stickyMethodList);
capabilities.put(Service.Lb, lbCapabilities); // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs
lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional");
return capabilities;
LbStickinessMethod method;
List<LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>();
method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http");
methodList.add(method);
method.addParam("holdtime", false, "time period for which persistence is in effect.", false);
method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based sticky method, can be used for any type of protocol.");
methodList.add(method);
method.addParam("holdtime", false, "time period for which persistence is in effect.", false);
Gson gson = new Gson();
String stickyMethodList = gson.toJson(methodList);
lbCapabilities.put(Capability.SupportedStickinessMethods, stickyMethodList);
capabilities.put(Service.Lb, lbCapabilities);
return capabilities;
} }
@Override @Override
public Provider getProvider() { public Provider getProvider() {
return Provider.F5BigIp; return Provider.F5BigIp;
@ -258,8 +270,8 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Deprecated @Deprecated
public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd) { public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd) {
Long zoneId = cmd.getZoneId(); Long zoneId = cmd.getZoneId();
DataCenterVO zone =null; DataCenterVO zone = null;
PhysicalNetworkVO pNetwork=null; PhysicalNetworkVO pNetwork = null;
ExternalLoadBalancerDeviceVO lbDeviceVO = null; ExternalLoadBalancerDeviceVO lbDeviceVO = null;
HostVO lbHost = null; HostVO lbHost = null;
@ -279,7 +291,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, (ServerResource) new F5BigIpResource()); lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, (ServerResource) new F5BigIpResource());
if (lbDeviceVO != null) { if (lbDeviceVO != null) {
lbHost = _hostDao.findById(lbDeviceVO.getHostId()); lbHost = _hostDao.findById(lbDeviceVO.getHostId());
} }
return lbHost; return lbHost;
@ -295,8 +307,8 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Deprecated @Deprecated
public List<Host> listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd) { public List<Host> listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd) {
Long zoneId = cmd.getZoneId(); Long zoneId = cmd.getZoneId();
DataCenterVO zone =null; DataCenterVO zone = null;
PhysicalNetworkVO pNetwork=null; PhysicalNetworkVO pNetwork = null;
if (zoneId != null) { if (zoneId != null) {
zone = _dcDao.findById(zoneId); zone = _dcDao.findById(zoneId);
@ -378,7 +390,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
Long physcialNetworkId = cmd.getPhysicalNetworkId(); Long physcialNetworkId = cmd.getPhysicalNetworkId();
Long lbDeviceId = cmd.getLoadBalancerDeviceId(); Long lbDeviceId = cmd.getLoadBalancerDeviceId();
PhysicalNetworkVO pNetwork = null; PhysicalNetworkVO pNetwork = null;
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO> (); List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO>();
if (physcialNetworkId == null && lbDeviceId == null) { if (physcialNetworkId == null && lbDeviceId == null) {
throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified"); throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified");
@ -451,7 +463,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
response.setObjectName("f5loadbalancer"); response.setObjectName("f5loadbalancer");
return response; return response;
} }
@Override @Override
public boolean verifyServicesCombination(List<String> services) { public boolean verifyServicesCombination(List<String> services) {
return true; return true;
@ -459,7 +471,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Override @Override
public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service) throws ResourceUnavailableException { public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service) throws ResourceUnavailableException {
// return true, as IP will be associated as part of LB rule configuration // return true, as IP will be associated as part of LB rule configuration
return false; return false;
} }

View File

@ -1,6 +1,6 @@
/** /**
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved * * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
* *
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
* *
@ -26,6 +26,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.ejb.Local; import javax.ejb.Local;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.api.commands.AddExternalFirewallCmd; import com.cloud.api.commands.AddExternalFirewallCmd;
@ -41,8 +42,8 @@ import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ConcurrentOperationException;
@ -54,14 +55,14 @@ import com.cloud.host.Host;
import com.cloud.host.HostVO; import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao; import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.Network; import com.cloud.network.ExternalFirewallDeviceManagerImpl;
import com.cloud.network.ExternalFirewallDeviceVO;
import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState; import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.Network;
import com.cloud.network.Network.Capability; import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service; import com.cloud.network.Network.Service;
import com.cloud.network.ExternalFirewallDeviceManagerImpl;
import com.cloud.network.ExternalFirewallDeviceVO;
import com.cloud.network.NetworkExternalFirewallVO; import com.cloud.network.NetworkExternalFirewallVO;
import com.cloud.network.NetworkManager; import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO; import com.cloud.network.NetworkVO;
@ -90,28 +91,41 @@ import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;
@Local(value=NetworkElement.class) @Local(value = NetworkElement.class)
public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceManagerImpl implements SourceNatServiceProvider, FirewallServiceProvider, public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceManagerImpl implements SourceNatServiceProvider, FirewallServiceProvider,
PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer, JuniperSRXFirewallElementService{ PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer, JuniperSRXFirewallElementService {
private static final Logger s_logger = Logger.getLogger(JuniperSRXExternalFirewallElement.class); private static final Logger s_logger = Logger.getLogger(JuniperSRXExternalFirewallElement.class);
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities(); private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@Inject NetworkManager _networkManager; @Inject
@Inject HostDao _hostDao; NetworkManager _networkManager;
@Inject ConfigurationManager _configMgr; @Inject
@Inject NetworkOfferingDao _networkOfferingDao; HostDao _hostDao;
@Inject NetworkDao _networksDao; @Inject
@Inject DataCenterDao _dcDao; ConfigurationManager _configMgr;
@Inject PhysicalNetworkDao _physicalNetworkDao; @Inject
@Inject ExternalFirewallDeviceDao _fwDevicesDao; NetworkOfferingDao _networkOfferingDao;
@Inject NetworkExternalFirewallDao _networkFirewallDao; @Inject
@Inject NetworkDao _networkDao; NetworkDao _networksDao;
@Inject NetworkServiceMapDao _ntwkSrvcDao; @Inject
@Inject HostDetailsDao _hostDetailDao; DataCenterDao _dcDao;
@Inject ConfigurationDao _configDao; @Inject
PhysicalNetworkDao _physicalNetworkDao;
@Inject
ExternalFirewallDeviceDao _fwDevicesDao;
@Inject
NetworkExternalFirewallDao _networkFirewallDao;
@Inject
NetworkDao _networkDao;
@Inject
NetworkServiceMapDao _ntwkSrvcDao;
@Inject
HostDetailsDao _hostDetailDao;
@Inject
ConfigurationDao _configDao;
private boolean canHandle(Network network, Service service) { private boolean canHandle(Network network, Service service) {
DataCenter zone = _configMgr.getZone(network.getDataCenterId()); DataCenter zone = _configMgr.getZone(network.getDataCenterId());
if ((zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() != Network.GuestType.Isolated) || (zone.getNetworkType() == NetworkType.Basic && network.getGuestType() != Network.GuestType.Shared)) { if ((zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() != Network.GuestType.Isolated) || (zone.getNetworkType() == NetworkType.Basic && network.getGuestType() != Network.GuestType.Shared)) {
@ -130,20 +144,21 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
return false; return false;
} }
} }
return true; return true;
} }
@Override @Override
public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientNetworkCapacityException { public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientNetworkCapacityException {
DataCenter zone = _configMgr.getZone(network.getDataCenterId()); DataCenter zone = _configMgr.getZone(network.getDataCenterId());
//don't have to implement network is Basic zone // don't have to implement network is Basic zone
if (zone.getNetworkType() == NetworkType.Basic) { if (zone.getNetworkType() == NetworkType.Basic) {
s_logger.debug("Not handling network implement in zone of type " + NetworkType.Basic); s_logger.debug("Not handling network implement in zone of type " + NetworkType.Basic);
return false; return false;
} }
if (!canHandle(network, null)) { if (!canHandle(network, null)) {
return false; return false;
} }
@ -151,13 +166,15 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
try { try {
return manageGuestNetworkWithExternalFirewall(true, network); return manageGuestNetworkWithExternalFirewall(true, network);
} catch (InsufficientCapacityException capacityException) { } catch (InsufficientCapacityException capacityException) {
// TODO: handle out of capacity exception in more gracefule manner when multiple providers are present for the network // TODO: handle out of capacity exception in more gracefule manner when multiple providers are present for
// the network
return false; return false;
} }
} }
@Override @Override
public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientNetworkCapacityException, ResourceUnavailableException {
return true; return true;
} }
@ -169,35 +186,35 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
@Override @Override
public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException { public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException {
DataCenter zone = _configMgr.getZone(network.getDataCenterId()); DataCenter zone = _configMgr.getZone(network.getDataCenterId());
//don't have to implement network is Basic zone // don't have to implement network is Basic zone
if (zone.getNetworkType() == NetworkType.Basic) { if (zone.getNetworkType() == NetworkType.Basic) {
s_logger.debug("Not handling network shutdown in zone of type " + NetworkType.Basic); s_logger.debug("Not handling network shutdown in zone of type " + NetworkType.Basic);
return false; return false;
} }
if (!canHandle(network, null)) { if (!canHandle(network, null)) {
return false; return false;
} }
try { try {
return manageGuestNetworkWithExternalFirewall(false, network); return manageGuestNetworkWithExternalFirewall(false, network);
} catch (InsufficientCapacityException capacityException) { } catch (InsufficientCapacityException capacityException) {
// TODO: handle out of capacity exception // TODO: handle out of capacity exception
return false; return false;
} }
} }
@Override @Override
public boolean destroy(Network config) { public boolean destroy(Network config) {
return true; return true;
} }
@Override @Override
public boolean applyFWRules(Network config, List<? extends FirewallRule> rules) throws ResourceUnavailableException { public boolean applyFWRules(Network config, List<? extends FirewallRule> rules) throws ResourceUnavailableException {
if (!canHandle(config, Service.Firewall)) { if (!canHandle(config, Service.Firewall)) {
return false; return false;
} }
return applyFirewallRules(config, rules); return applyFirewallRules(config, rules);
} }
@ -206,7 +223,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
if (!canHandle(config, Service.Vpn)) { if (!canHandle(config, Service.Vpn)) {
return false; return false;
} }
return manageRemoteAccessVpn(true, config, vpn); return manageRemoteAccessVpn(true, config, vpn);
} }
@ -216,24 +233,24 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
if (!canHandle(config, Service.Vpn)) { if (!canHandle(config, Service.Vpn)) {
return false; return false;
} }
return manageRemoteAccessVpn(false, config, vpn); return manageRemoteAccessVpn(false, config, vpn);
} }
@Override @Override
public String[] applyVpnUsers(RemoteAccessVpn vpn, List<? extends VpnUser> users) throws ResourceUnavailableException{ public String[] applyVpnUsers(RemoteAccessVpn vpn, List<? extends VpnUser> users) throws ResourceUnavailableException {
Network config = _networksDao.findById(vpn.getNetworkId()); Network config = _networksDao.findById(vpn.getNetworkId());
if (!canHandle(config, Service.Vpn)) { if (!canHandle(config, Service.Vpn)) {
return null; return null;
} }
boolean result = manageRemoteAccessVpnUsers(config, vpn, users); boolean result = manageRemoteAccessVpnUsers(config, vpn, users);
String[] results = new String[users.size()]; String[] results = new String[users.size()];
for (int i = 0; i < results.length; i++) { for (int i = 0; i < results.length; i++) {
results[i] = String.valueOf(result); results[i] = String.valueOf(result);
} }
return results; return results;
} }
@ -249,49 +266,49 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
private static Map<Service, Map<Capability, String>> setCapabilities() { private static Map<Service, Map<Capability, String>> setCapabilities() {
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>(); Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
// Set capabilities for Firewall service // Set capabilities for Firewall service
Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>(); Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>();
firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp"); firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
firewallCapabilities.put(Capability.MultipleIps, "true"); firewallCapabilities.put(Capability.MultipleIps, "true");
firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); firewallCapabilities.put(Capability.TrafficStatistics, "per public ip");
capabilities.put(Service.Firewall, firewallCapabilities); capabilities.put(Service.Firewall, firewallCapabilities);
//Disabling VPN for Juniper in Acton as it 1) Was never tested 2) probably just doesn't work // Disabling VPN for Juniper in Acton as it 1) Was never tested 2) probably just doesn't work
// // Set VPN capabilities // // Set VPN capabilities
// Map<Capability, String> vpnCapabilities = new HashMap<Capability, String>(); // Map<Capability, String> vpnCapabilities = new HashMap<Capability, String>();
// vpnCapabilities.put(Capability.SupportedVpnTypes, "ipsec"); // vpnCapabilities.put(Capability.SupportedVpnTypes, "ipsec");
// capabilities.put(Service.Vpn, vpnCapabilities); // capabilities.put(Service.Vpn, vpnCapabilities);
capabilities.put(Service.Gateway, null); capabilities.put(Service.Gateway, null);
Map<Capability, String> sourceNatCapabilities = new HashMap<Capability, String>(); Map<Capability, String> sourceNatCapabilities = new HashMap<Capability, String>();
// Specifies that this element supports either one source NAT rule per account, or no source NAT rules at all; // Specifies that this element supports either one source NAT rule per account, or no source NAT rules at all;
// in the latter case a shared interface NAT rule will be used // in the latter case a shared interface NAT rule will be used
sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "per account, per zone"); sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "per account, per zone");
capabilities.put(Service.SourceNat, sourceNatCapabilities); capabilities.put(Service.SourceNat, sourceNatCapabilities);
// Specifies that port forwarding rules are supported by this element // Specifies that port forwarding rules are supported by this element
capabilities.put(Service.PortForwarding, null); capabilities.put(Service.PortForwarding, null);
// Specifies that static NAT rules are supported by this element // Specifies that static NAT rules are supported by this element
capabilities.put(Service.StaticNat, null); capabilities.put(Service.StaticNat, null);
return capabilities; return capabilities;
} }
@Override @Override
public boolean applyPFRules(Network network, List<PortForwardingRule> rules) throws ResourceUnavailableException { public boolean applyPFRules(Network network, List<PortForwardingRule> rules) throws ResourceUnavailableException {
if (!canHandle(network, Service.PortForwarding)) { if (!canHandle(network, Service.PortForwarding)) {
return false; return false;
} }
return applyFirewallRules(network, rules); return applyFirewallRules(network, rules);
} }
@Override @Override
public boolean isReady(PhysicalNetworkServiceProvider provider) { public boolean isReady(PhysicalNetworkServiceProvider provider) {
List<ExternalFirewallDeviceVO> fwDevices = _fwDevicesDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.JuniperSRX.getName()); List<ExternalFirewallDeviceVO> fwDevices = _fwDevicesDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.JuniperSRX.getName());
// true if at-least one SRX device is added in to physical network and is in configured (in enabled state) state // true if at-least one SRX device is added in to physical network and is in configured (in enabled state) state
if (fwDevices != null && !fwDevices.isEmpty()) { if (fwDevices != null && !fwDevices.isEmpty()) {
@ -317,11 +334,12 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
} }
@Override @Override
@Deprecated // should use more generic addNetworkDevice command to add firewall @Deprecated
// should use more generic addNetworkDevice command to add firewall
public Host addExternalFirewall(AddExternalFirewallCmd cmd) { public Host addExternalFirewall(AddExternalFirewallCmd cmd) {
Long zoneId = cmd.getZoneId(); Long zoneId = cmd.getZoneId();
DataCenterVO zone =null; DataCenterVO zone = null;
PhysicalNetworkVO pNetwork=null; PhysicalNetworkVO pNetwork = null;
HostVO fwHost = null; HostVO fwHost = null;
zone = _dcDao.findById(zoneId); zone = _dcDao.findById(zoneId);
@ -340,8 +358,8 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
ExternalFirewallDeviceVO fwDeviceVO = addExternalFirewall(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, (ServerResource) new JuniperSrxResource()); ExternalFirewallDeviceVO fwDeviceVO = addExternalFirewall(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, (ServerResource) new JuniperSrxResource());
if (fwDeviceVO != null) { if (fwDeviceVO != null) {
fwHost = _hostDao.findById(fwDeviceVO.getHostId()); fwHost = _hostDao.findById(fwDeviceVO.getHostId());
} }
return fwHost; return fwHost;
} }
@ -351,12 +369,13 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
} }
@Override @Override
@Deprecated // should use more generic listNetworkDevice command @Deprecated
// should use more generic listNetworkDevice command
public List<Host> listExternalFirewalls(ListExternalFirewallsCmd cmd) { public List<Host> listExternalFirewalls(ListExternalFirewallsCmd cmd) {
List<Host> firewallHosts = new ArrayList<Host>(); List<Host> firewallHosts = new ArrayList<Host>();
Long zoneId = cmd.getZoneId(); Long zoneId = cmd.getZoneId();
DataCenterVO zone =null; DataCenterVO zone = null;
PhysicalNetworkVO pNetwork=null; PhysicalNetworkVO pNetwork = null;
if (zoneId != null) { if (zoneId != null) {
zone = _dcDao.findById(zoneId); zone = _dcDao.findById(zoneId);
@ -391,7 +410,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
if (!deviceName.equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { if (!deviceName.equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) {
throw new InvalidParameterValueException("Invalid SRX firewall device type"); throw new InvalidParameterValueException("Invalid SRX firewall device type");
} }
return addExternalFirewall(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, return addExternalFirewall(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName,
(ServerResource) new JuniperSrxResource()); (ServerResource) new JuniperSrxResource());
} }
@ -415,7 +434,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
if (fwDeviceVO == null || !fwDeviceVO.getDeviceName().equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { if (fwDeviceVO == null || !fwDeviceVO.getDeviceName().equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) {
throw new InvalidParameterValueException("No SRX firewall device found with ID: " + fwDeviceId); throw new InvalidParameterValueException("No SRX firewall device found with ID: " + fwDeviceId);
} }
if (deviceCapacity != null) { if (deviceCapacity != null) {
// check if any networks are using this SRX device // check if any networks are using this SRX device
List<NetworkExternalFirewallVO> networks = _networkFirewallDao.listByFirewallDeviceId(fwDeviceId); List<NetworkExternalFirewallVO> networks = _networkFirewallDao.listByFirewallDeviceId(fwDeviceId);
@ -439,7 +458,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
Long physcialNetworkId = cmd.getPhysicalNetworkId(); Long physcialNetworkId = cmd.getPhysicalNetworkId();
Long fwDeviceId = cmd.getFirewallDeviceId(); Long fwDeviceId = cmd.getFirewallDeviceId();
PhysicalNetworkVO pNetwork = null; PhysicalNetworkVO pNetwork = null;
List<ExternalFirewallDeviceVO> fwDevices = new ArrayList<ExternalFirewallDeviceVO> (); List<ExternalFirewallDeviceVO> fwDevices = new ArrayList<ExternalFirewallDeviceVO>();
if (physcialNetworkId == null && fwDeviceId == null) { if (physcialNetworkId == null && fwDeviceId == null) {
throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified"); throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified");
@ -513,7 +532,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
response.setObjectName("srxfirewall"); response.setObjectName("srxfirewall");
return response; return response;
} }
@Override @Override
public boolean verifyServicesCombination(List<String> services) { public boolean verifyServicesCombination(List<String> services) {
return true; return true;
@ -524,9 +543,9 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
return this; return this;
} }
@Override @Override
public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service) throws ResourceUnavailableException { public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service) throws ResourceUnavailableException {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }

View File

@ -1,6 +1,6 @@
/** /**
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved * * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
* *
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
* *
@ -31,15 +31,12 @@ import javax.ejb.Local;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager;
import com.cloud.agent.AgentManager.OnError;
import com.cloud.agent.api.Answer; import com.cloud.agent.api.Answer;
import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesAnswer;
import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.LoadBalancerTO;
import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO;
import com.cloud.agent.manager.Commands;
import com.cloud.api.ApiConstants; import com.cloud.api.ApiConstants;
import com.cloud.api.commands.AddNetscalerLoadBalancerCmd; import com.cloud.api.commands.AddNetscalerLoadBalancerCmd;
import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd; import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd;
@ -51,7 +48,6 @@ import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeployDestination;
@ -67,9 +63,9 @@ import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.ExternalLoadBalancerDeviceManager; import com.cloud.network.ExternalLoadBalancerDeviceManager;
import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl;
import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.ExternalLoadBalancerDeviceVO;
import com.cloud.network.IpAddress;
import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.IpAddress;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.network.Network.Capability; import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
@ -90,8 +86,8 @@ import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.lb.LoadBalancingRule.LbDestination;
import com.cloud.network.resource.NetscalerResource; import com.cloud.network.resource.NetscalerResource;
import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.StaticNat;
import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering;
@ -108,37 +104,50 @@ import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;
import com.google.gson.Gson; import com.google.gson.Gson;
@Local(value=NetworkElement.class) @Local(value = NetworkElement.class)
public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, NetscalerLoadBalancerElementService, ExternalLoadBalancerDeviceManager, IpDeployer, StaticNatServiceProvider { public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, NetscalerLoadBalancerElementService, ExternalLoadBalancerDeviceManager, IpDeployer,
StaticNatServiceProvider {
private static final Logger s_logger = Logger.getLogger(NetscalerElement.class); private static final Logger s_logger = Logger.getLogger(NetscalerElement.class);
@Inject NetworkManager _networkManager; @Inject
@Inject ConfigurationManager _configMgr; NetworkManager _networkManager;
@Inject NetworkServiceMapDao _ntwkSrvcDao; @Inject
@Inject AgentManager _agentMgr; ConfigurationManager _configMgr;
@Inject NetworkManager _networkMgr; @Inject
@Inject HostDao _hostDao; NetworkServiceMapDao _ntwkSrvcDao;
@Inject DataCenterDao _dcDao; @Inject
@Inject ExternalLoadBalancerDeviceDao _lbDeviceDao; AgentManager _agentMgr;
@Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject
@Inject PhysicalNetworkDao _physicalNetworkDao; NetworkManager _networkMgr;
@Inject NetworkDao _networkDao; @Inject
@Inject HostDetailsDao _detailsDao; HostDao _hostDao;
@Inject ConfigurationDao _configDao; @Inject
DataCenterDao _dcDao;
@Inject
ExternalLoadBalancerDeviceDao _lbDeviceDao;
@Inject
NetworkExternalLoadBalancerDao _networkLBDao;
@Inject
PhysicalNetworkDao _physicalNetworkDao;
@Inject
NetworkDao _networkDao;
@Inject
HostDetailsDao _detailsDao;
@Inject
ConfigurationDao _configDao;
private boolean canHandle(Network config, Service service) { private boolean canHandle(Network config, Service service) {
DataCenter zone = _dcDao.findById(config.getDataCenterId()); DataCenter zone = _dcDao.findById(config.getDataCenterId());
boolean handleInAdvanceZone = (zone.getNetworkType() == NetworkType.Advanced && config.getGuestType() == Network.GuestType.Isolated && config.getTrafficType() == TrafficType.Guest); boolean handleInAdvanceZone = (zone.getNetworkType() == NetworkType.Advanced && config.getGuestType() == Network.GuestType.Isolated && config.getTrafficType() == TrafficType.Guest);
boolean handleInBasicZone = (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() == Network.GuestType.Shared && config.getTrafficType() == TrafficType.Guest); boolean handleInBasicZone = (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() == Network.GuestType.Shared && config.getTrafficType() == TrafficType.Guest);
if (!(handleInAdvanceZone || handleInBasicZone)) { if (!(handleInAdvanceZone || handleInBasicZone)) {
s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType() + " in zone of type " + zone.getNetworkType()); s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType() + " in zone of type " + zone.getNetworkType());
return false; return false;
} }
return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), service, Network.Provider.Netscaler));
_ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), service, Network.Provider.Netscaler));
} }
private boolean isBasicZoneNetwok(Network config) { private boolean isBasicZoneNetwok(Network config) {
@ -147,8 +156,9 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
} }
@Override @Override
public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientNetworkCapacityException { public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientNetworkCapacityException {
if (!canHandle(guestConfig, Service.Lb)) { if (!canHandle(guestConfig, Service.Lb)) {
return false; return false;
} }
@ -158,16 +168,17 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
} catch (InsufficientCapacityException capacityException) { } catch (InsufficientCapacityException capacityException) {
// TODO: handle out of capacity exception gracefully in case of multple providers available // TODO: handle out of capacity exception gracefully in case of multple providers available
return false; return false;
} }
} }
@Override @Override
public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientNetworkCapacityException, ResourceUnavailableException {
return true; return true;
} }
@Override @Override
public boolean release(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) { public boolean release(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) {
return true; return true;
} }
@ -189,12 +200,12 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
public boolean destroy(Network config) { public boolean destroy(Network config) {
return true; return true;
} }
@Override @Override
public boolean validateLBRule(Network network, LoadBalancingRule rule) { public boolean validateLBRule(Network network, LoadBalancingRule rule) {
return true; return true;
} }
@Override @Override
public boolean applyLBRules(Network config, List<LoadBalancingRule> rules) throws ResourceUnavailableException { public boolean applyLBRules(Network config, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
if (!canHandle(config, Service.Lb)) { if (!canHandle(config, Service.Lb)) {
@ -210,62 +221,61 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
@Override @Override
public Map<Service, Map<Capability, String>> getCapabilities() { public Map<Service, Map<Capability, String>> getCapabilities() {
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>(); Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
// Set capabilities for LB service
Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
// Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn");
// specifies that Netscaler network element can provided both shared and isolation modes // Set capabilities for LB service
lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared"); Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
// Specifies that load balancing rules can be made for either TCP or UDP traffic // Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp"); lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn");
// Specifies that this element can measure network usage on a per public IP basis
lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
// Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs // specifies that Netscaler network element can provided both shared and isolation modes
lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional"); lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared");
LbStickinessMethod method;
List <LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>();
method = new LbStickinessMethod(StickinessMethodType.LBCookieBased,"This is cookie based sticky method, can be used only for http");
methodList.add(method);
method.addParam("holdtime", false, "time period in minutes for which persistence is in effect.",false);
method = new LbStickinessMethod(StickinessMethodType.AppCookieBased,"This is app session based sticky method, can be used only for http"); // Specifies that load balancing rules can be made for either TCP or UDP traffic
methodList.add(method); lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
method.addParam("name", true, "cookie name passed in http header by apllication to the client",false);
method = new LbStickinessMethod(StickinessMethodType.SourceBased,"This is source based sticky method, can be used for any type of protocol."); // Specifies that this element can measure network usage on a per public IP basis
methodList.add(method); lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
method.addParam("holdtime", false, "time period for which persistence is in effect.",false);
Gson gson = new Gson(); // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs
String stickyMethodList = gson.toJson(methodList); lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional");
lbCapabilities.put(Capability.SupportedStickinessMethods,stickyMethodList);
LbStickinessMethod method;
lbCapabilities.put(Capability.ElasticLb, "true"); List<LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>();
method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http");
capabilities.put(Service.Lb, lbCapabilities); methodList.add(method);
method.addParam("holdtime", false, "time period in minutes for which persistence is in effect.", false);
Map<Capability, String> staticNatCapabilities = new HashMap<Capability, String>();
staticNatCapabilities.put(Capability.ElasticIp, "true"); method = new LbStickinessMethod(StickinessMethodType.AppCookieBased, "This is app session based sticky method, can be used only for http");
capabilities.put(Service.StaticNat, staticNatCapabilities); methodList.add(method);
method.addParam("name", true, "cookie name passed in http header by apllication to the client", false);
//TODO - Murali, please put correct capabilities here method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based sticky method, can be used for any type of protocol.");
Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>(); methodList.add(method);
firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); method.addParam("holdtime", false, "time period for which persistence is in effect.", false);
firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp");
firewallCapabilities.put(Capability.MultipleIps, "true"); Gson gson = new Gson();
String stickyMethodList = gson.toJson(methodList);
capabilities.put(Service.Firewall, firewallCapabilities); lbCapabilities.put(Capability.SupportedStickinessMethods, stickyMethodList);
return capabilities; lbCapabilities.put(Capability.ElasticLb, "true");
capabilities.put(Service.Lb, lbCapabilities);
Map<Capability, String> staticNatCapabilities = new HashMap<Capability, String>();
staticNatCapabilities.put(Capability.ElasticIp, "true");
capabilities.put(Service.StaticNat, staticNatCapabilities);
// TODO - Murali, please put correct capabilities here
Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>();
firewallCapabilities.put(Capability.TrafficStatistics, "per public ip");
firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp");
firewallCapabilities.put(Capability.MultipleIps, "true");
capabilities.put(Service.Firewall, firewallCapabilities);
return capabilities;
} }
@Override @Override
@ -349,7 +359,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
throw new CloudRuntimeException("There are more number of networks already using this netscaler device than configured capacity"); throw new CloudRuntimeException("There are more number of networks already using this netscaler device than configured capacity");
} }
if (dedicatedUse !=null && dedicatedUse == true) { if (dedicatedUse != null && dedicatedUse == true) {
throw new CloudRuntimeException("There are networks already using this netscaler device to make device dedicated"); throw new CloudRuntimeException("There are networks already using this netscaler device to make device dedicated");
} }
@ -370,7 +380,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
// FIXME how to interpret configured capacity of the SDX device // FIXME how to interpret configured capacity of the SDX device
} }
if(dedicatedUse != null) { if (dedicatedUse != null) {
lbDeviceVo.setIsDedicatedDevice(dedicatedUse); lbDeviceVo.setIsDedicatedDevice(dedicatedUse);
} }
@ -427,7 +437,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
Long physcialNetworkId = cmd.getPhysicalNetworkId(); Long physcialNetworkId = cmd.getPhysicalNetworkId();
Long lbDeviceId = cmd.getLoadBalancerDeviceId(); Long lbDeviceId = cmd.getLoadBalancerDeviceId();
PhysicalNetworkVO pNetwork = null; PhysicalNetworkVO pNetwork = null;
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO> (); List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO>();
if (physcialNetworkId == null && lbDeviceId == null) { if (physcialNetworkId == null && lbDeviceId == null) {
throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified"); throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified");
@ -489,7 +499,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
public boolean isReady(PhysicalNetworkServiceProvider provider) { public boolean isReady(PhysicalNetworkServiceProvider provider) {
List<ExternalLoadBalancerDeviceVO> lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.Netscaler.getName()); List<ExternalLoadBalancerDeviceVO> lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.Netscaler.getName());
// true if at-least one Netscaler device is added in to physical network and is in configured (in enabled state) state // true if at-least one Netscaler device is added in to physical network and is in configured (in enabled state)
// state
if (lbDevices != null && !lbDevices.isEmpty()) { if (lbDevices != null && !lbDevices.isEmpty()) {
for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) {
if (lbDevice.getState() == LBDeviceState.Enabled) { if (lbDevice.getState() == LBDeviceState.Enabled) {
@ -503,7 +514,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
@Override @Override
public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
ResourceUnavailableException { ResourceUnavailableException {
// TODO reset the configuration on all of the netscaler devices in this physical network // TODO reset the configuration on all of the netscaler devices in this physical network
return true; return true;
} }
@ -513,7 +524,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
} }
private boolean isNetscalerDevice(String deviceName) { private boolean isNetscalerDevice(String deviceName) {
if ((deviceName == null) || ((!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerMPXLoadBalancer.getName())) && if ((deviceName == null) || ((!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerMPXLoadBalancer.getName())) &&
(!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerSDXLoadBalancer.getName())) && (!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerSDXLoadBalancer.getName())) &&
(!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerVPXLoadBalancer.getName())))) { (!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerVPXLoadBalancer.getName())))) {
return false; return false;
@ -521,7 +532,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
return true; return true;
} }
} }
@Override @Override
public boolean verifyServicesCombination(List<String> services) { public boolean verifyServicesCombination(List<String> services) {
return true; return true;
@ -552,7 +563,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
} }
String errMsg = null; String errMsg = null;
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
if (lbDeviceVO == null) { if (lbDeviceVO == null) {
try { try {
lbDeviceVO = allocateLoadBalancerForNetwork(network); lbDeviceVO = allocateLoadBalancerForNetwork(network);
@ -586,7 +597,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
} }
if (loadBalancersToApply.size() > 0) { if (loadBalancersToApply.size() > 0) {
int numLoadBalancersForCommand = loadBalancersToApply.size(); int numLoadBalancersForCommand = loadBalancersToApply.size();
LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand);
@ -641,7 +652,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
} }
SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO); SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO);
answer = (SetStaticNatRulesAnswer )_agentMgr.send(lbDevice.getHostId(), cmd); answer = (SetStaticNatRulesAnswer) _agentMgr.send(lbDevice.getHostId(), cmd);
if (answer == null) { if (answer == null) {
return false; return false;
} else { } else {
@ -652,4 +663,5 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
return false; return false;
} }
} }
} }

View File

@ -44,82 +44,83 @@ import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;
@Local(value=NetworkElement.class) @Local(value = NetworkElement.class)
public class OvsElement extends AdapterBase implements NetworkElement { public class OvsElement extends AdapterBase implements NetworkElement {
@Inject OvsNetworkManager _ovsVlanMgr; @Inject
@Inject OvsTunnelManager _ovsTunnelMgr; OvsNetworkManager _ovsVlanMgr;
@Inject
@Override OvsTunnelManager _ovsTunnelMgr;
public boolean destroy(Network network)
throws ConcurrentOperationException, ResourceUnavailableException {
return true;
}
@Override @Override
public Map<Service, Map<Capability, String>> getCapabilities() { public boolean destroy(Network network)
return null; throws ConcurrentOperationException, ResourceUnavailableException {
} return true;
}
@Override @Override
public Provider getProvider() { public Map<Service, Map<Capability, String>> getCapabilities() {
return null; return null;
} }
@Override @Override
public boolean implement(Network network, NetworkOffering offering, public Provider getProvider() {
DeployDestination dest, ReservationContext context) return null;
throws ConcurrentOperationException, ResourceUnavailableException, }
InsufficientCapacityException {
return true;
}
@Override @Override
public boolean prepare(Network network, NicProfile nic, public boolean implement(Network network, NetworkOffering offering,
VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context)
DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException,
throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
InsufficientCapacityException { return true;
if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { }
return true;
}
if (nic.getTrafficType() != Networks.TrafficType.Guest) {
return true;
}
_ovsVlanMgr.VmCheckAndCreateTunnel(vm, dest);
String command = _ovsVlanMgr.applyDefaultFlow(vm.getVirtualMachine(), dest);
if (command != null) {
nic.setBroadcastUri(BroadcastDomainType.Vswitch.toUri(command));
}
_ovsTunnelMgr.VmCheckAndCreateTunnel(vm, dest);
return true;
}
@Override @Override
public boolean release(Network network, NicProfile nic, public boolean prepare(Network network, NicProfile nic,
VirtualMachineProfile<? extends VirtualMachine> vm, VirtualMachineProfile<? extends VirtualMachine> vm,
ReservationContext context) throws ConcurrentOperationException, DeployDestination dest, ReservationContext context)
ResourceUnavailableException { throws ConcurrentOperationException, ResourceUnavailableException,
if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { InsufficientCapacityException {
if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) {
return true; return true;
} }
if (nic.getTrafficType() != Networks.TrafficType.Guest) { if (nic.getTrafficType() != Networks.TrafficType.Guest) {
return true; return true;
} }
_ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine()); _ovsVlanMgr.VmCheckAndCreateTunnel(vm, dest);
return true; String command = _ovsVlanMgr.applyDefaultFlow(vm.getVirtualMachine(), dest);
} if (command != null) {
nic.setBroadcastUri(BroadcastDomainType.Vswitch.toUri(command));
}
@Override _ovsTunnelMgr.VmCheckAndCreateTunnel(vm, dest);
public boolean shutdown(Network network, ReservationContext context, boolean cleanup)
throws ConcurrentOperationException, ResourceUnavailableException { return true;
return true; }
}
@Override
public boolean release(Network network, NicProfile nic,
VirtualMachineProfile<? extends VirtualMachine> vm,
ReservationContext context) throws ConcurrentOperationException,
ResourceUnavailableException {
if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) {
return true;
}
if (nic.getTrafficType() != Networks.TrafficType.Guest) {
return true;
}
_ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine());
return true;
}
@Override
public boolean shutdown(Network network, ReservationContext context, boolean cleanup)
throws ConcurrentOperationException, ResourceUnavailableException {
return true;
}
@Override @Override
public boolean isReady(PhysicalNetworkServiceProvider provider) { public boolean isReady(PhysicalNetworkServiceProvider provider) {
@ -127,8 +128,8 @@ public class OvsElement extends AdapterBase implements NetworkElement {
} }
@Override @Override
public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException { throws ConcurrentOperationException, ResourceUnavailableException {
return true; return true;
} }
@ -136,7 +137,7 @@ public class OvsElement extends AdapterBase implements NetworkElement {
public boolean canEnableIndividualServices() { public boolean canEnableIndividualServices() {
return false; return false;
} }
@Override @Override
public boolean verifyServicesCombination(List<String> services) { public boolean verifyServicesCombination(List<String> services) {
return true; return true;

View File

@ -54,14 +54,14 @@ import com.cloud.network.dao.LoadBalancerDao;
import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.VirtualRouterProviderDao; import com.cloud.network.dao.VirtualRouterProviderDao;
import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRulesManager;
import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy; import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
import com.cloud.network.lb.LoadBalancingRulesManager;
import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.network.router.VirtualNetworkApplianceManager;
import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.RulesManager;
import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.StaticNat;
@ -88,56 +88,72 @@ import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
import com.google.gson.Gson; import com.google.gson.Gson;
@Local(value = NetworkElement.class)
@Local(value=NetworkElement.class) public class VirtualRouterElement extends AdapterBase implements VirtualRouterElementService, DhcpServiceProvider, UserDataServiceProvider, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider,
public class VirtualRouterElement extends AdapterBase implements VirtualRouterElementService, DhcpServiceProvider, UserDataServiceProvider, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider, LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer { LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer {
private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class); private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class);
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities(); private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@Inject NetworkDao _networksDao; @Inject
@Inject NetworkManager _networkMgr; NetworkDao _networksDao;
@Inject LoadBalancingRulesManager _lbMgr; @Inject
@Inject NetworkOfferingDao _networkOfferingDao; NetworkManager _networkMgr;
@Inject VirtualNetworkApplianceManager _routerMgr; @Inject
@Inject ConfigurationManager _configMgr; LoadBalancingRulesManager _lbMgr;
@Inject RulesManager _rulesMgr; @Inject
@Inject UserVmManager _userVmMgr; NetworkOfferingDao _networkOfferingDao;
@Inject UserVmDao _userVmDao; @Inject
@Inject DomainRouterDao _routerDao; VirtualNetworkApplianceManager _routerMgr;
@Inject LoadBalancerDao _lbDao; @Inject
@Inject HostDao _hostDao; ConfigurationManager _configMgr;
@Inject AccountManager _accountMgr; @Inject
@Inject ConfigurationDao _configDao; RulesManager _rulesMgr;
@Inject VirtualRouterProviderDao _vrProviderDao; @Inject
UserVmManager _userVmMgr;
@Inject
UserVmDao _userVmDao;
@Inject
DomainRouterDao _routerDao;
@Inject
LoadBalancerDao _lbDao;
@Inject
HostDao _hostDao;
@Inject
AccountManager _accountMgr;
@Inject
ConfigurationDao _configDao;
@Inject
VirtualRouterProviderDao _vrProviderDao;
protected boolean canHandle(Network network, Service service) { protected boolean canHandle(Network network, Service service) {
Long physicalNetworkId = _networkMgr.getPhysicalNetworkId(network); Long physicalNetworkId = _networkMgr.getPhysicalNetworkId(network);
if (physicalNetworkId == null) { if (physicalNetworkId == null) {
return false; return false;
} }
if (!_networkMgr.isProviderEnabledInPhysicalNetwork(physicalNetworkId, "VirtualRouter")) { if (!_networkMgr.isProviderEnabledInPhysicalNetwork(physicalNetworkId, "VirtualRouter")) {
return false; return false;
} }
if (service == null) { if (service == null) {
if (!_networkMgr.isProviderForNetwork(getProvider(), network.getId())) { if (!_networkMgr.isProviderForNetwork(getProvider(), network.getId())) {
s_logger.trace("Element " + getProvider().getName() + " is not a provider for the network " + network); s_logger.trace("Element " + getProvider().getName() + " is not a provider for the network " + network);
return false; return false;
} }
} else { } else {
if (!_networkMgr.isProviderSupportServiceInNetwork(network.getId(), service, getProvider())) { if (!_networkMgr.isProviderSupportServiceInNetwork(network.getId(), service, getProvider())) {
s_logger.trace("Element " + getProvider().getName() + " doesn't support service " + service.getName() + " in the network " + network); s_logger.trace("Element " + getProvider().getName() + " doesn't support service " + service.getName() + " in the network " + network);
return false; return false;
} }
} }
return true; return true;
} }
@Override @Override
public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientCapacityException {
if (offering.isSystemOnly()) { if (offering.isSystemOnly()) {
return false; return false;
} }
@ -149,28 +165,28 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
return true; return true;
} }
@Override @Override
public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
if (vm.getType() != VirtualMachine.Type.User) { InsufficientCapacityException, ResourceUnavailableException {
if (vm.getType() != VirtualMachine.Type.User) {
return false; return false;
} }
if (!canHandle(network, null)) { if (!canHandle(network, null)) {
return false; return false;
} }
NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
if (offering.isSystemOnly()) { if (offering.isSystemOnly()) {
return false; return false;
} }
if (!_networkMgr.isProviderEnabledInPhysicalNetwork(_networkMgr.getPhysicalNetworkId(network), "VirtualRouter")) { if (!_networkMgr.isProviderEnabledInPhysicalNetwork(_networkMgr.getPhysicalNetworkId(network), "VirtualRouter")) {
return false; return false;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm; VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
List<DomainRouterVO> routers = _routerMgr.deployVirtualRouter(network, dest, _accountMgr.getAccount(network.getAccountId()), uservm.getParameters(), offering.getRedundantRouter()); List<DomainRouterVO> routers = _routerMgr.deployVirtualRouter(network, dest, _accountMgr.getAccount(network.getAccountId()), uservm.getParameters(), offering.getRedundantRouter());
if ((routers == null) || (routers.size() == 0)) { if ((routers == null) || (routers.size() == 0)) {
throw new ResourceUnavailableException("Can't find at least one running router!", this.getClass(), 0); throw new ResourceUnavailableException("Can't find at least one running router!", this.getClass(), 0);
@ -186,8 +202,8 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual router doesn't exist in the network " + config.getId()); s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual router doesn't exist in the network " + config.getId());
return true; return true;
} }
if(!_routerMgr.applyFirewallRules(config, rules, routers)){ if (!_routerMgr.applyFirewallRules(config, rules, routers)) {
throw new CloudRuntimeException("Failed to apply firewall rules in network " + config.getId()); throw new CloudRuntimeException("Failed to apply firewall rules in network " + config.getId());
} else { } else {
return true; return true;
@ -196,6 +212,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
return true; return true;
} }
} }
/* /*
* This function detects numbers like 12 ,32h ,42m .. etc,. 1) plain * This function detects numbers like 12 ,32h ,42m .. etc,. 1) plain
* number like 12 2) time or tablesize like 12h, 34m, 45k, 54m , here * number like 12 2) time or tablesize like 12h, 34m, 45k, 54m , here
@ -304,7 +321,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
} }
return true; return true;
} }
@Override @Override
public boolean applyLBRules(Network network, List<LoadBalancingRule> rules) throws ResourceUnavailableException { public boolean applyLBRules(Network network, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
if (canHandle(network, Service.Lb)) { if (canHandle(network, Service.Lb)) {
@ -313,8 +330,8 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual router doesn't exist in the network " + network.getId()); s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual router doesn't exist in the network " + network.getId());
return true; return true;
} }
if(!_routerMgr.applyFirewallRules(network, rules, routers)){ if (!_routerMgr.applyFirewallRules(network, rules, routers)) {
throw new CloudRuntimeException("Failed to apply firewall rules in network " + network.getId()); throw new CloudRuntimeException("Failed to apply firewall rules in network " + network.getId());
} else { } else {
return true; return true;
@ -323,14 +340,13 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
return true; return true;
} }
} }
@Override @Override
public String[] applyVpnUsers(RemoteAccessVpn vpn, List<? extends VpnUser> users) throws ResourceUnavailableException{ public String[] applyVpnUsers(RemoteAccessVpn vpn, List<? extends VpnUser> users) throws ResourceUnavailableException {
Network network = _networksDao.findById(vpn.getNetworkId()); Network network = _networksDao.findById(vpn.getNetworkId());
if (canHandle(network, Service.Vpn)) { if (canHandle(network, Service.Vpn)) {
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
if (routers == null || routers.isEmpty()) { if (routers == null || routers.isEmpty()) {
s_logger.debug("Virtual router elemnt doesn't need to apply vpn users on the backend; virtual router doesn't exist in the network " + network.getId()); s_logger.debug("Virtual router elemnt doesn't need to apply vpn users on the backend; virtual router doesn't exist in the network " + network.getId());
return null; return null;
@ -341,26 +357,26 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
return null; return null;
} }
} }
@Override @Override
public boolean startVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException { public boolean startVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException {
if (canHandle(network, Service.Vpn)) { if (canHandle(network, Service.Vpn)) {
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
if (routers == null || routers.isEmpty()) { if (routers == null || routers.isEmpty()) {
s_logger.debug("Virtual router elemnt doesn't need stop vpn on the backend; virtual router doesn't exist in the network " + network.getId()); s_logger.debug("Virtual router elemnt doesn't need stop vpn on the backend; virtual router doesn't exist in the network " + network.getId());
return true; return true;
} }
return _routerMgr.startRemoteAccessVpn(network, vpn, routers); return _routerMgr.startRemoteAccessVpn(network, vpn, routers);
} else { } else {
s_logger.debug("Element " + this.getName() + " doesn't handle createVpn command"); s_logger.debug("Element " + this.getName() + " doesn't handle createVpn command");
return false; return false;
} }
} }
@Override @Override
public boolean stopVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException { public boolean stopVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException {
if (canHandle(network, Service.Vpn)) { if (canHandle(network, Service.Vpn)) {
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
if (routers == null || routers.isEmpty()) { if (routers == null || routers.isEmpty()) {
s_logger.debug("Virtual router elemnt doesn't need stop vpn on the backend; virtual router doesn't exist in the network " + network.getId()); s_logger.debug("Virtual router elemnt doesn't need stop vpn on the backend; virtual router doesn't exist in the network " + network.getId());
return true; return true;
@ -387,7 +403,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
s_logger.debug("Virtual router elemnt doesn't need to associate ip addresses on the backend; virtual router doesn't exist in the network " + network.getId()); s_logger.debug("Virtual router elemnt doesn't need to associate ip addresses on the backend; virtual router doesn't exist in the network " + network.getId());
return true; return true;
} }
return _routerMgr.associateIP(network, ipAddress, routers); return _routerMgr.associateIP(network, ipAddress, routers);
} else { } else {
return false; return false;
@ -398,89 +414,124 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
public Provider getProvider() { public Provider getProvider() {
return Provider.VirtualRouter; return Provider.VirtualRouter;
} }
@Override @Override
public Map<Service, Map<Capability, String>> getCapabilities() { public Map<Service, Map<Capability, String>> getCapabilities() {
return capabilities; return capabilities;
} }
private static String getHAProxyStickinessCapability() { private static String getHAProxyStickinessCapability() {
LbStickinessMethod method; LbStickinessMethod method;
List <LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>(1); List<LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>(1);
method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is loadbalancer cookie based stickiness method."); method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is loadbalancer cookie based stickiness method.");
method.addParam("cookie-name", false, "Cookie name passed in http header by the LB to the client.", false); method.addParam("cookie-name", false, "Cookie name passed in http header by the LB to the client.", false);
method.addParam("mode", false, "Valid values: insert, rewrite, prefix. Default value: insert. In the insert mode cookie will be created by the LB. In other modes, cookie will be created by the server and LB modifies it.", false); method.addParam("mode", false,
method.addParam("nocache", false, "This option is recommended in conjunction with the insert mode when there is a cache between the client and HAProxy, as it ensures that a cacheable response will be tagged non-cacheable if a cookie needs to be inserted. This is important because if all persistence cookies are added on a cacheable home page for instance, then all customers will then fetch the page from an outer cache and will all share the same persistence cookie, leading to one server receiving much more traffic than others. See also the insert and postonly options. ", true); "Valid values: insert, rewrite, prefix. Default value: insert. In the insert mode cookie will be created by the LB. In other modes, cookie will be created by the server and LB modifies it.", false);
method.addParam("indirect", false, "When this option is specified in insert mode, cookies will only be added when the server was not reached after a direct access, which means that only when a server is elected after applying a load-balancing algorithm, or after a redispatch, then the cookie will be inserted. If the client has all the required information to connect to the same server next time, no further cookie will be inserted. In all cases, when the indirect option is used in insert mode, the cookie is always removed from the requests transmitted to the server. The persistence mechanism then becomes totally transparent from the application point of view.", true); method.addParam(
method.addParam("postonly",false, "This option ensures that cookie insertion will only be performed on responses to POST requests. It is an alternative to the nocache option, because POST responses are not cacheable, so this ensures that the persistence cookie will never get cached.Since most sites do not need any sort of persistence before the first POST which generally is a login request, this is a very efficient method to optimize caching without risking to find a persistence cookie in the cache. See also the insert and nocache options.", true); "nocache",
method.addParam("domain",false, "This option allows to specify the domain at which a cookie is inserted. It requires exactly one parameter: a valid domain name. If the domain begins with a dot, the browser is allowed to use it for any host ending with that name. It is also possible to specify several domain names by invoking this option multiple times. Some browsers might have small limits on the number of domains, so be careful when doing that. For the record, sending 10 domains to MSIE 6 or Firefox 2 works as expected.", false); false,
"This option is recommended in conjunction with the insert mode when there is a cache between the client and HAProxy, as it ensures that a cacheable response will be tagged non-cacheable if a cookie needs to be inserted. This is important because if all persistence cookies are added on a cacheable home page for instance, then all customers will then fetch the page from an outer cache and will all share the same persistence cookie, leading to one server receiving much more traffic than others. See also the insert and postonly options. ",
true);
method.addParam(
"indirect",
false,
"When this option is specified in insert mode, cookies will only be added when the server was not reached after a direct access, which means that only when a server is elected after applying a load-balancing algorithm, or after a redispatch, then the cookie will be inserted. If the client has all the required information to connect to the same server next time, no further cookie will be inserted. In all cases, when the indirect option is used in insert mode, the cookie is always removed from the requests transmitted to the server. The persistence mechanism then becomes totally transparent from the application point of view.",
true);
method.addParam(
"postonly",
false,
"This option ensures that cookie insertion will only be performed on responses to POST requests. It is an alternative to the nocache option, because POST responses are not cacheable, so this ensures that the persistence cookie will never get cached.Since most sites do not need any sort of persistence before the first POST which generally is a login request, this is a very efficient method to optimize caching without risking to find a persistence cookie in the cache. See also the insert and nocache options.",
true);
method.addParam(
"domain",
false,
"This option allows to specify the domain at which a cookie is inserted. It requires exactly one parameter: a valid domain name. If the domain begins with a dot, the browser is allowed to use it for any host ending with that name. It is also possible to specify several domain names by invoking this option multiple times. Some browsers might have small limits on the number of domains, so be careful when doing that. For the record, sending 10 domains to MSIE 6 or Firefox 2 works as expected.",
false);
methodList.add(method); methodList.add(method);
method = new LbStickinessMethod(StickinessMethodType.AppCookieBased, "This is App session based sticky method. Define session stickiness on an existing application cookie. It can be used only for a specific http traffic"); method = new LbStickinessMethod(StickinessMethodType.AppCookieBased,
"This is App session based sticky method. Define session stickiness on an existing application cookie. It can be used only for a specific http traffic");
method.addParam("cookie-name", true, "This is the name of the cookie used by the application and which LB will have to learn for each new session", false); method.addParam("cookie-name", true, "This is the name of the cookie used by the application and which LB will have to learn for each new session", false);
method.addParam("length", true, "This is the max number of characters that will be memorized and checked in each cookie value", false); method.addParam("length", true, "This is the max number of characters that will be memorized and checked in each cookie value", false);
method.addParam("holdtime", true, "This is the time after which the cookie will be removed from memory if unused. The value should be in the format Example : 20s or 30m or 4h or 5d . only seconds(s), minutes(m) hours(h) and days(d) are valid , cannot use th combinations like 20h30m. ", false); method.addParam(
method.addParam("request-learn", false, "If this option is specified, then haproxy will be able to learn the cookie found in the request in case the server does not specify any in response. This is typically what happens with PHPSESSID cookies, or when haproxy's session expires before the application's session and the correct server is selected. It is recommended to specify this option to improve reliability", true); "holdtime",
method.addParam("prefix", false, "When this option is specified, haproxy will match on the cookie prefix (or URL parameter prefix). The appsession value is the data following this prefix. Example : appsession ASPSESSIONID len 64 timeout 3h prefix This will match the cookie ASPSESSIONIDXXXX=XXXXX, the appsession value will be XXXX=XXXXX.", true); true,
method.addParam("mode", false, "This option allows to change the URL parser mode. 2 modes are currently supported : - path-parameters : The parser looks for the appsession in the path parameters part (each parameter is separated by a semi-colon), which is convenient for JSESSIONID for example.This is the default mode if the option is not set. - query-string : In this mode, the parser will look for the appsession in the query string.", false); "This is the time after which the cookie will be removed from memory if unused. The value should be in the format Example : 20s or 30m or 4h or 5d . only seconds(s), minutes(m) hours(h) and days(d) are valid , cannot use th combinations like 20h30m. ",
false);
method.addParam(
"request-learn",
false,
"If this option is specified, then haproxy will be able to learn the cookie found in the request in case the server does not specify any in response. This is typically what happens with PHPSESSID cookies, or when haproxy's session expires before the application's session and the correct server is selected. It is recommended to specify this option to improve reliability",
true);
method.addParam(
"prefix",
false,
"When this option is specified, haproxy will match on the cookie prefix (or URL parameter prefix). The appsession value is the data following this prefix. Example : appsession ASPSESSIONID len 64 timeout 3h prefix This will match the cookie ASPSESSIONIDXXXX=XXXXX, the appsession value will be XXXX=XXXXX.",
true);
method.addParam(
"mode",
false,
"This option allows to change the URL parser mode. 2 modes are currently supported : - path-parameters : The parser looks for the appsession in the path parameters part (each parameter is separated by a semi-colon), which is convenient for JSESSIONID for example.This is the default mode if the option is not set. - query-string : In this mode, the parser will look for the appsession in the query string.",
false);
methodList.add(method); methodList.add(method);
method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based Stickiness method, it can be used for any type of protocol."); method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based Stickiness method, it can be used for any type of protocol.");
method.addParam("tablesize", false, "Size of table to store source ip addresses. example: tablesize=200k or 300m or 400g", false); method.addParam("tablesize", false, "Size of table to store source ip addresses. example: tablesize=200k or 300m or 400g", false);
method.addParam("expire", false, "Entry in source ip table will expire after expire duration. units can be s,m,h,d . example: expire=30m 20s 50h 4d", false); method.addParam("expire", false, "Entry in source ip table will expire after expire duration. units can be s,m,h,d . example: expire=30m 20s 50h 4d", false);
methodList.add(method); methodList.add(method);
Gson gson = new Gson(); Gson gson = new Gson();
String capability = gson.toJson(methodList); String capability = gson.toJson(methodList);
return capability; return capability;
} }
private static Map<Service, Map<Capability, String>> setCapabilities() { private static Map<Service, Map<Capability, String>> setCapabilities() {
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>(); Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
//Set capabilities for LB service // Set capabilities for LB service
Map<Capability, String> lbCapabilities = new HashMap<Capability, String>(); Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn,source"); lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn,source");
lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated"); lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated");
lbCapabilities.put(Capability.SupportedProtocols, "tcp, udp"); lbCapabilities.put(Capability.SupportedProtocols, "tcp, udp");
lbCapabilities.put(Capability.SupportedStickinessMethods, getHAProxyStickinessCapability()); lbCapabilities.put(Capability.SupportedStickinessMethods, getHAProxyStickinessCapability());
capabilities.put(Service.Lb, lbCapabilities); capabilities.put(Service.Lb, lbCapabilities);
//Set capabilities for Firewall service // Set capabilities for Firewall service
Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>(); Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>();
firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); firewallCapabilities.put(Capability.TrafficStatistics, "per public ip");
firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp"); firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp");
firewallCapabilities.put(Capability.MultipleIps, "true"); firewallCapabilities.put(Capability.MultipleIps, "true");
capabilities.put(Service.Firewall, firewallCapabilities); capabilities.put(Service.Firewall, firewallCapabilities);
//Set capabilities for vpn // Set capabilities for vpn
Map<Capability, String> vpnCapabilities = new HashMap<Capability, String>(); Map<Capability, String> vpnCapabilities = new HashMap<Capability, String>();
vpnCapabilities.put(Capability.SupportedVpnTypes, "pptp,l2tp,ipsec"); vpnCapabilities.put(Capability.SupportedVpnTypes, "pptp,l2tp,ipsec");
capabilities.put(Service.Vpn, vpnCapabilities); capabilities.put(Service.Vpn, vpnCapabilities);
Map<Capability, String> dnsCapabilities = new HashMap<Capability, String>(); Map<Capability, String> dnsCapabilities = new HashMap<Capability, String>();
dnsCapabilities.put(Capability.AllowDnsSuffixModification, "true"); dnsCapabilities.put(Capability.AllowDnsSuffixModification, "true");
capabilities.put(Service.Dns, dnsCapabilities); capabilities.put(Service.Dns, dnsCapabilities);
capabilities.put(Service.UserData, null); capabilities.put(Service.UserData, null);
capabilities.put(Service.Dhcp, null); capabilities.put(Service.Dhcp, null);
capabilities.put(Service.Gateway, null); capabilities.put(Service.Gateway, null);
Map<Capability, String> sourceNatCapabilities = new HashMap<Capability, String>(); Map<Capability, String> sourceNatCapabilities = new HashMap<Capability, String>();
sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "per account"); sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "per account");
sourceNatCapabilities.put(Capability.RedundantRouter, "true"); sourceNatCapabilities.put(Capability.RedundantRouter, "true");
capabilities.put(Service.SourceNat, sourceNatCapabilities); capabilities.put(Service.SourceNat, sourceNatCapabilities);
capabilities.put(Service.StaticNat, null); capabilities.put(Service.StaticNat, null);
capabilities.put(Service.PortForwarding, null); capabilities.put(Service.PortForwarding, null);
return capabilities; return capabilities;
} }
@Override @Override
public boolean applyStaticNats(Network config, List<? extends StaticNat> rules) throws ResourceUnavailableException { public boolean applyStaticNats(Network config, List<? extends StaticNat> rules) throws ResourceUnavailableException {
if (canHandle(config, Service.StaticNat)) { if (canHandle(config, Service.StaticNat)) {
@ -489,13 +540,13 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
s_logger.debug("Virtual router elemnt doesn't need to apply static nat on the backend; virtual router doesn't exist in the network " + config.getId()); s_logger.debug("Virtual router elemnt doesn't need to apply static nat on the backend; virtual router doesn't exist in the network " + config.getId());
return true; return true;
} }
return _routerMgr.applyStaticNats(config, rules, routers); return _routerMgr.applyStaticNats(config, rules, routers);
} else { } else {
return true; return true;
} }
} }
@Override @Override
public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
@ -517,9 +568,9 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
} }
return result; return result;
} }
@Override @Override
public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException{ public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException {
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(config.getId(), Role.VIRTUAL_ROUTER); List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(config.getId(), Role.VIRTUAL_ROUTER);
if (routers == null || routers.isEmpty()) { if (routers == null || routers.isEmpty()) {
return true; return true;
@ -530,21 +581,21 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
} }
return result; return result;
} }
@Override @Override
public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException{ public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException {
if (!canHandle(network, null)) { if (!canHandle(network, null)) {
return false; return false;
} }
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
if (routers == null || routers.isEmpty()) { if (routers == null || routers.isEmpty()) {
s_logger.debug("Can't find virtual router element in network " + network.getId()); s_logger.debug("Can't find virtual router element in network " + network.getId());
return true; return true;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm; VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
return _routerMgr.savePasswordToRouter(network, nic, uservm, routers); return _routerMgr.savePasswordToRouter(network, nic, uservm, routers);
} }
@ -552,7 +603,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
public String getPropertiesFile() { public String getPropertiesFile() {
return "virtualrouter_commands.properties"; return "virtualrouter_commands.properties";
} }
@Override @Override
public VirtualRouterProvider configure(ConfigureVirtualRouterElementCmd cmd) { public VirtualRouterProvider configure(ConfigureVirtualRouterElementCmd cmd) {
VirtualRouterProviderVO element = _vrProviderDao.findById(cmd.getId()); VirtualRouterProviderVO element = _vrProviderDao.findById(cmd.getId());
@ -560,13 +611,13 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
s_logger.debug("Can't find element with network service provider id " + cmd.getId()); s_logger.debug("Can't find element with network service provider id " + cmd.getId());
return null; return null;
} }
element.setEnabled(cmd.getEnabled()); element.setEnabled(cmd.getEnabled());
_vrProviderDao.persist(element); _vrProviderDao.persist(element);
return element; return element;
} }
@Override @Override
public VirtualRouterProvider addElement(Long nspId) { public VirtualRouterProvider addElement(Long nspId) {
VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(nspId, VirtualRouterProviderType.VirtualRouter); VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(nspId, VirtualRouterProviderType.VirtualRouter);
@ -587,8 +638,8 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual router doesn't exist in the network " + network.getId()); s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual router doesn't exist in the network " + network.getId());
return true; return true;
} }
if(!_routerMgr.applyFirewallRules(network, rules, routers)){ if (!_routerMgr.applyFirewallRules(network, rules, routers)) {
throw new CloudRuntimeException("Failed to apply firewall rules in network " + network.getId()); throw new CloudRuntimeException("Failed to apply firewall rules in network " + network.getId());
} else { } else {
return true; return true;
@ -597,7 +648,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
return true; return true;
} }
} }
@Override @Override
public boolean isReady(PhysicalNetworkServiceProvider provider) { public boolean isReady(PhysicalNetworkServiceProvider provider) {
VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), VirtualRouterProviderType.VirtualRouter); VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), VirtualRouterProviderType.VirtualRouter);
@ -614,7 +665,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
if (element == null) { if (element == null) {
return true; return true;
} }
//Find domain routers // Find domain routers
long elementId = element.getId(); long elementId = element.getId();
List<DomainRouterVO> routers = _routerDao.listByElementId(elementId); List<DomainRouterVO> routers = _routerDao.listByElementId(elementId);
boolean result = true; boolean result = true;
@ -623,11 +674,11 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
} }
return result; return result;
} }
@Override @Override
public boolean canEnableIndividualServices() { public boolean canEnableIndividualServices() {
return true; return true;
} }
public Long getIdByNspId(Long nspId) { public Long getIdByNspId(Long nspId) {
VirtualRouterProviderVO vr = _vrProviderDao.findByNspIdAndType(nspId, VirtualRouterProviderType.VirtualRouter); VirtualRouterProviderVO vr = _vrProviderDao.findByNspIdAndType(nspId, VirtualRouterProviderType.VirtualRouter);
@ -654,17 +705,17 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm; VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
boolean publicNetwork = false; boolean publicNetwork = false;
if (_networkMgr.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, getProvider())) { if (_networkMgr.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, getProvider())) {
publicNetwork = true; publicNetwork = true;
} }
boolean isPodBased = (dest.getDataCenter().getNetworkType() == NetworkType.Basic || _networkMgr.isSecurityGroupSupportedInNetwork(network)) && boolean isPodBased = (dest.getDataCenter().getNetworkType() == NetworkType.Basic || _networkMgr.isSecurityGroupSupportedInNetwork(network)) &&
network.getTrafficType() == TrafficType.Guest; network.getTrafficType() == TrafficType.Guest;
List<DomainRouterVO> routers; List<DomainRouterVO> routers;
if (publicNetwork) { if (publicNetwork) {
routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
} else { } else {
@ -675,8 +726,9 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
} }
} }
//for Basic zone, add all Running routers - we have to send Dhcp/vmData/password info to them when network.dns.basiczone.updates is set to "all" // for Basic zone, add all Running routers - we have to send Dhcp/vmData/password info to them when
// network.dns.basiczone.updates is set to "all"
Long podId = dest.getPod().getId(); Long podId = dest.getPod().getId();
if (isPodBased && _routerMgr.getDnsBasicZoneUpdate().equalsIgnoreCase("all")) { if (isPodBased && _routerMgr.getDnsBasicZoneUpdate().equalsIgnoreCase("all")) {
List<DomainRouterVO> allRunningRoutersOutsideThePod = _routerDao.findByNetworkOutsideThePod(network.getId(), podId, State.Running, Role.VIRTUAL_ROUTER); List<DomainRouterVO> allRunningRoutersOutsideThePod = _routerDao.findByNetworkOutsideThePod(network.getId(), podId, State.Running, Role.VIRTUAL_ROUTER);
@ -686,7 +738,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
if ((routers == null) || (routers.size() == 0)) { if ((routers == null) || (routers.size() == 0)) {
throw new ResourceUnavailableException("Can't find at least one router!", this.getClass(), 0); throw new ResourceUnavailableException("Can't find at least one router!", this.getClass(), 0);
} }
List<VirtualRouter> rets = _routerMgr.applyDhcpEntry(network, nic, uservm, dest, context, routers); List<VirtualRouter> rets = _routerMgr.applyDhcpEntry(network, nic, uservm, dest, context, routers);
return (rets != null) && (!rets.isEmpty()); return (rets != null) && (!rets.isEmpty());
} }
@ -702,17 +754,17 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm; VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
boolean publicNetwork = false; boolean publicNetwork = false;
if (_networkMgr.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, getProvider())) { if (_networkMgr.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, getProvider())) {
publicNetwork = true; publicNetwork = true;
} }
boolean isPodBased = (dest.getDataCenter().getNetworkType() == NetworkType.Basic || _networkMgr.isSecurityGroupSupportedInNetwork(network)) && boolean isPodBased = (dest.getDataCenter().getNetworkType() == NetworkType.Basic || _networkMgr.isSecurityGroupSupportedInNetwork(network)) &&
network.getTrafficType() == TrafficType.Guest; network.getTrafficType() == TrafficType.Guest;
List<DomainRouterVO> routers; List<DomainRouterVO> routers;
if (publicNetwork) { if (publicNetwork) {
routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
} else { } else {
@ -723,8 +775,9 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
} }
} }
//for Basic zone, add all Running routers - we have to send Dhcp/vmData/password info to them when network.dns.basiczone.updates is set to "all" // for Basic zone, add all Running routers - we have to send Dhcp/vmData/password info to them when
// network.dns.basiczone.updates is set to "all"
Long podId = dest.getPod().getId(); Long podId = dest.getPod().getId();
if (isPodBased && _routerMgr.getDnsBasicZoneUpdate().equalsIgnoreCase("all")) { if (isPodBased && _routerMgr.getDnsBasicZoneUpdate().equalsIgnoreCase("all")) {
List<DomainRouterVO> allRunningRoutersOutsideThePod = _routerDao.findByNetworkOutsideThePod(network.getId(), podId, State.Running, Role.VIRTUAL_ROUTER); List<DomainRouterVO> allRunningRoutersOutsideThePod = _routerDao.findByNetworkOutsideThePod(network.getId(), podId, State.Running, Role.VIRTUAL_ROUTER);
@ -734,7 +787,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
if ((routers == null) || (routers.size() == 0)) { if ((routers == null) || (routers.size() == 0)) {
throw new ResourceUnavailableException("Can't find at least one router!", this.getClass(), 0); throw new ResourceUnavailableException("Can't find at least one router!", this.getClass(), 0);
} }
List<VirtualRouter> rets = _routerMgr.applyUserData(network, nic, uservm, dest, context, routers); List<VirtualRouter> rets = _routerMgr.applyUserData(network, nic, uservm, dest, context, routers);
return (rets != null) && (!rets.isEmpty()); return (rets != null) && (!rets.isEmpty());
} }
@ -746,7 +799,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
Long id = cmd.getId(); Long id = cmd.getId();
Long nspId = cmd.getNspId(); Long nspId = cmd.getNspId();
Boolean enabled = cmd.getEnabled(); Boolean enabled = cmd.getEnabled();
SearchCriteriaService<VirtualRouterProviderVO, VirtualRouterProviderVO> sc = SearchCriteria2.create(VirtualRouterProviderVO.class); SearchCriteriaService<VirtualRouterProviderVO, VirtualRouterProviderVO> sc = SearchCriteria2.create(VirtualRouterProviderVO.class);
if (id != null) { if (id != null) {
sc.addAnd(sc.getEntity().getId(), Op.EQ, id); sc.addAnd(sc.getEntity().getId(), Op.EQ, id);

View File

@ -79,7 +79,7 @@ import com.cloud.vm.UserVmVO;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
@Local(value = { FirewallService.class, FirewallManager.class }) @Local(value = { FirewallService.class, FirewallManager.class })
public class FirewallManagerImpl implements FirewallService, FirewallManager, Manager{ public class FirewallManagerImpl implements FirewallService, FirewallManager, Manager {
private static final Logger s_logger = Logger.getLogger(FirewallManagerImpl.class); private static final Logger s_logger = Logger.getLogger(FirewallManagerImpl.class);
String _name; String _name;
@ -97,7 +97,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
AccountManager _accountMgr; AccountManager _accountMgr;
@Inject @Inject
NetworkManager _networkMgr; NetworkManager _networkMgr;
@Inject @Inject
UsageEventDao _usageEventDao; UsageEventDao _usageEventDao;
@Inject @Inject
ConfigurationDao _configDao; ConfigurationDao _configDao;
@ -107,9 +107,9 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
PortForwardingRulesDao _pfRulesDao; PortForwardingRulesDao _pfRulesDao;
@Inject @Inject
UserVmDao _vmDao; UserVmDao _vmDao;
private boolean _elbEnabled=false; private boolean _elbEnabled = false;
@Override @Override
public boolean start() { public boolean start() {
return true; return true;
@ -124,7 +124,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
public String getName() { public String getName() {
return _name; return _name;
} }
@Override @Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
@ -132,73 +132,75 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
_elbEnabled = Boolean.parseBoolean(elbEnabledString); _elbEnabled = Boolean.parseBoolean(elbEnabledString);
return true; return true;
} }
@Override @Override
public FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException { public FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
return createFirewallRule(rule.getSourceIpAddressId(), caller, rule.getXid(), rule.getSourcePortStart() ,rule.getSourcePortEnd(), rule.getProtocol(), rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), null, rule.getType()); return createFirewallRule(rule.getSourceIpAddressId(), caller, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), rule.getSourceCidrList(), rule.getIcmpCode(),
rule.getIcmpType(), null, rule.getType());
} }
@DB @DB
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_OPEN, eventDescription = "creating firewall rule", create = true) @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_OPEN, eventDescription = "creating firewall rule", create = true)
public FirewallRule createFirewallRule(long ipAddrId, Account caller, String xId, Integer portStart,Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType, Long relatedRuleId, FirewallRule.FirewallRuleType type) throws NetworkRuleConflictException{ public FirewallRule createFirewallRule(long ipAddrId, Account caller, String xId, Integer portStart, Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType,
Long relatedRuleId, FirewallRule.FirewallRuleType type) throws NetworkRuleConflictException {
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId); IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
// Validate ip address // Validate ip address
if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) { if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system"); throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system");
} }
validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall, type); validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall, type);
//icmp code and icmp type can't be passed in for any other protocol rather than icmp // icmp code and icmp type can't be passed in for any other protocol rather than icmp
if (!protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (icmpCode != null || icmpType != null)) { if (!protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (icmpCode != null || icmpType != null)) {
throw new InvalidParameterValueException("Can specify icmpCode and icmpType for ICMP protocol only"); throw new InvalidParameterValueException("Can specify icmpCode and icmpType for ICMP protocol only");
} }
if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (portStart != null || portEnd != null)) { if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (portStart != null || portEnd != null)) {
throw new InvalidParameterValueException("Can't specify start/end port when protocol is ICMP"); throw new InvalidParameterValueException("Can't specify start/end port when protocol is ICMP");
} }
Long networkId = null; Long networkId = null;
Long accountId = null; Long accountId = null;
Long domainId = null; Long domainId = null;
if (ipAddress != null) { if (ipAddress != null) {
networkId = ipAddress.getAssociatedWithNetworkId(); networkId = ipAddress.getAssociatedWithNetworkId();
accountId = ipAddress.getAllocatedToAccountId(); accountId = ipAddress.getAllocatedToAccountId();
domainId = ipAddress.getAllocatedInDomainId(); domainId = ipAddress.getAllocatedInDomainId();
} }
_networkMgr.checkIpForService(ipAddress, Service.Firewall); _networkMgr.checkIpForService(ipAddress, Service.Firewall);
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
FirewallRuleVO newRule = new FirewallRuleVO (xId, ipAddrId, portStart, portEnd, protocol.toLowerCase(), networkId, accountId, domainId, Purpose.Firewall, sourceCidrList, icmpCode, icmpType, relatedRuleId); FirewallRuleVO newRule = new FirewallRuleVO(xId, ipAddrId, portStart, portEnd, protocol.toLowerCase(), networkId, accountId, domainId, Purpose.Firewall, sourceCidrList, icmpCode, icmpType, relatedRuleId);
newRule.setType(type); newRule.setType(type);
newRule = _firewallDao.persist(newRule); newRule = _firewallDao.persist(newRule);
if (type == FirewallRuleType.User) if (type == FirewallRuleType.User)
detectRulesConflict(newRule, ipAddress); detectRulesConflict(newRule, ipAddress);
if (!_firewallDao.setStateToAdd(newRule)) { if (!_firewallDao.setStateToAdd(newRule)) {
throw new CloudRuntimeException("Unable to update the state to add for " + newRule); throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
} }
UserContext.current().setEventDetails("Rule Id: " + newRule.getId()); UserContext.current().setEventDetails("Rule Id: " + newRule.getId());
txn.commit(); txn.commit();
return newRule; return newRule;
} }
@Override @Override
public List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd) { public List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd) {
Long ipId = cmd.getIpAddressId(); Long ipId = cmd.getIpAddressId();
Long id = cmd.getId(); Long id = cmd.getId();
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>(); List<Long> permittedAccounts = new ArrayList<Long>();
@ -215,7 +217,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
Long domainId = domainIdRecursiveListProject.first(); Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second(); Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder(); SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
@ -239,7 +241,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
return _firewallDao.search(sc, filter); return _firewallDao.search(sc, filter);
} }
@Override @Override
public void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException { public void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException {
assert newRule.getSourceIpAddressId() == ipAddress.getId() : "You passed in an ip address that doesn't match the address in the new rule"; assert newRule.getSourceIpAddressId() == ipAddress.getId() : "You passed in an ip address that doesn't match the address in the new rule";
@ -251,21 +253,22 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
if (rule.getId() == newRule.getId()) { if (rule.getId() == newRule.getId()) {
continue; // Skips my own rule. continue; // Skips my own rule.
} }
boolean oneOfRulesIsFirewall = ((rule.getPurpose() == Purpose.Firewall || newRule.getPurpose() == Purpose.Firewall) && ((newRule.getPurpose() != rule.getPurpose()) || (!newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())))); boolean oneOfRulesIsFirewall = ((rule.getPurpose() == Purpose.Firewall || newRule.getPurpose() == Purpose.Firewall) && ((newRule.getPurpose() != rule.getPurpose()) || (!newRule.getProtocol()
.equalsIgnoreCase(rule.getProtocol()))));
//if both rules are firewall and their cidrs are different, we can skip port ranges verification
// if both rules are firewall and their cidrs are different, we can skip port ranges verification
boolean bothRulesFirewall = (rule.getPurpose() == newRule.getPurpose() && rule.getPurpose() == Purpose.Firewall); boolean bothRulesFirewall = (rule.getPurpose() == newRule.getPurpose() && rule.getPurpose() == Purpose.Firewall);
boolean duplicatedCidrs = false; boolean duplicatedCidrs = false;
if (bothRulesFirewall) { if (bothRulesFirewall) {
//Verify that the rules have different cidrs // Verify that the rules have different cidrs
List<String> ruleCidrList = rule.getSourceCidrList(); List<String> ruleCidrList = rule.getSourceCidrList();
List<String> newRuleCidrList = newRule.getSourceCidrList(); List<String> newRuleCidrList = newRule.getSourceCidrList();
if (ruleCidrList == null || newRuleCidrList == null) { if (ruleCidrList == null || newRuleCidrList == null) {
continue; continue;
} }
Collection<String> similar = new HashSet<String>(ruleCidrList); Collection<String> similar = new HashSet<String>(ruleCidrList);
similar.retainAll(newRuleCidrList); similar.retainAll(newRuleCidrList);
@ -273,7 +276,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
duplicatedCidrs = true; duplicatedCidrs = true;
} }
} }
if (!oneOfRulesIsFirewall) { if (!oneOfRulesIsFirewall) {
if (rule.getPurpose() == Purpose.StaticNat && newRule.getPurpose() != Purpose.StaticNat) { if (rule.getPurpose() == Purpose.StaticNat && newRule.getPurpose() != Purpose.StaticNat) {
throw new NetworkRuleConflictException("There is 1 to 1 Nat rule specified for the ip address id=" + newRule.getSourceIpAddressId()); throw new NetworkRuleConflictException("There is 1 to 1 Nat rule specified for the ip address id=" + newRule.getSourceIpAddressId());
@ -284,57 +287,58 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
if (rule.getNetworkId() != newRule.getNetworkId() && rule.getState() != State.Revoke) { if (rule.getNetworkId() != newRule.getNetworkId() && rule.getState() != State.Revoke) {
throw new NetworkRuleConflictException("New rule is for a different network than what's specified in rule " + rule.getXid()); throw new NetworkRuleConflictException("New rule is for a different network than what's specified in rule " + rule.getXid());
} }
if (newRule.getProtocol().equalsIgnoreCase(NetUtils.ICMP_PROTO) && newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())) { if (newRule.getProtocol().equalsIgnoreCase(NetUtils.ICMP_PROTO) && newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())) {
if (newRule.getIcmpCode().longValue() == rule.getIcmpCode().longValue() && newRule.getIcmpType().longValue() == rule.getIcmpType().longValue() && newRule.getProtocol().equalsIgnoreCase(rule.getProtocol()) && duplicatedCidrs) { if (newRule.getIcmpCode().longValue() == rule.getIcmpCode().longValue() && newRule.getIcmpType().longValue() == rule.getIcmpType().longValue()
&& newRule.getProtocol().equalsIgnoreCase(rule.getProtocol()) && duplicatedCidrs) {
throw new InvalidParameterValueException("New rule conflicts with existing rule id=" + rule.getId()); throw new InvalidParameterValueException("New rule conflicts with existing rule id=" + rule.getId());
} }
} }
boolean notNullPorts = (newRule.getSourcePortStart() != null && newRule.getSourcePortEnd() != null && rule.getSourcePortStart() != null && rule.getSourcePortEnd() != null) ; boolean notNullPorts = (newRule.getSourcePortStart() != null && newRule.getSourcePortEnd() != null && rule.getSourcePortStart() != null && rule.getSourcePortEnd() != null);
if (!notNullPorts) { if (!notNullPorts) {
continue; continue;
} else if (!oneOfRulesIsFirewall && !(bothRulesFirewall && !duplicatedCidrs) && ((rule.getSourcePortStart().intValue() <= newRule.getSourcePortStart().intValue() && rule.getSourcePortEnd().intValue() >= newRule.getSourcePortStart().intValue()) } else if (!oneOfRulesIsFirewall && !(bothRulesFirewall && !duplicatedCidrs)
|| (rule.getSourcePortStart().intValue() <= newRule.getSourcePortEnd().intValue() && rule.getSourcePortEnd().intValue() >= newRule.getSourcePortEnd().intValue()) && ((rule.getSourcePortStart().intValue() <= newRule.getSourcePortStart().intValue() && rule.getSourcePortEnd().intValue() >= newRule.getSourcePortStart().intValue())
|| (newRule.getSourcePortStart().intValue() <= rule.getSourcePortStart().intValue() && newRule.getSourcePortEnd().intValue() >= rule.getSourcePortStart().intValue()) || (rule.getSourcePortStart().intValue() <= newRule.getSourcePortEnd().intValue() && rule.getSourcePortEnd().intValue() >= newRule.getSourcePortEnd().intValue())
|| (newRule.getSourcePortStart().intValue() <= rule.getSourcePortEnd().intValue() && newRule.getSourcePortEnd().intValue() >= rule.getSourcePortEnd().intValue()))) { || (newRule.getSourcePortStart().intValue() <= rule.getSourcePortStart().intValue() && newRule.getSourcePortEnd().intValue() >= rule.getSourcePortStart().intValue())
|| (newRule.getSourcePortStart().intValue() <= rule.getSourcePortEnd().intValue() && newRule.getSourcePortEnd().intValue() >= rule.getSourcePortEnd().intValue()))) {
// we allow port forwarding rules with the same parameters but different protocols // we allow port forwarding rules with the same parameters but different protocols
boolean allowPf = (rule.getPurpose() == Purpose.PortForwarding && newRule.getPurpose() == Purpose.PortForwarding && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())); boolean allowPf = (rule.getPurpose() == Purpose.PortForwarding && newRule.getPurpose() == Purpose.PortForwarding && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol()));
boolean allowStaticNat = (rule.getPurpose() == Purpose.StaticNat && newRule.getPurpose() == Purpose.StaticNat && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol())); boolean allowStaticNat = (rule.getPurpose() == Purpose.StaticNat && newRule.getPurpose() == Purpose.StaticNat && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol()));
if (!(allowPf || allowStaticNat || oneOfRulesIsFirewall)) { if (!(allowPf || allowStaticNat || oneOfRulesIsFirewall)) {
throw new NetworkRuleConflictException("The range specified, " + newRule.getSourcePortStart() + "-" + newRule.getSourcePortEnd() + ", conflicts with rule " + rule.getId() throw new NetworkRuleConflictException("The range specified, " + newRule.getSourcePortStart() + "-" + newRule.getSourcePortEnd() + ", conflicts with rule " + rule.getId()
+ " which has " + rule.getSourcePortStart() + "-" + rule.getSourcePortEnd()); + " which has " + rule.getSourcePortStart() + "-" + rule.getSourcePortEnd());
} }
} }
} }
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("No network rule conflicts detected for " + newRule + " against " + (rules.size() - 1) + " existing rules"); s_logger.debug("No network rule conflicts detected for " + newRule + " against " + (rules.size() - 1) + " existing rules");
} }
} }
@Override @Override
public void validateFirewallRule(Account caller, IPAddressVO ipAddress, Integer portStart, Integer portEnd, String proto, Purpose purpose, FirewallRuleType type) { public void validateFirewallRule(Account caller, IPAddressVO ipAddress, Integer portStart, Integer portEnd, String proto, Purpose purpose, FirewallRuleType type) {
if (portStart != null && !NetUtils.isValidPort(portStart)) { if (portStart != null && !NetUtils.isValidPort(portStart)) {
throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart); throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart);
} }
if (portEnd != null && !NetUtils.isValidPort(portEnd)) { if (portEnd != null && !NetUtils.isValidPort(portEnd)) {
throw new InvalidParameterValueException("Public port range is an invalid value: " + portEnd); throw new InvalidParameterValueException("Public port range is an invalid value: " + portEnd);
} }
// start port can't be bigger than end port // start port can't be bigger than end port
if (portStart != null && portEnd != null && portStart > portEnd) { if (portStart != null && portEnd != null && portStart > portEnd) {
throw new InvalidParameterValueException("Start port can't be bigger than end port"); throw new InvalidParameterValueException("Start port can't be bigger than end port");
} }
if (ipAddress == null && type == FirewallRuleType.System) { if (ipAddress == null && type == FirewallRuleType.System) {
return; return;
} }
// Validate ip address // Validate ip address
_accountMgr.checkAccess(caller, null, true, ipAddress); _accountMgr.checkAccess(caller, null, true, ipAddress);
@ -343,34 +347,33 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
throw new InvalidParameterValueException("Unable to create port forwarding rule ; ip id=" + ipAddress.getId() + " is not associated with any network"); throw new InvalidParameterValueException("Unable to create port forwarding rule ; ip id=" + ipAddress.getId() + " is not associated with any network");
} }
Network network = _networkMgr.getNetwork(networkId); Network network = _networkMgr.getNetwork(networkId);
assert network != null : "Can't create port forwarding rule as network associated with public ip address is null?"; assert network != null : "Can't create port forwarding rule as network associated with public ip address is null?";
// Verify that the network guru supports the protocol specified // Verify that the network guru supports the protocol specified
Map<Network.Capability, String> protocolCapabilities = null; Map<Network.Capability, String> protocolCapabilities = null;
if (purpose == Purpose.LoadBalancing) { if (purpose == Purpose.LoadBalancing) {
if (!_elbEnabled) { if (!_elbEnabled) {
protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.Lb); protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.Lb);
} }
} else if (purpose == Purpose.Firewall){ } else if (purpose == Purpose.Firewall) {
protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.Firewall); protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.Firewall);
} else if (purpose == Purpose.PortForwarding) { } else if (purpose == Purpose.PortForwarding) {
protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.PortForwarding); protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.PortForwarding);
} }
if (protocolCapabilities != null) { if (protocolCapabilities != null) {
String supportedProtocols = protocolCapabilities.get(Capability.SupportedProtocols).toLowerCase(); String supportedProtocols = protocolCapabilities.get(Capability.SupportedProtocols).toLowerCase();
if (!supportedProtocols.contains(proto.toLowerCase())) { if (!supportedProtocols.contains(proto.toLowerCase())) {
throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId()); throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId());
} else if (proto.equalsIgnoreCase(NetUtils.ICMP_PROTO) && purpose != Purpose.Firewall) { } else if (proto.equalsIgnoreCase(NetUtils.ICMP_PROTO) && purpose != Purpose.Firewall) {
throw new InvalidParameterValueException("Protocol " + proto + " is currently supported only for rules with purpose " + Purpose.Firewall); throw new InvalidParameterValueException("Protocol " + proto + " is currently supported only for rules with purpose " + Purpose.Firewall);
} }
} }
} }
@Override @Override
public boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException { public boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException {
boolean success = true; boolean success = true;
@ -396,28 +399,27 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
} }
} }
} }
return success; return success;
} }
@Override @Override
public boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException { public boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException {
List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall); List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall);
return applyFirewallRules(rules, false, caller); return applyFirewallRules(rules, false, caller);
} }
@Override @Override
public boolean applyFirewallRules(List<FirewallRuleVO> rules, boolean continueOnError, Account caller) { public boolean applyFirewallRules(List<FirewallRuleVO> rules, boolean continueOnError, Account caller) {
if (rules.size() == 0) { if (rules.size() == 0) {
s_logger.debug("There are no firewall rules to apply for ip id=" + rules); s_logger.debug("There are no firewall rules to apply for ip id=" + rules);
return true; return true;
} }
for (FirewallRuleVO rule: rules){ for (FirewallRuleVO rule : rules) {
// load cidrs if any // load cidrs if any
rule.setSourceCidrList(_firewallCidrsDao.getSourceCidrs(rule.getId())); rule.setSourceCidrList(_firewallCidrsDao.getSourceCidrs(rule.getId()));
} }
if (caller != null) { if (caller != null) {
@ -435,7 +437,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
return true; return true;
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true) @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
public boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId) { public boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId) {
@ -444,13 +446,13 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
if (rule == null || rule.getPurpose() != Purpose.Firewall) { if (rule == null || rule.getPurpose() != Purpose.Firewall) {
throw new InvalidParameterValueException("Unable to find " + ruleId + " having purpose " + Purpose.Firewall); throw new InvalidParameterValueException("Unable to find " + ruleId + " having purpose " + Purpose.Firewall);
} }
if (rule.getType() == FirewallRuleType.System && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { if (rule.getType() == FirewallRuleType.System && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
throw new InvalidParameterValueException("Only root admin can delete the system wide firewall rule"); throw new InvalidParameterValueException("Only root admin can delete the system wide firewall rule");
} }
_accountMgr.checkAccess(caller, null, true, rule); _accountMgr.checkAccess(caller, null, true, rule);
revokeRule(rule, caller, userId, false); revokeRule(rule, caller, userId, false);
boolean success = false; boolean success = false;
@ -465,15 +467,15 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
return success; return success;
} }
@Override @Override
public boolean revokeFirewallRule(long ruleId, boolean apply) { public boolean revokeFirewallRule(long ruleId, boolean apply) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
long userId = UserContext.current().getCallerUserId(); long userId = UserContext.current().getCallerUserId();
return revokeFirewallRule(ruleId, apply, caller, userId); return revokeFirewallRule(ruleId, apply, caller, userId);
} }
@Override @Override
@DB @DB
public void revokeRule(FirewallRuleVO rule, Account caller, long userId, boolean needUsageEvent) { public void revokeRule(FirewallRuleVO rule, Account caller, long userId, boolean needUsageEvent) {
if (caller != null) { if (caller != null) {
@ -500,16 +502,15 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(), null); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(), null);
_usageEventDao.persist(usageEvent); _usageEventDao.persist(usageEvent);
} }
txn.commit(); txn.commit();
} }
@Override @Override
public FirewallRule getFirewallRule(long ruleId) { public FirewallRule getFirewallRule(long ruleId) {
return _firewallDao.findById(ruleId); return _firewallDao.findById(ruleId);
} }
@Override @Override
public boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException { public boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException {
List<FirewallRule> rules = new ArrayList<FirewallRule>(); List<FirewallRule> rules = new ArrayList<FirewallRule>();
@ -520,7 +521,8 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
} }
for (FirewallRuleVO rule : fwRules) { for (FirewallRuleVO rule : fwRules) {
// Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no need to send them one by one // Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no
// need to send them one by one
revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM); revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM);
} }
@ -537,21 +539,22 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
return rules.size() == 0; return rules.size() == 0;
} }
@Override @Override
public FirewallRule createRuleForAllCidrs(long ipAddrId, Account caller, Integer startPort, Integer endPort, String protocol, Integer icmpCode, Integer icmpType, Long relatedRuleId) throws NetworkRuleConflictException{ public FirewallRule createRuleForAllCidrs(long ipAddrId, Account caller, Integer startPort, Integer endPort, String protocol, Integer icmpCode, Integer icmpType, Long relatedRuleId)
throws NetworkRuleConflictException {
//If firwallRule for this port range already exists, return it
// If firwallRule for this port range already exists, return it
List<FirewallRuleVO> rules = _firewallDao.listByIpPurposeAndProtocolAndNotRevoked(ipAddrId, startPort, endPort, protocol, Purpose.Firewall); List<FirewallRuleVO> rules = _firewallDao.listByIpPurposeAndProtocolAndNotRevoked(ipAddrId, startPort, endPort, protocol, Purpose.Firewall);
if (!rules.isEmpty()) { if (!rules.isEmpty()) {
return rules.get(0); return rules.get(0);
} }
List<String> oneCidr = new ArrayList<String>(); List<String> oneCidr = new ArrayList<String>();
oneCidr.add(NetUtils.ALL_CIDRS); oneCidr.add(NetUtils.ALL_CIDRS);
return createFirewallRule(ipAddrId, caller, null, startPort, endPort, protocol, oneCidr, icmpCode, icmpType, relatedRuleId, FirewallRule.FirewallRuleType.User); return createFirewallRule(ipAddrId, caller, null, startPort, endPort, protocol, oneCidr, icmpCode, icmpType, relatedRuleId, FirewallRule.FirewallRuleType.User);
} }
@Override @Override
public boolean revokeAllFirewallRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException { public boolean revokeAllFirewallRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException {
List<FirewallRule> rules = new ArrayList<FirewallRule>(); List<FirewallRule> rules = new ArrayList<FirewallRule>();
@ -562,7 +565,8 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
} }
for (FirewallRuleVO rule : fwRules) { for (FirewallRuleVO rule : fwRules) {
// Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no need to send them one by one // Mark all Firewall rules as Revoke, but don't revoke them yet - we have to revoke all rules for ip, no
// need to send them one by one
revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM); revokeFirewallRule(rule.getId(), false, caller, Account.ACCOUNT_ID_SYSTEM);
} }
@ -579,22 +583,21 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
return success && rules.size() == 0; return success && rules.size() == 0;
} }
@Override @Override
public boolean revokeRelatedFirewallRule(long ruleId, boolean apply) { public boolean revokeRelatedFirewallRule(long ruleId, boolean apply) {
FirewallRule fwRule = _firewallDao.findByRelatedId(ruleId); FirewallRule fwRule = _firewallDao.findByRelatedId(ruleId);
if (fwRule == null) { if (fwRule == null) {
s_logger.trace("No related firewall rule exists for rule id=" + ruleId + " so returning true here"); s_logger.trace("No related firewall rule exists for rule id=" + ruleId + " so returning true here");
return true; return true;
} }
s_logger.debug("Revoking Firewall rule id=" + fwRule.getId() + " as a part of rule delete id=" + ruleId + " with apply=" + apply); s_logger.debug("Revoking Firewall rule id=" + fwRule.getId() + " as a part of rule delete id=" + ruleId + " with apply=" + apply);
return revokeFirewallRule(fwRule.getId(), apply); return revokeFirewallRule(fwRule.getId(), apply);
} }
@Override @Override
public boolean revokeFirewallRulesForVm(long vmId) { public boolean revokeFirewallRulesForVm(long vmId) {
boolean success = true; boolean success = true;
@ -606,23 +609,22 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
List<PortForwardingRuleVO> pfRules = _pfRulesDao.listByVm(vmId); List<PortForwardingRuleVO> pfRules = _pfRulesDao.listByVm(vmId);
List<FirewallRuleVO> staticNatRules = _firewallDao.listStaticNatByVmId(vm.getId()); List<FirewallRuleVO> staticNatRules = _firewallDao.listStaticNatByVmId(vm.getId());
List<FirewallRuleVO> firewallRules = new ArrayList<FirewallRuleVO>(); List<FirewallRuleVO> firewallRules = new ArrayList<FirewallRuleVO>();
//Make a list of firewall rules to reprogram // Make a list of firewall rules to reprogram
for (PortForwardingRuleVO pfRule : pfRules) { for (PortForwardingRuleVO pfRule : pfRules) {
FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(pfRule.getId()); FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(pfRule.getId());
if (relatedRule != null) { if (relatedRule != null) {
firewallRules.add(relatedRule); firewallRules.add(relatedRule);
} }
} }
for (FirewallRuleVO staticNatRule : staticNatRules) { for (FirewallRuleVO staticNatRule : staticNatRules) {
FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(staticNatRule.getId()); FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(staticNatRule.getId());
if (relatedRule != null) { if (relatedRule != null) {
firewallRules.add(relatedRule); firewallRules.add(relatedRule);
} }
} }
Set<Long> ipsToReprogram = new HashSet<Long>(); Set<Long> ipsToReprogram = new HashSet<Long>();
if (firewallRules.isEmpty()) { if (firewallRules.isEmpty()) {
@ -642,7 +644,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
for (Long ipId : ipsToReprogram) { for (Long ipId : ipsToReprogram) {
s_logger.debug("Applying firewall rules for ip address id=" + ipId + " as a part of vm expunge"); s_logger.debug("Applying firewall rules for ip address id=" + ipId + " as a part of vm expunge");
try { try {
success = success && applyFirewallRules(ipId,_accountMgr.getSystemAccount()); success = success && applyFirewallRules(ipId, _accountMgr.getSystemAccount());
} catch (ResourceUnavailableException ex) { } catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to apply port forwarding rules for ip id=" + ipId); s_logger.warn("Failed to apply port forwarding rules for ip id=" + ipId);
success = false; success = false;
@ -652,17 +654,18 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
return success; return success;
} }
@Override @Override
public boolean addSystemFirewallRules(IPAddressVO ip, Account acct) { public boolean addSystemFirewallRules(IPAddressVO ip, Account acct) {
List<FirewallRuleVO> systemRules = _firewallDao.listSystemRules(); List<FirewallRuleVO> systemRules = _firewallDao.listSystemRules();
for (FirewallRuleVO rule : systemRules) { for (FirewallRuleVO rule : systemRules) {
try { try {
this.createFirewallRule(ip.getId(), acct, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), this.createFirewallRule(ip.getId(), acct, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(),
rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), rule.getRelated(), FirewallRuleType.System); rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), rule.getRelated(), FirewallRuleType.System);
} catch (Exception e) { } catch (Exception e) {
s_logger.debug("Failed to add system wide firewall rule, due to:" + e.toString()); s_logger.debug("Failed to add system wide firewall rule, due to:" + e.toString());
} }
} }
return true; return true;
} }
} }

View File

@ -183,7 +183,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
} }
return null; return null;
} }
private boolean genericValidator(CreateLBStickinessPolicyCmd cmd) throws InvalidParameterValueException { private boolean genericValidator(CreateLBStickinessPolicyCmd cmd) throws InvalidParameterValueException {
LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId()); LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId());
/* Validation : check for valid Method name and params */ /* Validation : check for valid Method name and params */
@ -192,13 +192,13 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
boolean methodMatch = false; boolean methodMatch = false;
if (stickinessMethodList == null) { if (stickinessMethodList == null) {
throw new InvalidParameterValueException("Failed: No Stickiness method available for LB rule:" + cmd.getLbRuleId()); throw new InvalidParameterValueException("Failed: No Stickiness method available for LB rule:" + cmd.getLbRuleId());
} }
for (LbStickinessMethod method : stickinessMethodList) { for (LbStickinessMethod method : stickinessMethodList) {
if (method.getMethodName().equalsIgnoreCase(cmd.getStickinessMethodName())) { if (method.getMethodName().equalsIgnoreCase(cmd.getStickinessMethodName())) {
methodMatch = true; methodMatch = true;
Map apiParamList = cmd.getparamList(); Map apiParamList = cmd.getparamList();
List<LbStickinessMethodParam> methodParamList = method.getParamList(); List<LbStickinessMethodParam> methodParamList = method.getParamList();
Map<String, String> tempParamList = new HashMap<String, String>(); Map<String, String> tempParamList = new HashMap<String, String>();
/* /*
@ -246,15 +246,15 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
if (methodMatch == false) { if (methodMatch == false) {
throw new InvalidParameterValueException("Failed to match Stickiness method name for LB rule:" + cmd.getLbRuleId()); throw new InvalidParameterValueException("Failed to match Stickiness method name for LB rule:" + cmd.getLbRuleId());
} }
/* Validation : check for the multiple policies to the rule id */ /* Validation : check for the multiple policies to the rule id */
List<LBStickinessPolicyVO> stickinessPolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(cmd.getLbRuleId(), false); List<LBStickinessPolicyVO> stickinessPolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(cmd.getLbRuleId(), false);
if (stickinessPolicies.size() > 0) { if (stickinessPolicies.size() > 0) {
throw new InvalidParameterValueException("Failed to create Stickiness policy: Already policy attached " + cmd.getLbRuleId()); throw new InvalidParameterValueException("Failed to create Stickiness policy: Already policy attached " + cmd.getLbRuleId());
} }
return true; return true;
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Override @Override
@DB @DB
@ -265,20 +265,20 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
/* Validation : check corresponding load balancer rule exist */ /* Validation : check corresponding load balancer rule exist */
LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId()); LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId());
if (loadBalancer == null) { if (loadBalancer == null) {
throw new InvalidParameterValueException("Failed: LB rule id: " + cmd.getLbRuleId() + " not present "); throw new InvalidParameterValueException("Failed: LB rule id: " + cmd.getLbRuleId() + " not present ");
} }
_accountMgr.checkAccess(caller.getCaller(), null, true, loadBalancer); _accountMgr.checkAccess(caller.getCaller(), null, true, loadBalancer);
if (loadBalancer.getState() == FirewallRule.State.Revoke) { if (loadBalancer.getState() == FirewallRule.State.Revoke) {
throw new InvalidParameterValueException("Failed: LB rule id:" + cmd.getLbRuleId() + " is in deleting state: "); throw new InvalidParameterValueException("Failed: LB rule id:" + cmd.getLbRuleId() + " is in deleting state: ");
} }
/* Generic validations */ /* Generic validations */
if (!genericValidator(cmd)) { if (!genericValidator(cmd)) {
throw new InvalidParameterValueException("Failed to create Stickiness policy: Validation Failed " + cmd.getLbRuleId()); throw new InvalidParameterValueException("Failed to create Stickiness policy: Validation Failed " + cmd.getLbRuleId());
} }
/* Specific validations using network element validator for specific validations*/ /* Specific validations using network element validator for specific validations */
LBStickinessPolicyVO lbpolicy = new LBStickinessPolicyVO(loadBalancer.getId(), cmd.getLBStickinessPolicyName(), cmd.getStickinessMethodName(), cmd.getparamList(), cmd.getDescription()); LBStickinessPolicyVO lbpolicy = new LBStickinessPolicyVO(loadBalancer.getId(), cmd.getLBStickinessPolicyName(), cmd.getStickinessMethodName(), cmd.getparamList(), cmd.getDescription());
List<LbStickinessPolicy> policyList = new ArrayList<LbStickinessPolicy>(); List<LbStickinessPolicy> policyList = new ArrayList<LbStickinessPolicy>();
policyList.add(new LbStickinessPolicy(cmd.getStickinessMethodName(), lbpolicy.getParams())); policyList.add(new LbStickinessPolicy(cmd.getStickinessMethodName(), lbpolicy.getParams()));
@ -295,11 +295,11 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
_lbDao.persist(loadBalancer); _lbDao.persist(loadBalancer);
return policy; return policy;
} }
@Override @Override
@DB @DB
@ActionEvent(eventType = EventTypes.EVENT_LB_STICKINESSPOLICY_CREATE, eventDescription = "Apply Stickinesspolicy to load balancer ", async = true) @ActionEvent(eventType = EventTypes.EVENT_LB_STICKINESSPOLICY_CREATE, eventDescription = "Apply Stickinesspolicy to load balancer ", async = true)
public boolean applyLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) { public boolean applyLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) {
try { try {
applyLoadBalancerConfig(cmd.getLbRuleId()); applyLoadBalancerConfig(cmd.getLbRuleId());
@ -310,19 +310,19 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
} }
return true; return true;
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_LB_STICKINESSPOLICY_DELETE, eventDescription = "revoking LB Stickiness policy ", async = true) @ActionEvent(eventType = EventTypes.EVENT_LB_STICKINESSPOLICY_DELETE, eventDescription = "revoking LB Stickiness policy ", async = true)
public boolean deleteLBStickinessPolicy(long stickinessPolicyId) { public boolean deleteLBStickinessPolicy(long stickinessPolicyId) {
UserContext caller = UserContext.current(); UserContext caller = UserContext.current();
LBStickinessPolicyVO stickinessPolicy = _lb2stickinesspoliciesDao.findById(stickinessPolicyId); LBStickinessPolicyVO stickinessPolicy = _lb2stickinesspoliciesDao.findById(stickinessPolicyId);
if (stickinessPolicy == null) { if (stickinessPolicy == null) {
throw new InvalidParameterException("Invalid Stickiness policy id value: " + stickinessPolicyId); throw new InvalidParameterException("Invalid Stickiness policy id value: " + stickinessPolicyId);
} }
LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(stickinessPolicy.getLoadBalancerId())); LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(stickinessPolicy.getLoadBalancerId()));
if (loadBalancer == null) { if (loadBalancer == null) {
throw new InvalidParameterException("Invalid Load balancer :"+stickinessPolicy.getLoadBalancerId()+" for Stickiness policy id: " + stickinessPolicyId); throw new InvalidParameterException("Invalid Load balancer :" + stickinessPolicy.getLoadBalancerId() + " for Stickiness policy id: " + stickinessPolicyId);
} }
long loadBalancerId = loadBalancer.getId(); long loadBalancerId = loadBalancer.getId();
_accountMgr.checkAccess(caller.getCaller(), null, true, loadBalancer); _accountMgr.checkAccess(caller.getCaller(), null, true, loadBalancer);
@ -335,7 +335,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
stickinessPolicy.setRevoke(true); stickinessPolicy.setRevoke(true);
_lb2stickinesspoliciesDao.persist(stickinessPolicy); _lb2stickinesspoliciesDao.persist(stickinessPolicy);
s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", stickinesspolicyID " + stickinessPolicyId); s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", stickinesspolicyID " + stickinessPolicyId);
if (!applyLoadBalancerConfig(loadBalancerId)) { if (!applyLoadBalancerConfig(loadBalancerId)) {
s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for stickinesspolicyID " + stickinessPolicyId); s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for stickinesspolicyID " + stickinessPolicyId);
throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for stickinesspolicyID " + stickinessPolicyId); throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for stickinesspolicyID " + stickinessPolicyId);
@ -346,8 +346,8 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
return false; return false;
} }
return true; return true;
} }
@Override @Override
@DB @DB
@ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription = "assigning to load balancer", async = true) @ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription = "assigning to load balancer", async = true)
@ -421,9 +421,9 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
} catch (ResourceUnavailableException e) { } catch (ResourceUnavailableException e) {
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
} }
if(!success){ if (!success) {
throw new CloudRuntimeException("Failed to add load balancer rule id " + loadBalancerId + " for vms " + instanceIds); throw new CloudRuntimeException("Failed to add load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
} }
return success; return success;
@ -456,7 +456,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
_lb2VmMapDao.persist(map); _lb2VmMapDao.persist(map);
s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + instanceId); s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + instanceId);
} }
if (!applyLoadBalancerConfig(loadBalancerId)) { if (!applyLoadBalancerConfig(loadBalancerId)) {
s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds); s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds); throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
@ -465,9 +465,9 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
} catch (ResourceUnavailableException e) { } catch (ResourceUnavailableException e) {
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
} }
if(!success){ if (!success) {
throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds); throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
} }
return success; return success;
} }
@ -521,9 +521,9 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
_accountMgr.checkAccess(caller, null, true, rule); _accountMgr.checkAccess(caller, null, true, rule);
boolean result = deleteLoadBalancerRule(loadBalancerId, apply, caller, ctx.getCallerUserId()); boolean result = deleteLoadBalancerRule(loadBalancerId, apply, caller, ctx.getCallerUserId());
if(!result){ if (!result) {
throw new CloudRuntimeException("Unable to remove load balancer rule " + loadBalancerId); throw new CloudRuntimeException("Unable to remove load balancer rule " + loadBalancerId);
} }
return result; return result;
} }
@ -560,12 +560,12 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), 0, lb.getId(), null); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), 0, lb.getId(), null);
_usageEventDao.persist(usageEvent); _usageEventDao.persist(usageEvent);
} }
txn.commit(); txn.commit();
//gather external network usage stats for this lb rule // gather external network usage stats for this lb rule
NetworkVO network = _networkDao.findById(lb.getNetworkId()); NetworkVO network = _networkDao.findById(lb.getNetworkId());
if(network != null){ if (network != null) {
if (_networkMgr.networkIsConfiguredForExternalNetworking(network.getDataCenterId(), network.getId())) { if (_networkMgr.networkIsConfiguredForExternalNetworking(network.getDataCenterId(), network.getId())) {
_externalLBMgr.updateExternalLoadBalancerNetworkUsageStats(loadBalancerId); _externalLBMgr.updateExternalLoadBalancerNetworkUsageStats(loadBalancerId);
} }
@ -590,22 +590,21 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
} else { } else {
_firewallDao.remove(lb.getId()); _firewallDao.remove(lb.getId());
} }
_elbMgr.handleDeleteLoadBalancerRule(lb, callerUserId, caller); _elbMgr.handleDeleteLoadBalancerRule(lb, callerUserId, caller);
if (success) { if (success) {
s_logger.debug("Load balancer with id " + lb.getId() + " is removed successfully"); s_logger.debug("Load balancer with id " + lb.getId() + " is removed successfully");
} }
return success; return success;
} }
@Override
@Override
@ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription = "creating load balancer") @ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription = "creating load balancer")
public LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException, InsufficientAddressCapacityException { public LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException, InsufficientAddressCapacityException {
Account lbOwner = _accountMgr.getAccount(lb.getEntityOwnerId()); Account lbOwner = _accountMgr.getAccount(lb.getEntityOwnerId());
int defPortStart = lb.getDefaultPortStart(); int defPortStart = lb.getDefaultPortStart();
int defPortEnd = lb.getDefaultPortEnd(); int defPortEnd = lb.getDefaultPortEnd();
@ -618,50 +617,50 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
if ((lb.getAlgorithm() == null) || !NetUtils.isValidAlgorithm(lb.getAlgorithm())) { if ((lb.getAlgorithm() == null) || !NetUtils.isValidAlgorithm(lb.getAlgorithm())) {
throw new InvalidParameterValueException("Invalid algorithm: " + lb.getAlgorithm()); throw new InvalidParameterValueException("Invalid algorithm: " + lb.getAlgorithm());
} }
Long ipAddrId = lb.getSourceIpAddressId(); Long ipAddrId = lb.getSourceIpAddressId();
IPAddressVO ipAddressVo = null; IPAddressVO ipAddressVo = null;
if (ipAddrId != null) { if (ipAddrId != null) {
ipAddressVo = _ipAddressDao.findById(ipAddrId); ipAddressVo = _ipAddressDao.findById(ipAddrId);
// Validate ip address // Validate ip address
if (ipAddressVo == null) { if (ipAddressVo == null) {
throw new InvalidParameterValueException("Unable to create load balance rule; ip id=" + ipAddrId + " doesn't exist in the system"); throw new InvalidParameterValueException("Unable to create load balance rule; ip id=" + ipAddrId + " doesn't exist in the system");
} else if (ipAddressVo.isOneToOneNat()) { } else if (ipAddressVo.isOneToOneNat()) {
throw new NetworkRuleConflictException("Can't do load balance on ip address: " + ipAddressVo.getAddress()); throw new NetworkRuleConflictException("Can't do load balance on ip address: " + ipAddressVo.getAddress());
} }
_networkMgr.checkIpForService(ipAddressVo, Service.Lb); _networkMgr.checkIpForService(ipAddressVo, Service.Lb);
} }
LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb, lbOwner, lb.getNetworkId()); LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb, lbOwner, lb.getNetworkId());
if (result == null){ if (result == null) {
IpAddress ip = null; IpAddress ip = null;
Network guestNetwork = _networkMgr.getNetwork(lb.getNetworkId()); Network guestNetwork = _networkMgr.getNetwork(lb.getNetworkId());
NetworkOffering off = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); NetworkOffering off = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
if (off.getElasticLb() && ipAddressVo == null) { if (off.getElasticLb() && ipAddressVo == null) {
ip = _networkMgr.assignElasticIp(lb.getNetworkId(), lbOwner, true, false); ip = _networkMgr.assignElasticIp(lb.getNetworkId(), lbOwner, true, false);
lb.setSourceIpAddressId(ip.getId()); lb.setSourceIpAddressId(ip.getId());
} }
try { try {
result = createLoadBalancer(lb, openFirewall); result = createLoadBalancer(lb, openFirewall);
} catch (Exception ex) { } catch (Exception ex) {
s_logger.warn("Failed to create load balancer due to ", ex); s_logger.warn("Failed to create load balancer due to ", ex);
} finally { } finally {
if (result == null && ip != null) { if (result == null && ip != null) {
s_logger.debug("Releasing elastic IP address " + ip + " as corresponding lb rule failed to create"); s_logger.debug("Releasing elastic IP address " + ip + " as corresponding lb rule failed to create");
_networkMgr.handleElasticIpRelease(ip); _networkMgr.handleElasticIpRelease(ip);
} }
} }
} }
if (result == null){ if (result == null) {
throw new CloudRuntimeException("Failed to create load balancer rule: "+lb.getName()); throw new CloudRuntimeException("Failed to create load balancer rule: " + lb.getName());
} }
return result; return result;
} }
@DB @DB
public LoadBalancer createLoadBalancer(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException { public LoadBalancer createLoadBalancer(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException {
UserContext caller = UserContext.current(); UserContext caller = UserContext.current();
@ -669,7 +668,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
int defPortStart = lb.getDefaultPortStart(); int defPortStart = lb.getDefaultPortStart();
int srcPortEnd = lb.getSourcePortEnd(); int srcPortEnd = lb.getSourcePortEnd();
long sourceIpId = lb.getSourceIpAddressId(); long sourceIpId = lb.getSourceIpAddressId();
IPAddressVO ipAddr = _ipAddressDao.findById(sourceIpId); IPAddressVO ipAddr = _ipAddressDao.findById(sourceIpId);
Long networkId = ipAddr.getSourceNetworkId(); Long networkId = ipAddr.getSourceNetworkId();
// make sure ip address exists // make sure ip address exists
@ -677,12 +676,11 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id" + sourceIpId); throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id" + sourceIpId);
} else if (ipAddr.isOneToOneNat()) { } else if (ipAddr.isOneToOneNat()) {
throw new InvalidParameterValueException("Unable to create load balancer rule; ip id=" + sourceIpId + " has static nat enabled"); throw new InvalidParameterValueException("Unable to create load balancer rule; ip id=" + sourceIpId + " has static nat enabled");
} }
_firewallMgr.validateFirewallRule(caller.getCaller(), ipAddr, srcPortStart, srcPortEnd, lb.getProtocol(), Purpose.LoadBalancing, FirewallRuleType.User); _firewallMgr.validateFirewallRule(caller.getCaller(), ipAddr, srcPortStart, srcPortEnd, lb.getProtocol(), Purpose.LoadBalancing, FirewallRuleType.User);
networkId = ipAddr.getAssociatedWithNetworkId();
networkId = ipAddr.getAssociatedWithNetworkId();
if (networkId == null) { if (networkId == null) {
throw new InvalidParameterValueException("Unable to create load balancer rule ; ip id=" + sourceIpId + " is not associated with any network"); throw new InvalidParameterValueException("Unable to create load balancer rule ; ip id=" + sourceIpId + " is not associated with any network");
@ -699,12 +697,12 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
LoadBalancerVO newRule = new LoadBalancerVO(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourceIpAddressId(), lb.getSourcePortEnd(), lb.getDefaultPortStart(), LoadBalancerVO newRule = new LoadBalancerVO(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourceIpAddressId(), lb.getSourcePortEnd(), lb.getDefaultPortStart(),
lb.getAlgorithm(), network.getId(), ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId()); lb.getAlgorithm(), network.getId(), ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId());
newRule = _lbDao.persist(newRule); newRule = _lbDao.persist(newRule);
if (openFirewall) { if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(sourceIpId, caller.getCaller(), lb.getSourcePortStart(), lb.getSourcePortEnd(), lb.getProtocol(), null, null, newRule.getId()); _firewallMgr.createRuleForAllCidrs(sourceIpId, caller.getCaller(), lb.getSourcePortStart(), lb.getSourcePortEnd(), lb.getProtocol(), null, null, newRule.getId());
} }
@ -721,7 +719,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_CREATE, ipAddr.getAllocatedToAccountId(), ipAddr.getDataCenterId(), newRule.getId(), null); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_CREATE, ipAddr.getAllocatedToAccountId(), ipAddr.getDataCenterId(), newRule.getId(), null);
_usageEventDao.persist(usageEvent); _usageEventDao.persist(usageEvent);
txn.commit(); txn.commit();
return newRule; return newRule;
} catch (Exception e) { } catch (Exception e) {
success = false; success = false;
@ -731,11 +729,11 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
throw new CloudRuntimeException("Unable to add rule for ip address id=" + newRule.getSourceIpAddressId(), e); throw new CloudRuntimeException("Unable to add rule for ip address id=" + newRule.getSourceIpAddressId(), e);
} finally { } finally {
if (!success && newRule != null) { if (!success && newRule != null) {
txn.start(); txn.start();
_firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false); _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
_lbDao.remove(newRule.getId()); _lbDao.remove(newRule.getId());
txn.commit(); txn.commit();
} }
} }
@ -743,8 +741,8 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
@Override @Override
public boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException { public boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException {
LoadBalancerVO lb = _lbDao.findById(lbRuleId); LoadBalancerVO lb = _lbDao.findById(lbRuleId);
//get all rules in transition state // get all rules in transition state
List<LoadBalancerVO> lbs = _lbDao.listInTransitionStateByNetworkId(lb.getNetworkId()); List<LoadBalancerVO> lbs = _lbDao.listInTransitionStateByNetworkId(lb.getNetworkId());
return applyLoadBalancerRules(lbs, true); return applyLoadBalancerRules(lbs, true);
} }
@ -768,7 +766,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
List<LbDestination> dstList = getExistingDestinations(lb.getId()); List<LbDestination> dstList = getExistingDestinations(lb.getId());
List<LbStickinessPolicy> policyList = getStickinessPolicies(lb.getId()); List<LbStickinessPolicy> policyList = getStickinessPolicies(lb.getId());
LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList,policyList); LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList);
rules.add(loadBalancing); rules.add(loadBalancing);
} }
@ -779,12 +777,12 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
if (updateRulesInDB) { if (updateRulesInDB) {
for (LoadBalancerVO lb : lbs) { for (LoadBalancerVO lb : lbs) {
boolean checkForReleaseElasticIp = false; boolean checkForReleaseElasticIp = false;
txn.start(); txn.start();
if (lb.getState() == FirewallRule.State.Revoke) { if (lb.getState() == FirewallRule.State.Revoke) {
_lbDao.remove(lb.getId()); _lbDao.remove(lb.getId());
s_logger.debug("LB " + lb.getId() + " is successfully removed"); s_logger.debug("LB " + lb.getId() + " is successfully removed");
checkForReleaseElasticIp = true; checkForReleaseElasticIp = true;
} else if (lb.getState() == FirewallRule.State.Add) { } else if (lb.getState() == FirewallRule.State.Add) {
lb.setState(FirewallRule.State.Active); lb.setState(FirewallRule.State.Active);
s_logger.debug("LB rule " + lb.getId() + " state is set to Active"); s_logger.debug("LB rule " + lb.getId() + " state is set to Active");
@ -806,56 +804,56 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) { if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) {
lb.setState(FirewallRule.State.Add); lb.setState(FirewallRule.State.Add);
_lbDao.persist(lb); _lbDao.persist(lb);
s_logger.debug("LB rule " + lb.getId() + " state is set to Add as there are no more active LB-VM mappings"); s_logger.debug("LB rule " + lb.getId() + " state is set to Add as there are no more active LB-VM mappings");
} }
// remove LB-Stickiness policy mapping that were state to revoke // remove LB-Stickiness policy mapping that were state to revoke
List<LBStickinessPolicyVO> stickinesspolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(lb.getId(), true); List<LBStickinessPolicyVO> stickinesspolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(lb.getId(), true);
if (!stickinesspolicies.isEmpty()){ if (!stickinesspolicies.isEmpty()) {
_lb2stickinesspoliciesDao.remove(lb.getId(), true); _lb2stickinesspoliciesDao.remove(lb.getId(), true);
s_logger.debug("Load balancer rule id " + lb.getId() + " is removed stickiness policies"); s_logger.debug("Load balancer rule id " + lb.getId() + " is removed stickiness policies");
} }
txn.commit(); txn.commit();
if (checkForReleaseElasticIp) { if (checkForReleaseElasticIp) {
boolean success = true; boolean success = true;
long count = _firewallDao.countRulesByIpId(lb.getSourceIpAddressId()); long count = _firewallDao.countRulesByIpId(lb.getSourceIpAddressId());
if (count == 0) { if (count == 0) {
try { try {
success = handleElasticLBIpRelease(lb); success = handleElasticLBIpRelease(lb);
} catch (Exception ex) { } catch (Exception ex) {
s_logger.warn("Failed to release elastic ip as a part of lb rule " + lb + " deletion due to exception ", ex); s_logger.warn("Failed to release elastic ip as a part of lb rule " + lb + " deletion due to exception ", ex);
success = false; success = false;
} finally { } finally {
if (!success) { if (!success) {
s_logger.warn("Failed to release elastic ip as a part of lb rule " + lb + " deletion"); s_logger.warn("Failed to release elastic ip as a part of lb rule " + lb + " deletion");
} }
} }
} }
} }
} }
} }
return true; return true;
} }
protected boolean handleElasticLBIpRelease(LoadBalancerVO lb) { protected boolean handleElasticLBIpRelease(LoadBalancerVO lb) {
IpAddress ip = _ipAddressDao.findById(lb.getSourceIpAddressId()); IpAddress ip = _ipAddressDao.findById(lb.getSourceIpAddressId());
boolean success = true; boolean success = true;
if (ip.getElastic()) { if (ip.getElastic()) {
s_logger.debug("Releasing elastic ip address " + lb.getSourceIpAddressId() + " as a part of delete lb rule"); s_logger.debug("Releasing elastic ip address " + lb.getSourceIpAddressId() + " as a part of delete lb rule");
if (!_networkMgr.releasePublicIpAddress(lb.getSourceIpAddressId(), UserContext.current().getCallerUserId(), UserContext.current().getCaller())) { if (!_networkMgr.releasePublicIpAddress(lb.getSourceIpAddressId(), UserContext.current().getCallerUserId(), UserContext.current().getCaller())) {
s_logger.warn("Unable to release elastic ip address id=" + lb.getSourceIpAddressId() + " as a part of delete lb rule"); s_logger.warn("Unable to release elastic ip address id=" + lb.getSourceIpAddressId() + " as a part of delete lb rule");
success = false; success = false;
} else { } else {
s_logger.warn("Successfully released elastic ip address id=" + lb.getSourceIpAddressId() + " as a part of delete lb rule"); s_logger.warn("Successfully released elastic ip address id=" + lb.getSourceIpAddressId() + " as a part of delete lb rule");
} }
} }
return success; return success;
} }
@Override @Override
public boolean removeAllLoadBalanacersForIp(long ipId, Account caller, long callerUserId) { public boolean removeAllLoadBalanacersForIp(long ipId, Account caller, long callerUserId) {
@ -886,19 +884,19 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
} }
return true; return true;
} }
@Override @Override
public List<LbStickinessPolicy> getStickinessPolicies(long lbId) { public List<LbStickinessPolicy> getStickinessPolicies(long lbId) {
List<LbStickinessPolicy> stickinessPolicies = new ArrayList<LbStickinessPolicy>(); List<LbStickinessPolicy> stickinessPolicies = new ArrayList<LbStickinessPolicy>();
List<LBStickinessPolicyVO> sDbpolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(lbId); List<LBStickinessPolicyVO> sDbpolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(lbId);
for (LBStickinessPolicyVO sDbPolicy : sDbpolicies) { for (LBStickinessPolicyVO sDbPolicy : sDbpolicies) {
LbStickinessPolicy sPolicy = new LbStickinessPolicy(sDbPolicy.getMethodName(), sDbPolicy.getParams(), sDbPolicy.isRevoke()); LbStickinessPolicy sPolicy = new LbStickinessPolicy(sDbPolicy.getMethodName(), sDbPolicy.getParams(), sDbPolicy.isRevoke());
stickinessPolicies.add(sPolicy); stickinessPolicies.add(sPolicy);
} }
return stickinessPolicies; return stickinessPolicies;
} }
@Override @Override
public List<LbDestination> getExistingDestinations(long lbId) { public List<LbDestination> getExistingDestinations(long lbId) {
List<LbDestination> dstList = new ArrayList<LbDestination>(); List<LbDestination> dstList = new ArrayList<LbDestination>();
@ -927,7 +925,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
return true; return true;
} }
@Override @Override
public boolean stop() { public boolean stop() {
return true; return true;
} }
@ -946,12 +944,12 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
String description = cmd.getDescription(); String description = cmd.getDescription();
String algorithm = cmd.getAlgorithm(); String algorithm = cmd.getAlgorithm();
LoadBalancerVO lb = _lbDao.findById(lbRuleId); LoadBalancerVO lb = _lbDao.findById(lbRuleId);
if (lb == null) { if (lb == null) {
throw new InvalidParameterValueException("Unable to find lb rule by id=" + lbRuleId); throw new InvalidParameterValueException("Unable to find lb rule by id=" + lbRuleId);
} }
//check permissions // check permissions
_accountMgr.checkAccess(caller, null, true, lb); _accountMgr.checkAccess(caller, null, true, lb);
if (name != null) { if (name != null) {
@ -980,10 +978,10 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
} }
} }
if(!success){ if (!success) {
throw new CloudRuntimeException("Failed to update load balancer rule: "+lbRuleId); throw new CloudRuntimeException("Failed to update load balancer rule: " + lbRuleId);
} }
return lb; return lb;
} }
@ -1037,14 +1035,17 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
return loadBalancerInstances; return loadBalancerInstances;
} }
@Override @Override
public List<LbStickinessMethod> getStickinessMethods(long networkid) public List<LbStickinessMethod> getStickinessMethods(long networkid)
{ {
String capability = getLBStickinessCapability(networkid); String capability = getLBStickinessCapability(networkid);
if (capability == null) return null; if (capability == null)
return null;
Gson gson = new Gson(); Gson gson = new Gson();
java.lang.reflect.Type listType = new TypeToken<List<LbStickinessMethod>>() {}.getType(); java.lang.reflect.Type listType = new TypeToken<List<LbStickinessMethod>>() {
List<LbStickinessMethod> result = gson.fromJson(capability,listType); }.getType();
List<LbStickinessMethod> result = gson.fromJson(capability, listType);
return result; return result;
} }
@ -1056,14 +1057,14 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
if (loadBalancer == null) { if (loadBalancer == null) {
return null; return null;
} }
_accountMgr.checkAccess(caller, null, true, loadBalancer); _accountMgr.checkAccess(caller, null, true, loadBalancer);
List<LBStickinessPolicyVO> sDbpolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(cmd.getLbRuleId()); List<LBStickinessPolicyVO> sDbpolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(cmd.getLbRuleId());
return sDbpolicies; return sDbpolicies;
} }
@Override @Override
public List<LoadBalancerVO> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) { public List<LoadBalancerVO> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) {
Long ipId = cmd.getPublicIpId(); Long ipId = cmd.getPublicIpId();
@ -1072,7 +1073,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
String name = cmd.getLoadBalancerRuleName(); String name = cmd.getLoadBalancerRuleName();
String keyword = cmd.getKeyword(); String keyword = cmd.getKeyword();
Long instanceId = cmd.getVirtualMachineId(); Long instanceId = cmd.getVirtualMachineId();
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>(); List<Long> permittedAccounts = new ArrayList<Long>();
@ -1080,12 +1081,12 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll()); _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll());
Long domainId = domainIdRecursiveListProject.first(); Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second(); Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(LoadBalancerVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); Filter searchFilter = new Filter(LoadBalancerVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<LoadBalancerVO> sb = _lbDao.createSearchBuilder(); SearchBuilder<LoadBalancerVO> sb = _lbDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
sb.and("sourceIpAddress", sb.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ); sb.and("sourceIpAddress", sb.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
@ -1104,7 +1105,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
SearchCriteria<LoadBalancerVO> sc = sb.create(); SearchCriteria<LoadBalancerVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
if (keyword != null) { if (keyword != null) {
SearchCriteria<LoadBalancerVO> ssc = _lbDao.createSearchCriteria(); SearchCriteria<LoadBalancerVO> ssc = _lbDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");

View File

@ -28,28 +28,30 @@ import com.cloud.network.rules.FirewallRule.FirewallRuleType;
import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.user.Account; import com.cloud.user.Account;
public interface FirewallManager extends FirewallService{ public interface FirewallManager extends FirewallService {
/** /**
* detectRulesConflict finds conflicts in networking rules. It checks for * detectRulesConflict finds conflicts in networking rules. It checks for
* conflicts between the following types of netowrking rules; * conflicts between the following types of netowrking rules;
* 1. one to one nat ip forwarding * 1. one to one nat ip forwarding
* 2. port forwarding * 2. port forwarding
* 3. load balancing * 3. load balancing
* *
* It is possible for two conflicting rules to be added at the same time * It is possible for two conflicting rules to be added at the same time
* and conflicts are detected between those two rules. In this case, it * and conflicts are detected between those two rules. In this case, it
* is possible for both rules to be rolled back when, technically, we should * is possible for both rules to be rolled back when, technically, we should
* only roll back one of the rules. However, the chances of that is low * only roll back one of the rules. However, the chances of that is low
* and the user can simply re-add one of the rules themselves. * and the user can simply re-add one of the rules themselves.
* *
* @param newRule the new rule created. * @param newRule
* @param ipAddress ip address that back up the new rule. * the new rule created.
* @param ipAddress
* ip address that back up the new rule.
* @throws NetworkRuleConflictException * @throws NetworkRuleConflictException
*/ */
void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException; void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException;
void validateFirewallRule(Account caller, IPAddressVO ipAddress, Integer portStart, Integer portEnd, String proto, Purpose purpose, FirewallRuleType type); void validateFirewallRule(Account caller, IPAddressVO ipAddress, Integer portStart, Integer portEnd, String proto, Purpose purpose, FirewallRuleType type);
boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException; boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException;
boolean applyFirewallRules(List<FirewallRuleVO> rules, boolean continueOnError, Account caller); boolean applyFirewallRules(List<FirewallRuleVO> rules, boolean continueOnError, Account caller);
@ -57,17 +59,22 @@ public interface FirewallManager extends FirewallService{
public void revokeRule(FirewallRuleVO rule, Account caller, long userId, boolean needUsageEvent); public void revokeRule(FirewallRuleVO rule, Account caller, long userId, boolean needUsageEvent);
boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException; boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException;
/** /**
* Revokes a firewall rule * Revokes a firewall rule
* @param ruleId the id of the rule to revoke. *
* @param caller TODO * @param ruleId
* @param userId TODO * the id of the rule to revoke.
* @param caller
* TODO
* @param userId
* TODO
* @return * @return
*/ */
boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId); boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId);
FirewallRule createFirewallRule(long ipAddrId, Account caller, String xId, Integer portStart, Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType, Long relatedRuleId, FirewallRule.FirewallRuleType type) FirewallRule createFirewallRule(long ipAddrId, Account caller, String xId, Integer portStart, Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType, Long relatedRuleId,
FirewallRule.FirewallRuleType type)
throws NetworkRuleConflictException; throws NetworkRuleConflictException;
FirewallRule createRuleForAllCidrs(long ipAddrId, Account caller, Integer startPort, Integer endPort, String protocol, Integer icmpCode, Integer icmpType, Long relatedRuleId) throws NetworkRuleConflictException; FirewallRule createRuleForAllCidrs(long ipAddrId, Account caller, Integer startPort, Integer endPort, String protocol, Integer icmpCode, Integer icmpType, Long relatedRuleId) throws NetworkRuleConflictException;
@ -75,6 +82,7 @@ public interface FirewallManager extends FirewallService{
boolean revokeAllFirewallRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException; boolean revokeAllFirewallRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException;
boolean revokeFirewallRulesForVm(long vmId); boolean revokeFirewallRulesForVm(long vmId);
boolean addSystemFirewallRules(IPAddressVO ip, Account acct); boolean addSystemFirewallRules(IPAddressVO ip, Account acct);
} }

View File

@ -26,54 +26,56 @@ import com.cloud.network.IpAddress;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.uservm.UserVm; import com.cloud.uservm.UserVm;
/** /**
* Rules Manager manages the network rules created for different networks. * Rules Manager manages the network rules created for different networks.
*/ */
public interface RulesManager extends RulesService { public interface RulesManager extends RulesService {
boolean applyPortForwardingRules(long ipAddressId, boolean continueOnError, Account caller); boolean applyPortForwardingRules(long ipAddressId, boolean continueOnError, Account caller);
boolean applyStaticNatRules(long sourceIpId, boolean continueOnError, Account caller); boolean applyStaticNatRules(long sourceIpId, boolean continueOnError, Account caller);
boolean applyPortForwardingRulesForNetwork(long networkId, boolean continueOnError, Account caller); boolean applyPortForwardingRulesForNetwork(long networkId, boolean continueOnError, Account caller);
boolean applyStaticNatRulesForNetwork(long networkId, boolean continueOnError, Account caller); boolean applyStaticNatRulesForNetwork(long networkId, boolean continueOnError, Account caller);
void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller); void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller);
void checkRuleAndUserVm(FirewallRule rule, UserVm userVm, Account caller); void checkRuleAndUserVm(FirewallRule rule, UserVm userVm, Account caller);
boolean revokeAllPFAndStaticNatRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException; boolean revokeAllPFAndStaticNatRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException;
boolean revokeAllPFStaticNatRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException; boolean revokeAllPFStaticNatRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException;
List<? extends FirewallRule> listFirewallRulesByIp(long ipAddressId); List<? extends FirewallRule> listFirewallRulesByIp(long ipAddressId);
/** /**
* Returns a list of port forwarding rules that are ready for application * Returns a list of port forwarding rules that are ready for application
* to the network elements for this ip. * to the network elements for this ip.
*
* @param ip * @param ip
* @return List of PortForwardingRule * @return List of PortForwardingRule
*/ */
List<? extends PortForwardingRule> listPortForwardingRulesForApplication(long ipId); List<? extends PortForwardingRule> listPortForwardingRulesForApplication(long ipId);
List<? extends PortForwardingRule> gatherPortForwardingRulesForApplication(List<? extends IpAddress> addrs); List<? extends PortForwardingRule> gatherPortForwardingRulesForApplication(List<? extends IpAddress> addrs);
boolean revokePortForwardingRulesForVm(long vmId); boolean revokePortForwardingRulesForVm(long vmId);
boolean revokeStaticNatRulesForVm(long vmId); boolean revokeStaticNatRulesForVm(long vmId);
FirewallRule[] reservePorts(IpAddress ip, String protocol, FirewallRule.Purpose purpose, boolean openFirewall, Account caller, int... ports) throws NetworkRuleConflictException; FirewallRule[] reservePorts(IpAddress ip, String protocol, FirewallRule.Purpose purpose, boolean openFirewall, Account caller, int... ports) throws NetworkRuleConflictException;
boolean releasePorts(long ipId, String protocol, FirewallRule.Purpose purpose, int... ports);
boolean releasePorts(long ipId, String protocol, FirewallRule.Purpose purpose, int... ports);
List<PortForwardingRuleVO> listByNetworkId(long networkId);
List<PortForwardingRuleVO> listByNetworkId(long networkId);
boolean applyStaticNatForIp(long sourceIpId, boolean continueOnError, Account caller, boolean forRevoke); boolean applyStaticNatForIp(long sourceIpId, boolean continueOnError, Account caller, boolean forRevoke);
boolean applyStaticNatsForNetwork(long networkId, boolean continueOnError, Account caller); boolean applyStaticNatsForNetwork(long networkId, boolean continueOnError, Account caller);
void enableElasticIpAndStaticNatForVm(UserVm vm, boolean getNewIp) throws InsufficientAddressCapacityException; void enableElasticIpAndStaticNatForVm(UserVm vm, boolean getNewIp) throws InsufficientAddressCapacityException;
boolean disableStaticNat(long ipAddressId, Account caller, long callerUserId, boolean releaseIpIfElastic) throws ResourceUnavailableException; boolean disableStaticNat(long ipAddressId, Account caller, long callerUserId, boolean releaseIpIfElastic) throws ResourceUnavailableException;
} }

View File

@ -155,7 +155,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
} }
} }
@Override @DB @Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating forwarding rule", create = true) @ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating forwarding rule", create = true)
public PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException { public PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException {
UserContext ctx = UserContext.current(); UserContext ctx = UserContext.current();
@ -164,30 +165,30 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
Long ipAddrId = rule.getSourceIpAddressId(); Long ipAddrId = rule.getSourceIpAddressId();
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId); IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
// Validate ip address // Validate ip address
if (ipAddress == null) { if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system"); throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system");
} else if (ipAddress.isOneToOneNat()) { } else if (ipAddress.isOneToOneNat()) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " has static nat enabled"); throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " has static nat enabled");
} }
_firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.PortForwarding, FirewallRuleType.User); _firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.PortForwarding, FirewallRuleType.User);
Long networkId = ipAddress.getAssociatedWithNetworkId(); Long networkId = ipAddress.getAssociatedWithNetworkId();
Long accountId = ipAddress.getAllocatedToAccountId(); Long accountId = ipAddress.getAllocatedToAccountId();
Long domainId = ipAddress.getAllocatedInDomainId(); Long domainId = ipAddress.getAllocatedInDomainId();
// start port can't be bigger than end port // start port can't be bigger than end port
if (rule.getDestinationPortStart() > rule.getDestinationPortEnd()) { if (rule.getDestinationPortStart() > rule.getDestinationPortEnd()) {
throw new InvalidParameterValueException("Start port can't be bigger than end port"); throw new InvalidParameterValueException("Start port can't be bigger than end port");
} }
// check that the port ranges are of equal size // check that the port ranges are of equal size
if ((rule.getDestinationPortEnd() - rule.getDestinationPortStart()) != (rule.getSourcePortEnd() - rule.getSourcePortStart())) { if ((rule.getDestinationPortEnd() - rule.getDestinationPortStart()) != (rule.getSourcePortEnd() - rule.getSourcePortStart())) {
throw new InvalidParameterValueException("Source port and destination port ranges should be of equal sizes."); throw new InvalidParameterValueException("Source port and destination port ranges should be of equal sizes.");
} }
// validate user VM exists // validate user VM exists
UserVm vm = _vmDao.findById(vmId); UserVm vm = _vmDao.findById(vmId);
if (vm == null) { if (vm == null) {
@ -195,7 +196,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
} else { } else {
checkRuleAndUserVm(rule, vm, caller); checkRuleAndUserVm(rule, vm, caller);
} }
_networkMgr.checkIpForService(ipAddress, Service.PortForwarding); _networkMgr.checkIpForService(ipAddress, Service.PortForwarding);
// Verify that vm has nic in the network // Verify that vm has nic in the network
@ -209,12 +210,12 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
PortForwardingRuleVO newRule = new PortForwardingRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), dstIp, rule.getDestinationPortStart(), PortForwardingRuleVO newRule = new PortForwardingRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), dstIp, rule.getDestinationPortStart(),
rule.getDestinationPortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, vmId); rule.getDestinationPortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, vmId);
newRule = _portForwardingDao.persist(newRule); newRule = _portForwardingDao.persist(newRule);
//create firewallRule for 0.0.0.0/0 cidr // create firewallRule for 0.0.0.0/0 cidr
if (openFirewall) { if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId()); _firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId());
} }
@ -230,18 +231,17 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
txn.commit(); txn.commit();
return newRule; return newRule;
} catch (Exception e) { } catch (Exception e) {
if (newRule != null) { if (newRule != null) {
txn.start(); txn.start();
//no need to apply the rule as it wasn't programmed on the backend yet // no need to apply the rule as it wasn't programmed on the backend yet
_firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false); _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
_portForwardingDao.remove(newRule.getId()); _portForwardingDao.remove(newRule.getId());
txn.commit(); txn.commit();
} }
if (e instanceof NetworkRuleConflictException) { if (e instanceof NetworkRuleConflictException) {
throw (NetworkRuleConflictException) e; throw (NetworkRuleConflictException) e;
} }
@ -249,7 +249,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
} }
} }
@Override @DB @Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating static nat rule", create = true) @ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating static nat rule", create = true)
public StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException { public StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
@ -257,44 +258,42 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
Long ipAddrId = rule.getSourceIpAddressId(); Long ipAddrId = rule.getSourceIpAddressId();
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId); IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
// Validate ip address // Validate ip address
if (ipAddress == null) { if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to create static nat rule; ip id=" + ipAddrId + " doesn't exist in the system"); throw new InvalidParameterValueException("Unable to create static nat rule; ip id=" + ipAddrId + " doesn't exist in the system");
} else if (ipAddress.isSourceNat() || !ipAddress.isOneToOneNat() || ipAddress.getAssociatedWithVmId() == null) { } else if (ipAddress.isSourceNat() || !ipAddress.isOneToOneNat() || ipAddress.getAssociatedWithVmId() == null) {
throw new NetworkRuleConflictException("Can't do static nat on ip address: " + ipAddress.getAddress()); throw new NetworkRuleConflictException("Can't do static nat on ip address: " + ipAddress.getAddress());
} }
_firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.StaticNat, FirewallRuleType.User); _firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.StaticNat, FirewallRuleType.User);
Long networkId = ipAddress.getAssociatedWithNetworkId(); Long networkId = ipAddress.getAssociatedWithNetworkId();
Long accountId = ipAddress.getAllocatedToAccountId(); Long accountId = ipAddress.getAllocatedToAccountId();
Long domainId = ipAddress.getAllocatedInDomainId(); Long domainId = ipAddress.getAllocatedInDomainId();
_networkMgr.checkIpForService(ipAddress, Service.StaticNat); _networkMgr.checkIpForService(ipAddress, Service.StaticNat);
Network network = _networkMgr.getNetwork(networkId); Network network = _networkMgr.getNetwork(networkId);
NetworkOffering off = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); NetworkOffering off = _configMgr.getNetworkOffering(network.getNetworkOfferingId());
if (off.getElasticIp()) { if (off.getElasticIp()) {
throw new InvalidParameterValueException("Can't create ip forwarding rules for the network where elasticIP service is enabled"); throw new InvalidParameterValueException("Can't create ip forwarding rules for the network where elasticIP service is enabled");
} }
String dstIp = _networkMgr.getIpInNetwork(ipAddress.getAssociatedWithVmId(), networkId); String dstIp = _networkMgr.getIpInNetwork(ipAddress.getAssociatedWithVmId(), networkId);
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
FirewallRuleVO newRule = new FirewallRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol().toLowerCase(), FirewallRuleVO newRule = new FirewallRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol().toLowerCase(),
networkId, accountId, domainId, rule.getPurpose(), null, null, null, null); networkId, accountId, domainId, rule.getPurpose(), null, null, null, null);
newRule = _firewallDao.persist(newRule); newRule = _firewallDao.persist(newRule);
//create firewallRule for 0.0.0.0/0 cidr // create firewallRule for 0.0.0.0/0 cidr
if (openFirewall) { if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId()); _firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId());
} }
try { try {
_firewallMgr.detectRulesConflict(newRule, ipAddress); _firewallMgr.detectRulesConflict(newRule, ipAddress);
@ -310,15 +309,15 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
return staticNatRule; return staticNatRule;
} catch (Exception e) { } catch (Exception e) {
if (newRule != null) { if (newRule != null) {
txn.start(); txn.start();
//no need to apply the rule as it wasn't programmed on the backend yet // no need to apply the rule as it wasn't programmed on the backend yet
_firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false); _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
_portForwardingDao.remove(newRule.getId()); _portForwardingDao.remove(newRule.getId());
txn.commit(); txn.commit();
} }
if (e instanceof NetworkRuleConflictException) { if (e instanceof NetworkRuleConflictException) {
throw (NetworkRuleConflictException) e; throw (NetworkRuleConflictException) e;
} }
@ -329,7 +328,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
@Override @Override
public boolean enableStaticNat(long ipId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException { public boolean enableStaticNat(long ipId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException {
UserContext ctx = UserContext.current(); UserContext ctx = UserContext.current();
Account caller = ctx.getCaller(); Account caller = ctx.getCaller();
// Verify input parameters // Verify input parameters
UserVmVO vm = _vmDao.findById(vmId); UserVmVO vm = _vmDao.findById(vmId);
@ -364,14 +363,14 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
// Verify ip address parameter // Verify ip address parameter
isIpReadyForStaticNat(vmId, ipAddress, caller, ctx.getCallerUserId()); isIpReadyForStaticNat(vmId, ipAddress, caller, ctx.getCallerUserId());
_networkMgr.checkIpForService(ipAddress, Service.StaticNat); _networkMgr.checkIpForService(ipAddress, Service.StaticNat);
ipAddress.setOneToOneNat(true); ipAddress.setOneToOneNat(true);
ipAddress.setAssociatedWithVmId(vmId); ipAddress.setAssociatedWithVmId(vmId);
if (_ipAddressDao.update(ipAddress.getId(), ipAddress)) { if (_ipAddressDao.update(ipAddress.getId(), ipAddress)) {
//enable static nat on the backend // enable static nat on the backend
s_logger.trace("Enabling static nat for ip address " + ipAddress + " and vm id=" + vmId + " on the backend"); s_logger.trace("Enabling static nat for ip address " + ipAddress + " and vm id=" + vmId + " on the backend");
if (applyStaticNatForIp(ipId, false, caller, false)) { if (applyStaticNatForIp(ipId, false, caller, false)) {
return true; return true;
@ -388,8 +387,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
} }
} }
protected void isIpReadyForStaticNat(long vmId, IPAddressVO ipAddress, Account caller, long callerUserId) throws NetworkRuleConflictException, ResourceUnavailableException { protected void isIpReadyForStaticNat(long vmId, IPAddressVO ipAddress, Account caller, long callerUserId) throws NetworkRuleConflictException, ResourceUnavailableException {
if (ipAddress.isSourceNat()) { if (ipAddress.isSourceNat()) {
throw new InvalidParameterValueException("Can't enable static, ip address " + ipAddress + " is a sourceNat ip address"); throw new InvalidParameterValueException("Can't enable static, ip address " + ipAddress + " is a sourceNat ip address");
} }
@ -398,7 +397,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
if (portForwardingRules != null && !portForwardingRules.isEmpty()) { if (portForwardingRules != null && !portForwardingRules.isEmpty()) {
throw new NetworkRuleConflictException("Failed to enable static nat for the ip address " + ipAddress + " as it already has PortForwarding rules assigned"); throw new NetworkRuleConflictException("Failed to enable static nat for the ip address " + ipAddress + " as it already has PortForwarding rules assigned");
} }
List<FirewallRuleVO> loadBalancingRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipAddress.getId(), Purpose.LoadBalancing); List<FirewallRuleVO> loadBalancingRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipAddress.getId(), Purpose.LoadBalancing);
if (loadBalancingRules != null && !loadBalancingRules.isEmpty()) { if (loadBalancingRules != null && !loadBalancingRules.isEmpty()) {
throw new NetworkRuleConflictException("Failed to enable static nat for the ip address " + ipAddress + " as it already has LoadBalancing rules assigned"); throw new NetworkRuleConflictException("Failed to enable static nat for the ip address " + ipAddress + " as it already has LoadBalancing rules assigned");
@ -406,33 +405,33 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
} else if (ipAddress.getAssociatedWithVmId() != null && ipAddress.getAssociatedWithVmId().longValue() != vmId) { } else if (ipAddress.getAssociatedWithVmId() != null && ipAddress.getAssociatedWithVmId().longValue() != vmId) {
throw new NetworkRuleConflictException("Failed to enable static for the ip address " + ipAddress + " and vm id=" + vmId + " as it's already assigned to antoher vm"); throw new NetworkRuleConflictException("Failed to enable static for the ip address " + ipAddress + " and vm id=" + vmId + " as it's already assigned to antoher vm");
} }
IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vmId);
if (oldIP != null) {
//If elasticIP functionality is supported in the network, we always have to disable static nat on the old ip in order to re-enable it on the new one
Long networkId = oldIP.getAssociatedWithNetworkId();
boolean reassignStaticNat = false;
if (networkId != null) {
Network guestNetwork = _networkMgr.getNetwork(networkId);
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
if (offering.getElasticIp()) {
reassignStaticNat = true;
}
}
// If there is public ip address already associated with the vm, throw an exception
if (!reassignStaticNat) {
throw new InvalidParameterValueException("Failed to enable static nat for the ip address id=" + ipAddress.getId() + " as vm id=" + vmId + " is already associated with ip id=" + oldIP.getId());
}
//unassign old static nat rule
s_logger.debug("Disassociating static nat for ip " + oldIP);
if (!disableStaticNat(oldIP.getId(), caller, callerUserId, true)) {
throw new CloudRuntimeException("Failed to disable old static nat rule for vm id=" + vmId + " and ip " + oldIP);
}
}
}
IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vmId);
if (oldIP != null) {
// If elasticIP functionality is supported in the network, we always have to disable static nat on the old
// ip in order to re-enable it on the new one
Long networkId = oldIP.getAssociatedWithNetworkId();
boolean reassignStaticNat = false;
if (networkId != null) {
Network guestNetwork = _networkMgr.getNetwork(networkId);
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
if (offering.getElasticIp()) {
reassignStaticNat = true;
}
}
// If there is public ip address already associated with the vm, throw an exception
if (!reassignStaticNat) {
throw new InvalidParameterValueException("Failed to enable static nat for the ip address id=" + ipAddress.getId() + " as vm id=" + vmId + " is already associated with ip id=" + oldIP.getId());
}
// unassign old static nat rule
s_logger.debug("Disassociating static nat for ip " + oldIP);
if (!disableStaticNat(oldIP.getId(), caller, callerUserId, true)) {
throw new CloudRuntimeException("Failed to disable old static nat rule for vm id=" + vmId + " and ip " + oldIP);
}
}
}
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_DELETE, eventDescription = "revoking forwarding rule", async = true) @ActionEvent(eventType = EventTypes.EVENT_NET_RULE_DELETE, eventDescription = "revoking forwarding rule", async = true)
@ -447,8 +446,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
_accountMgr.checkAccess(caller, null, true, rule); _accountMgr.checkAccess(caller, null, true, rule);
if(!revokePortForwardingRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)){ if (!revokePortForwardingRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)) {
throw new CloudRuntimeException("Failed to delete port forwarding rule"); throw new CloudRuntimeException("Failed to delete port forwarding rule");
} }
return true; return true;
} }
@ -482,8 +481,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
_accountMgr.checkAccess(caller, null, true, rule); _accountMgr.checkAccess(caller, null, true, rule);
if(!revokeStaticNatRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)){ if (!revokeStaticNatRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)) {
throw new CloudRuntimeException("Failed to revoke forwarding rule"); throw new CloudRuntimeException("Failed to revoke forwarding rule");
} }
return true; return true;
} }
@ -537,7 +536,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
return success; return success;
} }
@Override @Override
public boolean revokeStaticNatRulesForVm(long vmId) { public boolean revokeStaticNatRulesForVm(long vmId) {
boolean success = true; boolean success = true;
@ -598,12 +597,12 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll()); _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll());
Long domainId = domainIdRecursiveListProject.first(); Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second(); Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<PortForwardingRuleVO> sb = _portForwardingDao.createSearchBuilder(); SearchBuilder<PortForwardingRuleVO> sb = _portForwardingDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), Op.EQ); sb.and("id", sb.entity().getId(), Op.EQ);
sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ); sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
sb.and("purpose", sb.entity().getPurpose(), Op.EQ); sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
@ -623,21 +622,20 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
return _portForwardingDao.search(sc, filter); return _portForwardingDao.search(sc, filter);
} }
@Override @Override
public List<String> getSourceCidrs(long ruleId){ public List<String> getSourceCidrs(long ruleId) {
return _firewallCidrsDao.getSourceCidrs(ruleId); return _firewallCidrsDao.getSourceCidrs(ruleId);
} }
@Override @Override
public boolean applyPortForwardingRules(long ipId, boolean continueOnError, Account caller) { public boolean applyPortForwardingRules(long ipId, boolean continueOnError, Account caller) {
List<PortForwardingRuleVO> rules = _portForwardingDao.listForApplication(ipId); List<PortForwardingRuleVO> rules = _portForwardingDao.listForApplication(ipId);
if (rules.size() == 0) { if (rules.size() == 0) {
s_logger.debug("There are no firwall rules to apply for ip id=" + ipId); s_logger.debug("There are no firwall rules to apply for ip id=" + ipId);
return true; return true;
} }
if (caller != null) { if (caller != null) {
_accountMgr.checkAccess(caller, null, true, rules.toArray(new PortForwardingRuleVO[rules.size()])); _accountMgr.checkAccess(caller, null, true, rules.toArray(new PortForwardingRuleVO[rules.size()]));
@ -739,7 +737,6 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
return true; return true;
} }
@Override @Override
public boolean applyStaticNatsForNetwork(long networkId, boolean continueOnError, Account caller) { public boolean applyStaticNatsForNetwork(long networkId, boolean continueOnError, Account caller) {
List<IPAddressVO> ips = _ipAddressDao.listStaticNatPublicIps(networkId); List<IPAddressVO> ips = _ipAddressDao.listStaticNatPublicIps(networkId);
@ -747,11 +744,11 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
s_logger.debug("There are no static nat to apply for network id=" + networkId); s_logger.debug("There are no static nat to apply for network id=" + networkId);
return true; return true;
} }
if (caller != null) { if (caller != null) {
_accountMgr.checkAccess(caller, null, true, ips.toArray(new IPAddressVO[ips.size()])); _accountMgr.checkAccess(caller, null, true, ips.toArray(new IPAddressVO[ips.size()]));
} }
List<StaticNat> staticNats = new ArrayList<StaticNat>(); List<StaticNat> staticNats = new ArrayList<StaticNat>();
for (IPAddressVO ip : ips) { for (IPAddressVO ip : ips) {
// Get nic IP4 address // Get nic IP4 address
@ -759,7 +756,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
StaticNatImpl staticNat = new StaticNatImpl(ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), networkId, ip.getId(), dstIp, false); StaticNatImpl staticNat = new StaticNatImpl(ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), networkId, ip.getId(), dstIp, false);
staticNats.add(staticNat); staticNats.add(staticNat);
} }
try { try {
if (!_networkMgr.applyStaticNats(staticNats, continueOnError)) { if (!_networkMgr.applyStaticNats(staticNats, continueOnError)) {
return false; return false;
@ -774,7 +771,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
@Override @Override
public List<? extends FirewallRule> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll) { public List<? extends FirewallRule> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>(); List<Long> permittedAccounts = new ArrayList<Long>();
if (ipId != null) { if (ipId != null) {
@ -790,16 +787,15 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
domainId = domainIdRecursiveListProject.first(); domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second(); isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, start, size); Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, start, size);
SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder(); SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ); sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
sb.and("purpose", sb.entity().getPurpose(), Op.EQ); sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
sb.and("id", sb.entity().getId(), Op.EQ); sb.and("id", sb.entity().getId(), Op.EQ);
if (vmId != null) { if (vmId != null) {
SearchBuilder<IPAddressVO> ipSearch = _ipAddressDao.createSearchBuilder(); SearchBuilder<IPAddressVO> ipSearch = _ipAddressDao.createSearchBuilder();
ipSearch.and("associatedWithVmId", ipSearch.entity().getAssociatedWithVmId(), Op.EQ); ipSearch.and("associatedWithVmId", ipSearch.entity().getAssociatedWithVmId(), Op.EQ);
@ -809,7 +805,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
SearchCriteria<FirewallRuleVO> sc = sb.create(); SearchCriteria<FirewallRuleVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sc.setParameters("purpose", Purpose.StaticNat); sc.setParameters("purpose", Purpose.StaticNat);
if (id != null) { if (id != null) {
sc.setParameters("id", id); sc.setParameters("id", id);
} }
@ -828,8 +824,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "applying port forwarding rule", async = true) @ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "applying port forwarding rule", async = true)
public boolean applyPortForwardingRules(long ipId, Account caller) throws ResourceUnavailableException { public boolean applyPortForwardingRules(long ipId, Account caller) throws ResourceUnavailableException {
if(!applyPortForwardingRules(ipId, false, caller)){ if (!applyPortForwardingRules(ipId, false, caller)) {
throw new CloudRuntimeException("Failed to apply port forwarding rule"); throw new CloudRuntimeException("Failed to apply port forwarding rule");
} }
return true; return true;
} }
@ -837,8 +833,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "applying static nat rule", async = true) @ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "applying static nat rule", async = true)
public boolean applyStaticNatRules(long ipId, Account caller) throws ResourceUnavailableException { public boolean applyStaticNatRules(long ipId, Account caller) throws ResourceUnavailableException {
if(!applyStaticNatRules(ipId, false, caller)){ if (!applyStaticNatRules(ipId, false, caller)) {
throw new CloudRuntimeException("Failed to apply static nat rule"); throw new CloudRuntimeException("Failed to apply static nat rule");
} }
return true; return true;
} }
@ -862,20 +858,19 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
s_logger.debug("Releasing " + staticNatRules.size() + " static nat rules for ip id=" + ipId); s_logger.debug("Releasing " + staticNatRules.size() + " static nat rules for ip id=" + ipId);
} }
for (FirewallRuleVO rule : staticNatRules) { for (FirewallRuleVO rule : staticNatRules) {
// Mark all static nat rules as Revoke, but don't revoke them yet // Mark all static nat rules as Revoke, but don't revoke them yet
revokeStaticNatRuleInternal(rule.getId(), caller, userId, false); revokeStaticNatRuleInternal(rule.getId(), caller, userId, false);
} }
//revoke static nat for the ip address // revoke static nat for the ip address
boolean success = applyStaticNatForIp(ipId, false, caller, true); boolean success = applyStaticNatForIp(ipId, false, caller, true);
// revoke all port forwarding rules // revoke all port forwarding rules
success = success && applyPortForwardingRules(ipId, true, caller); success = success && applyPortForwardingRules(ipId, true, caller);
// revoke all all static nat rules // revoke all all static nat rules
success = success && applyStaticNatRules(ipId, true, caller); success = success && applyStaticNatRules(ipId, true, caller);
// Now we check again in case more rules have been inserted. // Now we check again in case more rules have been inserted.
rules.addAll(_portForwardingDao.listByIpAndNotRevoked(ipId)); rules.addAll(_portForwardingDao.listByIpAndNotRevoked(ipId));
@ -969,10 +964,10 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
for (int i = 0; i < ports.length; i++) { for (int i = 0; i < ports.length; i++) {
rules[i] = new FirewallRuleVO(null, ip.getId(), ports[i], protocol, ip.getAssociatedWithNetworkId(), ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), purpose, null, null, null, null); rules[i] = new FirewallRuleVO(null, ip.getId(), ports[i], protocol, ip.getAssociatedWithNetworkId(), ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), purpose, null, null, null, null);
rules[i] = _firewallDao.persist(rules[i]); rules[i] = _firewallDao.persist(rules[i]);
if (openFirewall) { if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(ip.getId(), caller, ports[i], ports[i], protocol, null, null, rules[i].getId()); _firewallMgr.createRuleForAllCidrs(ip.getId(), caller, ports[i], ports[i], protocol, null, null, rules[i].getId());
} }
@ -1023,36 +1018,38 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
public List<PortForwardingRuleVO> listByNetworkId(long networkId) { public List<PortForwardingRuleVO> listByNetworkId(long networkId) {
return _portForwardingDao.listByNetwork(networkId); return _portForwardingDao.listByNetwork(networkId);
} }
@Override @Override
public boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException{ public boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException {
UserContext ctx = UserContext.current(); UserContext ctx = UserContext.current();
Account caller = ctx.getCaller(); Account caller = ctx.getCaller();
IPAddressVO ipAddress = _ipAddressDao.findById(ipId); IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
checkIpAndUserVm(ipAddress, null, caller); checkIpAndUserVm(ipAddress, null, caller);
if (ipAddress.getElastic()) { if (ipAddress.getElastic()) {
throw new InvalidParameterValueException("Can't disable static nat for elastic IP address " + ipAddress); throw new InvalidParameterValueException("Can't disable static nat for elastic IP address " + ipAddress);
} }
Long vmId = ipAddress.getAssociatedWithVmId(); Long vmId = ipAddress.getAssociatedWithVmId();
if (vmId == null) { if (vmId == null) {
throw new InvalidParameterValueException("IP address " + ipAddress + " is not associated with any vm Id"); throw new InvalidParameterValueException("IP address " + ipAddress + " is not associated with any vm Id");
}
// if network has elastic IP functionality supported, we first have to disable static nat on old ip in order to
// re-enable it on the new one
// enable static nat takes care of that
Network guestNetwork = _networkMgr.getNetwork(ipAddress.getAssociatedWithNetworkId());
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
if (offering.getElasticIp()) {
enableElasticIpAndStaticNatForVm(_vmDao.findById(vmId), true);
return true;
} else {
return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false);
} }
//if network has elastic IP functionality supported, we first have to disable static nat on old ip in order to re-enable it on the new one
//enable static nat takes care of that
Network guestNetwork = _networkMgr.getNetwork(ipAddress.getAssociatedWithNetworkId());
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
if (offering.getElasticIp()) {
enableElasticIpAndStaticNatForVm(_vmDao.findById(vmId), true);
return true;
} else {
return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false);
}
} }
@Override @DB @Override
@DB
public boolean disableStaticNat(long ipId, Account caller, long callerUserId, boolean releaseIpIfElastic) throws ResourceUnavailableException { public boolean disableStaticNat(long ipId, Account caller, long callerUserId, boolean releaseIpIfElastic) throws ResourceUnavailableException {
boolean success = true; boolean success = true;
@ -1062,8 +1059,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
if (!ipAddress.isOneToOneNat()) { if (!ipAddress.isOneToOneNat()) {
throw new InvalidParameterValueException("One to one nat is not enabled for the ip id=" + ipId); throw new InvalidParameterValueException("One to one nat is not enabled for the ip id=" + ipId);
} }
//Revoke all firewall rules for the ip // Revoke all firewall rules for the ip
try { try {
s_logger.debug("Revoking all " + Purpose.Firewall + "rules as a part of disabling static nat for public IP id=" + ipId); s_logger.debug("Revoking all " + Purpose.Firewall + "rules as a part of disabling static nat for public IP id=" + ipId);
if (!_firewallMgr.revokeFirewallRulesForIp(ipId, callerUserId, caller)) { if (!_firewallMgr.revokeFirewallRulesForIp(ipId, callerUserId, caller)) {
@ -1079,22 +1076,22 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
s_logger.warn("Unable to revoke all static nat rules for ip " + ipAddress); s_logger.warn("Unable to revoke all static nat rules for ip " + ipAddress);
success = false; success = false;
} }
if (success) { if (success) {
boolean isIpElastic = ipAddress.getElastic(); boolean isIpElastic = ipAddress.getElastic();
ipAddress.setOneToOneNat(false); ipAddress.setOneToOneNat(false);
ipAddress.setAssociatedWithVmId(null); ipAddress.setAssociatedWithVmId(null);
if (isIpElastic && !releaseIpIfElastic) { if (isIpElastic && !releaseIpIfElastic) {
ipAddress.setElastic(false); ipAddress.setElastic(false);
} }
_ipAddressDao.update(ipAddress.getId(), ipAddress); _ipAddressDao.update(ipAddress.getId(), ipAddress);
if (isIpElastic && releaseIpIfElastic && !_networkMgr.handleElasticIpRelease(ipAddress)) { if (isIpElastic && releaseIpIfElastic && !_networkMgr.handleElasticIpRelease(ipAddress)) {
s_logger.warn("Failed to release elastic ip address " + ipAddress); s_logger.warn("Failed to release elastic ip address " + ipAddress);
success = false; success = false;
} }
return true; return true;
} else { } else {
s_logger.warn("Failed to disable one to one nat for the ip address id" + ipId); s_logger.warn("Failed to disable one to one nat for the ip address id" + ipId);
@ -1125,13 +1122,13 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
return new StaticNatRuleImpl(ruleVO, dstIp); return new StaticNatRuleImpl(ruleVO, dstIp);
} }
@Override @Override
public boolean applyStaticNatForIp(long sourceIpId, boolean continueOnError, Account caller, boolean forRevoke) { public boolean applyStaticNatForIp(long sourceIpId, boolean continueOnError, Account caller, boolean forRevoke) {
List<StaticNat> staticNats = new ArrayList<StaticNat>(); List<StaticNat> staticNats = new ArrayList<StaticNat>();
IpAddress sourceIp = _ipAddressDao.findById(sourceIpId); IpAddress sourceIp = _ipAddressDao.findById(sourceIpId);
if (!sourceIp.isOneToOneNat()) { if (!sourceIp.isOneToOneNat()) {
s_logger.debug("Source ip id=" + sourceIpId + " is not one to one nat"); s_logger.debug("Source ip id=" + sourceIpId + " is not one to one nat");
return true; return true;
@ -1141,30 +1138,30 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
if (networkId == null) { if (networkId == null) {
throw new CloudRuntimeException("Ip address is not associated with any network"); throw new CloudRuntimeException("Ip address is not associated with any network");
} }
UserVmVO vm = _vmDao.findById(sourceIp.getAssociatedWithVmId()); UserVmVO vm = _vmDao.findById(sourceIp.getAssociatedWithVmId());
Network network = _networkMgr.getNetwork(networkId); Network network = _networkMgr.getNetwork(networkId);
if (network == null) { if (network == null) {
throw new CloudRuntimeException("Unable to find ip address to map to in vm id=" + vm.getId()); throw new CloudRuntimeException("Unable to find ip address to map to in vm id=" + vm.getId());
} }
if (caller != null) { if (caller != null) {
_accountMgr.checkAccess(caller, null, true, sourceIp); _accountMgr.checkAccess(caller, null, true, sourceIp);
} }
//create new static nat rule // create new static nat rule
// Get nic IP4 address // Get nic IP4 address
String dstIp; String dstIp;
if (forRevoke) { if (forRevoke) {
dstIp = _networkMgr.getIpInNetworkIncludingRemoved(sourceIp.getAssociatedWithVmId(), networkId); dstIp = _networkMgr.getIpInNetworkIncludingRemoved(sourceIp.getAssociatedWithVmId(), networkId);
} else { } else {
dstIp = _networkMgr.getIpInNetwork(sourceIp.getAssociatedWithVmId(), networkId); dstIp = _networkMgr.getIpInNetwork(sourceIp.getAssociatedWithVmId(), networkId);
} }
StaticNatImpl staticNat = new StaticNatImpl(sourceIp.getAllocatedToAccountId(), sourceIp.getAllocatedInDomainId(), networkId, sourceIpId, dstIp, forRevoke); StaticNatImpl staticNat = new StaticNatImpl(sourceIp.getAllocatedToAccountId(), sourceIp.getAllocatedInDomainId(), networkId, sourceIpId, dstIp, forRevoke);
staticNats.add(staticNat); staticNats.add(staticNat);
try { try {
if (!_networkMgr.applyStaticNats(staticNats, continueOnError)) { if (!_networkMgr.applyStaticNats(staticNats, continueOnError)) {
return false; return false;
@ -1176,52 +1173,51 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
return true; return true;
} }
@Override
@Override public void enableElasticIpAndStaticNatForVm(UserVm vm, boolean getNewIp) throws InsufficientAddressCapacityException {
public void enableElasticIpAndStaticNatForVm(UserVm vm, boolean getNewIp) throws InsufficientAddressCapacityException{ boolean success = true;
boolean success = true;
// enable static nat if eIp capability is supported
//enable static nat if eIp capability is supported List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
List<? extends Nic> nics = _nicDao.listByVmId(vm.getId()); for (Nic nic : nics) {
for (Nic nic : nics) { Network guestNetwork = _networkMgr.getNetwork(nic.getNetworkId());
Network guestNetwork = _networkMgr.getNetwork(nic.getNetworkId()); NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); if (offering.getElasticIp()) {
if (offering.getElasticIp()) {
// check if there is already static nat enabled
//check if there is already static nat enabled if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) {
if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) { s_logger.debug("Vm " + vm + " already has elastic ip associated with it in guest network " + guestNetwork);
s_logger.debug("Vm " + vm + " already has elastic ip associated with it in guest network " + guestNetwork); continue;
continue; }
}
s_logger.debug("Allocating elastic ip and enabling static nat for it for the vm " + vm + " in guest network " + guestNetwork);
s_logger.debug("Allocating elastic ip and enabling static nat for it for the vm " + vm + " in guest network " + guestNetwork); IpAddress ip = _networkMgr.assignElasticIp(guestNetwork.getId(), _accountMgr.getAccount(vm.getAccountId()), false, true);
IpAddress ip = _networkMgr.assignElasticIp(guestNetwork.getId(), _accountMgr.getAccount(vm.getAccountId()), false, true); if (ip == null) {
if (ip == null) { throw new CloudRuntimeException("Failed to allocate elastic ip for vm " + vm + " in guest network " + guestNetwork);
throw new CloudRuntimeException("Failed to allocate elastic ip for vm " + vm + " in guest network " + guestNetwork); }
}
s_logger.debug("Allocated elastic ip " + ip + ", now enabling static nat on it for vm " + vm);
s_logger.debug("Allocated elastic ip " + ip + ", now enabling static nat on it for vm " + vm);
try {
try { success = enableStaticNat(ip.getId(), vm.getId());
success = enableStaticNat(ip.getId(), vm.getId()); } catch (NetworkRuleConflictException ex) {
} catch (NetworkRuleConflictException ex) { s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex);
s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex); success = false;
success = false; } catch (ResourceUnavailableException ex) {
} catch (ResourceUnavailableException ex) { s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex);
s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex); success = false;
success = false; }
}
if (!success) {
if (!success) { s_logger.warn("Failed to enable static nat on elastic ip " + ip + " for the vm " + vm + ", releasing the ip...");
s_logger.warn("Failed to enable static nat on elastic ip " + ip + " for the vm " + vm + ", releasing the ip..."); _networkMgr.handleElasticIpRelease(ip);
_networkMgr.handleElasticIpRelease(ip); throw new CloudRuntimeException("Failed to enable static nat on elastic ip for the vm " + vm);
throw new CloudRuntimeException("Failed to enable static nat on elastic ip for the vm " + vm); } else {
} else { s_logger.warn("Succesfully enabled static nat on elastic ip " + ip + " for the vm " + vm);
s_logger.warn("Succesfully enabled static nat on elastic ip " + ip + " for the vm " + vm); }
} }
} }
}
} }
} }

View File

@ -36,93 +36,93 @@ import com.cloud.offering.NetworkOffering;
import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDao;
@Entity @Entity
@Table(name="network_offerings") @Table(name = "network_offerings")
public class NetworkOfferingVO implements NetworkOffering, Identity { public class NetworkOfferingVO implements NetworkOffering, Identity {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id") @Column(name = "id")
long id; long id;
@Column(name="name") @Column(name = "name")
String name; String name;
@Column(name="unique_name") @Column(name = "unique_name")
private String uniqueName; private String uniqueName;
@Column(name="display_text") @Column(name = "display_text")
String displayText; String displayText;
@Column(name="nw_rate") @Column(name = "nw_rate")
Integer rateMbps; Integer rateMbps;
@Column(name="mc_rate") @Column(name = "mc_rate")
Integer multicastRateMbps; Integer multicastRateMbps;
@Column(name="traffic_type") @Column(name = "traffic_type")
@Enumerated(value=EnumType.STRING) @Enumerated(value = EnumType.STRING)
TrafficType trafficType; TrafficType trafficType;
@Column(name="specify_vlan") @Column(name = "specify_vlan")
boolean specifyVlan; boolean specifyVlan;
@Column(name="system_only") @Column(name = "system_only")
boolean systemOnly; boolean systemOnly;
@Column(name="service_offering_id") @Column(name = "service_offering_id")
Long serviceOfferingId; Long serviceOfferingId;
@Column(name="tags", length=4096) @Column(name = "tags", length = 4096)
String tags; String tags;
@Column(name="default") @Column(name = "default")
boolean isDefault; boolean isDefault;
@Column(name="availability") @Column(name = "availability")
@Enumerated(value=EnumType.STRING) @Enumerated(value = EnumType.STRING)
Availability availability; Availability availability;
@Column(name="state") @Column(name = "state")
@Enumerated(value=EnumType.STRING) @Enumerated(value = EnumType.STRING)
State state = State.Disabled; State state = State.Disabled;
@Column(name=GenericDao.REMOVED_COLUMN) @Column(name = GenericDao.REMOVED_COLUMN)
Date removed; Date removed;
@Column(name=GenericDao.CREATED_COLUMN) @Column(name = GenericDao.CREATED_COLUMN)
Date created; Date created;
@Column(name="guest_type") @Column(name = "guest_type")
@Enumerated(value=EnumType.STRING) @Enumerated(value = EnumType.STRING)
Network.GuestType guestType; Network.GuestType guestType;
@Column(name="dedicated_lb_service") @Column(name = "dedicated_lb_service")
boolean dedicatedLB; boolean dedicatedLB;
@Column(name="shared_source_nat_service") @Column(name = "shared_source_nat_service")
boolean sharedSourceNat; boolean sharedSourceNat;
@Column(name="specify_ip_ranges") @Column(name = "specify_ip_ranges")
boolean specifyIpRanges = false; boolean specifyIpRanges = false;
@Column(name="sort_key") @Column(name = "sort_key")
int sortKey; int sortKey;
@Column(name="uuid") @Column(name = "uuid")
String uuid; String uuid;
@Column(name="redundant_router_service") @Column(name = "redundant_router_service")
boolean redundantRouter; boolean redundantRouter;
@Column(name="conserve_mode") @Column(name = "conserve_mode")
boolean conserveMode; boolean conserveMode;
@Column(name="elastic_ip_service") @Column(name = "elastic_ip_service")
boolean elasticIp; boolean elasticIp;
@Column(name="elastic_lb_service") @Column(name = "elastic_lb_service")
boolean elasticLb; boolean elasticLb;
@Override @Override
public String getDisplayText() { public String getDisplayText() {
return displayText; return displayText;
@ -132,7 +132,7 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
public long getId() { public long getId() {
return id; return id;
} }
@Override @Override
public TrafficType getTrafficType() { public TrafficType getTrafficType() {
return trafficType; return trafficType;
@ -152,25 +152,25 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
public Integer getRateMbps() { public Integer getRateMbps() {
return rateMbps; return rateMbps;
} }
public Date getCreated() { public Date getCreated() {
return created; return created;
} }
@Override @Override
public boolean isSystemOnly() { public boolean isSystemOnly() {
return systemOnly; return systemOnly;
} }
public Date getRemoved() { public Date getRemoved() {
return removed; return removed;
} }
@Override @Override
public String getTags() { public String getTags() {
return tags; return tags;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@ -186,17 +186,17 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
public void setMulticastRateMbps(Integer multicastRateMbps) { public void setMulticastRateMbps(Integer multicastRateMbps) {
this.multicastRateMbps = multicastRateMbps; this.multicastRateMbps = multicastRateMbps;
} }
@Override @Override
public boolean isDefault() { public boolean isDefault() {
return isDefault; return isDefault;
} }
@Override @Override
public boolean getSpecifyVlan() { public boolean getSpecifyVlan() {
return specifyVlan; return specifyVlan;
} }
@Override @Override
public Availability getAvailability() { public Availability getAvailability() {
return availability; return availability;
@ -205,22 +205,22 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
public void setAvailability(Availability availability) { public void setAvailability(Availability availability) {
this.availability = availability; this.availability = availability;
} }
@Override @Override
public String getUniqueName() { public String getUniqueName() {
return uniqueName; return uniqueName;
} }
@Override @Override
public void setState(State state) { public void setState(State state) {
this.state = state; this.state = state;
} }
@Override @Override
public State getState() { public State getState() {
return state; return state;
} }
@Override @Override
public Network.GuestType getGuestType() { public Network.GuestType getGuestType() {
return guestType; return guestType;
@ -239,7 +239,7 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
public boolean getDedicatedLB() { public boolean getDedicatedLB() {
return dedicatedLB; return dedicatedLB;
} }
public void setDedicatedLb(boolean dedicatedLB) { public void setDedicatedLb(boolean dedicatedLB) {
this.dedicatedLB = dedicatedLB; this.dedicatedLB = dedicatedLB;
} }
@ -248,7 +248,7 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
public boolean getSharedSourceNat() { public boolean getSharedSourceNat() {
return sharedSourceNat; return sharedSourceNat;
} }
public void setSharedSourceNat(boolean sharedSourceNat) { public void setSharedSourceNat(boolean sharedSourceNat) {
this.sharedSourceNat = sharedSourceNat; this.sharedSourceNat = sharedSourceNat;
} }
@ -287,54 +287,57 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
} }
public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault, public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault,
Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb, boolean specifyIpRanges) { Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb,
this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges); boolean specifyIpRanges) {
this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges);
this.dedicatedLB = dedicatedLb; this.dedicatedLB = dedicatedLb;
this.sharedSourceNat = sharedSourceNat; this.sharedSourceNat = sharedSourceNat;
this.redundantRouter = redundantRouter; this.redundantRouter = redundantRouter;
this.elasticIp = elasticIp; this.elasticIp = elasticIp;
this.elasticLb = elasticLb; this.elasticLb = elasticLb;
} }
public NetworkOfferingVO() { public NetworkOfferingVO() {
} }
/** /**
* Network Offering for all system vms. * Network Offering for all system vms.
*
* @param name * @param name
* @param trafficType * @param trafficType
* @param specifyIpRanges TODO * @param specifyIpRanges
* TODO
*/ */
public NetworkOfferingVO(String name, TrafficType trafficType, boolean specifyIpRanges) { public NetworkOfferingVO(String name, TrafficType trafficType, boolean specifyIpRanges) {
this(name, "System Offering for " + name, trafficType, true, false, 0, 0, true, Availability.Required, null, null, true, specifyIpRanges); this(name, "System Offering for " + name, trafficType, true, false, 0, 0, true, Availability.Required, null, null, true, specifyIpRanges);
this.state = State.Enabled; this.state = State.Enabled;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder buf = new StringBuilder("[Network Offering ["); StringBuilder buf = new StringBuilder("[Network Offering [");
return buf.append(id).append("-").append(trafficType).append("-").append(name).append("]").toString(); return buf.append(id).append("-").append(trafficType).append("-").append(name).append("]").toString();
} }
@Override @Override
public String getUuid() { public String getUuid() {
return this.uuid; return this.uuid;
} }
public void setUuid(String uuid) { public void setUuid(String uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
public void setSortKey(int key) { public void setSortKey(int key) {
sortKey = key; sortKey = key;
} }
public int getSortKey() { public int getSortKey() {
return sortKey; return sortKey;
} }
public void setUniqueName(String uniqueName) { public void setUniqueName(String uniqueName) {
this.uniqueName = uniqueName; this.uniqueName = uniqueName;
} }
@Override @Override
@ -343,17 +346,18 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
} }
@Override @Override
public boolean getElasticIp() { public boolean getElasticIp() {
return elasticIp; return elasticIp;
} }
@Override @Override
public boolean getElasticLb() { public boolean getElasticLb() {
return elasticLb; return elasticLb;
} }
@Override @Override
public boolean getSpecifyIpRanges() { public boolean getSpecifyIpRanges() {
return specifyIpRanges; return specifyIpRanges;
} }
} }

View File

@ -33,32 +33,35 @@ import com.cloud.utils.db.GenericDao;
/** /**
* NetworkOfferingDao deals with searches and operations done on the * NetworkOfferingDao deals with searches and operations done on the
* network_offering table. * network_offering table.
* *
*/ */
public interface NetworkOfferingDao extends GenericDao<NetworkOfferingVO, Long> { public interface NetworkOfferingDao extends GenericDao<NetworkOfferingVO, Long> {
/** /**
* Returns the network offering that matches the name. * Returns the network offering that matches the name.
* @param uniqueName name *
* @param uniqueName
* name
* @return NetworkOfferingVO * @return NetworkOfferingVO
*/ */
NetworkOfferingVO findByUniqueName(String uniqueName); NetworkOfferingVO findByUniqueName(String uniqueName);
/** /**
* Persists the system network offering by checking the name. If it * Persists the system network offering by checking the name. If it
* is already there, then it returns the correct one in the database. * is already there, then it returns the correct one in the database.
* If not, then it persists it into the database. * If not, then it persists it into the database.
* *
* @param offering network offering to persist if not in the database. * @param offering
* network offering to persist if not in the database.
* @return NetworkOfferingVO backed by a row in the database * @return NetworkOfferingVO backed by a row in the database
*/ */
NetworkOfferingVO persistDefaultNetworkOffering(NetworkOfferingVO offering); NetworkOfferingVO persistDefaultNetworkOffering(NetworkOfferingVO offering);
List<NetworkOfferingVO> listSystemNetworkOfferings(); List<NetworkOfferingVO> listSystemNetworkOfferings();
List<NetworkOfferingVO> listByAvailability(Availability availability, boolean isSystem); List<NetworkOfferingVO> listByAvailability(Availability availability, boolean isSystem);
List<Long> getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering); List<Long> getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering);
List<NetworkOfferingVO> listByTrafficTypeGuestTypeAndState(NetworkOffering.State state, TrafficType trafficType, Network.GuestType type); List<NetworkOfferingVO> listByTrafficTypeGuestTypeAndState(NetworkOffering.State state, TrafficType trafficType, Network.GuestType type);
} }

View File

@ -21,7 +21,6 @@
*/ */
package com.cloud.offerings.dao; package com.cloud.offerings.dao;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
@ -40,31 +39,32 @@ import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
@Local(value=NetworkOfferingDao.class) @DB(txn=false) @Local(value = NetworkOfferingDao.class)
@DB(txn = false)
public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Long> implements NetworkOfferingDao { public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Long> implements NetworkOfferingDao {
final SearchBuilder<NetworkOfferingVO> NameSearch; final SearchBuilder<NetworkOfferingVO> NameSearch;
final SearchBuilder<NetworkOfferingVO> SystemOfferingSearch; final SearchBuilder<NetworkOfferingVO> SystemOfferingSearch;
final SearchBuilder<NetworkOfferingVO> AvailabilitySearch; final SearchBuilder<NetworkOfferingVO> AvailabilitySearch;
final SearchBuilder<NetworkOfferingVO> AllFieldsSearch; final SearchBuilder<NetworkOfferingVO> AllFieldsSearch;
private final GenericSearchBuilder<NetworkOfferingVO, Long> UpgradeSearch; private final GenericSearchBuilder<NetworkOfferingVO, Long> UpgradeSearch;
protected NetworkOfferingDaoImpl() { protected NetworkOfferingDaoImpl() {
super(); super();
NameSearch = createSearchBuilder(); NameSearch = createSearchBuilder();
NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ);
NameSearch.and("uniqueName", NameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ); NameSearch.and("uniqueName", NameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ);
NameSearch.done(); NameSearch.done();
SystemOfferingSearch = createSearchBuilder(); SystemOfferingSearch = createSearchBuilder();
SystemOfferingSearch.and("system", SystemOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ); SystemOfferingSearch.and("system", SystemOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
SystemOfferingSearch.done(); SystemOfferingSearch.done();
AvailabilitySearch = createSearchBuilder(); AvailabilitySearch = createSearchBuilder();
AvailabilitySearch.and("availability", AvailabilitySearch.entity().getAvailability(), SearchCriteria.Op.EQ); AvailabilitySearch.and("availability", AvailabilitySearch.entity().getAvailability(), SearchCriteria.Op.EQ);
AvailabilitySearch.and("isSystem", AvailabilitySearch.entity().isSystemOnly(), SearchCriteria.Op.EQ); AvailabilitySearch.and("isSystem", AvailabilitySearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
AvailabilitySearch.done(); AvailabilitySearch.done();
AllFieldsSearch = createSearchBuilder(); AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("trafficType", AllFieldsSearch.entity().getTrafficType(), SearchCriteria.Op.EQ); AllFieldsSearch.and("trafficType", AllFieldsSearch.entity().getTrafficType(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("guestType", AllFieldsSearch.entity().getGuestType(), SearchCriteria.Op.EQ); AllFieldsSearch.and("guestType", AllFieldsSearch.entity().getGuestType(), SearchCriteria.Op.EQ);
@ -81,17 +81,17 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
UpgradeSearch.and("state", UpgradeSearch.entity().getState(), Op.EQ); UpgradeSearch.and("state", UpgradeSearch.entity().getState(), Op.EQ);
UpgradeSearch.done(); UpgradeSearch.done();
} }
@Override @Override
public NetworkOfferingVO findByUniqueName(String uniqueName) { public NetworkOfferingVO findByUniqueName(String uniqueName) {
SearchCriteria<NetworkOfferingVO> sc = NameSearch.create(); SearchCriteria<NetworkOfferingVO> sc = NameSearch.create();
sc.setParameters("uniqueName", uniqueName); sc.setParameters("uniqueName", uniqueName);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public NetworkOfferingVO persistDefaultNetworkOffering(NetworkOfferingVO offering) { public NetworkOfferingVO persistDefaultNetworkOffering(NetworkOfferingVO offering) {
assert offering.getUniqueName() != null : "how are you going to find this later if you don't set it?"; assert offering.getUniqueName() != null : "how are you going to find this later if you don't set it?";
@ -107,14 +107,14 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
return findByUniqueName(offering.getName()); return findByUniqueName(offering.getName());
} }
} }
@Override @Override
public List<NetworkOfferingVO> listSystemNetworkOfferings() { public List<NetworkOfferingVO> listSystemNetworkOfferings() {
SearchCriteria<NetworkOfferingVO> sc = SystemOfferingSearch.create(); SearchCriteria<NetworkOfferingVO> sc = SystemOfferingSearch.create();
sc.setParameters("system", true); sc.setParameters("system", true);
return this.listIncludingRemovedBy(sc, null); return this.listIncludingRemovedBy(sc, null);
} }
@Override @Override
public List<NetworkOfferingVO> listByAvailability(Availability availability, boolean isSystem) { public List<NetworkOfferingVO> listByAvailability(Availability availability, boolean isSystem) {
SearchCriteria<NetworkOfferingVO> sc = AvailabilitySearch.create(); SearchCriteria<NetworkOfferingVO> sc = AvailabilitySearch.create();
@ -122,11 +122,12 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
sc.setParameters("isSystem", isSystem); sc.setParameters("isSystem", isSystem);
return listBy(sc, null); return listBy(sc, null);
} }
@Override @DB @Override
public boolean remove(Long networkOfferingId){ @DB
Transaction txn = Transaction.currentTxn(); public boolean remove(Long networkOfferingId) {
txn.start(); Transaction txn = Transaction.currentTxn();
txn.start();
NetworkOfferingVO offering = findById(networkOfferingId); NetworkOfferingVO offering = findById(networkOfferingId);
offering.setUniqueName(null); offering.setUniqueName(null);
update(networkOfferingId, offering); update(networkOfferingId, offering);
@ -134,27 +135,27 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
txn.commit(); txn.commit();
return result; return result;
} }
@Override @Override
public List<Long> getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering) { public List<Long> getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering) {
SearchCriteria<Long> sc = UpgradeSearch.create(); SearchCriteria<Long> sc = UpgradeSearch.create();
//exclude original offering // exclude original offering
sc.addAnd("id", SearchCriteria.Op.NEQ, originalOffering.getId()); sc.addAnd("id", SearchCriteria.Op.NEQ, originalOffering.getId());
//list only non-system offerings // list only non-system offerings
sc.addAnd("systemOnly", SearchCriteria.Op.EQ, false); sc.addAnd("systemOnly", SearchCriteria.Op.EQ, false);
//Type of the network should be the same // Type of the network should be the same
sc.addAnd("guestType", SearchCriteria.Op.EQ, originalOffering.getGuestType()); sc.addAnd("guestType", SearchCriteria.Op.EQ, originalOffering.getGuestType());
//Traffic types should be the same // Traffic types should be the same
sc.addAnd("trafficType", SearchCriteria.Op.EQ, originalOffering.getTrafficType()); sc.addAnd("trafficType", SearchCriteria.Op.EQ, originalOffering.getTrafficType());
sc.addAnd("state", SearchCriteria.Op.EQ, NetworkOffering.State.Enabled); sc.addAnd("state", SearchCriteria.Op.EQ, NetworkOffering.State.Enabled);
return customSearch(sc, null); return customSearch(sc, null);
} }
@Override @Override
public List<NetworkOfferingVO> listByTrafficTypeGuestTypeAndState(NetworkOffering.State state, TrafficType trafficType, Network.GuestType type) { public List<NetworkOfferingVO> listByTrafficTypeGuestTypeAndState(NetworkOffering.State state, TrafficType trafficType, Network.GuestType type) {
SearchCriteria<NetworkOfferingVO> sc = AllFieldsSearch.create(); SearchCriteria<NetworkOfferingVO> sc = AllFieldsSearch.create();
@ -163,4 +164,5 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
sc.setParameters("state", state); sc.setParameters("state", state);
return listBy(sc, null); return listBy(sc, null);
} }
} }

View File

@ -79,10 +79,10 @@ import com.cloud.vm.dao.VMInstanceDao;
import edu.emory.mathcs.backport.java.util.Arrays; import edu.emory.mathcs.backport.java.util.Arrays;
@Local(value = { ResourceLimitService.class}) @Local(value = { ResourceLimitService.class })
public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
public static final Logger s_logger = Logger.getLogger(ResourceLimitManagerImpl.class); public static final Logger s_logger = Logger.getLogger(ResourceLimitManagerImpl.class);
private String _name; private String _name;
@Inject @Inject
private DomainDao _domainDao; private DomainDao _domainDao;
@ -116,14 +116,13 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
private ProjectDao _projectDao; private ProjectDao _projectDao;
@Inject @Inject
private ProjectAccountDao _projectAccountDao; private ProjectAccountDao _projectAccountDao;
protected SearchBuilder<ResourceCountVO> ResourceCountSearch; protected SearchBuilder<ResourceCountVO> ResourceCountSearch;
ScheduledExecutorService _rcExecutor; ScheduledExecutorService _rcExecutor;
long _resourceCountCheckInterval=0; long _resourceCountCheckInterval = 0;
Map<ResourceType, Long> accountResourceLimitMap = new EnumMap<ResourceType, Long>(ResourceType.class); Map<ResourceType, Long> accountResourceLimitMap = new EnumMap<ResourceType, Long>(ResourceType.class);
Map<ResourceType, Long> projectResourceLimitMap = new EnumMap<ResourceType, Long>(ResourceType.class); Map<ResourceType, Long> projectResourceLimitMap = new EnumMap<ResourceType, Long>(ResourceType.class);
@Override @Override
public String getName() { public String getName() {
return _name; return _name;
@ -131,8 +130,8 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
@Override @Override
public boolean start() { public boolean start() {
if (_resourceCountCheckInterval > 0){ if (_resourceCountCheckInterval > 0) {
_rcExecutor.scheduleAtFixedRate(new ResourceCountCheckTask(), _resourceCountCheckInterval, _resourceCountCheckInterval, TimeUnit.SECONDS); _rcExecutor.scheduleAtFixedRate(new ResourceCountCheckTask(), _resourceCountCheckInterval, _resourceCountCheckInterval, TimeUnit.SECONDS);
} }
return true; return true;
} }
@ -141,11 +140,11 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
public boolean stop() { public boolean stop() {
return true; return true;
} }
@Override @Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
ResourceCountSearch = _resourceCountDao.createSearchBuilder(); ResourceCountSearch = _resourceCountDao.createSearchBuilder();
ResourceCountSearch.and("id", ResourceCountSearch.entity().getId(), SearchCriteria.Op.IN); ResourceCountSearch.and("id", ResourceCountSearch.entity().getId(), SearchCriteria.Op.IN);
ResourceCountSearch.and("accountId", ResourceCountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); ResourceCountSearch.and("accountId", ResourceCountSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
@ -153,28 +152,28 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
ResourceCountSearch.done(); ResourceCountSearch.done();
_resourceCountCheckInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ResourceCountCheckInterval.key()), 0); _resourceCountCheckInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ResourceCountCheckInterval.key()), 0);
if (_resourceCountCheckInterval > 0){ if (_resourceCountCheckInterval > 0) {
_rcExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ResourceCountChecker")); _rcExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ResourceCountChecker"));
} }
projectResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectPublicIPs.key()))); projectResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectPublicIPs.key())));
projectResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectSnapshots.key()))); projectResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectSnapshots.key())));
projectResourceLimitMap.put(Resource.ResourceType.template, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectTemplates.key()))); projectResourceLimitMap.put(Resource.ResourceType.template, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectTemplates.key())));
projectResourceLimitMap.put(Resource.ResourceType.user_vm, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectUserVms.key()))); projectResourceLimitMap.put(Resource.ResourceType.user_vm, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectUserVms.key())));
projectResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectVolumes.key()))); projectResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectVolumes.key())));
accountResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountPublicIPs.key()))); accountResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountPublicIPs.key())));
accountResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSnapshots.key()))); accountResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSnapshots.key())));
accountResourceLimitMap.put(Resource.ResourceType.template, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountTemplates.key()))); accountResourceLimitMap.put(Resource.ResourceType.template, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountTemplates.key())));
accountResourceLimitMap.put(Resource.ResourceType.user_vm, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountUserVms.key()))); accountResourceLimitMap.put(Resource.ResourceType.user_vm, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountUserVms.key())));
accountResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVolumes.key()))); accountResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVolumes.key())));
return true; return true;
} }
@Override @Override
public void incrementResourceCount(long accountId, ResourceType type, Long... delta) { public void incrementResourceCount(long accountId, ResourceType type, Long... delta) {
//don't upgrade resource count for system account // don't upgrade resource count for system account
if (accountId == Account.ACCOUNT_ID_SYSTEM) { if (accountId == Account.ACCOUNT_ID_SYSTEM) {
s_logger.trace("Not incrementing resource count for system accounts, returning"); s_logger.trace("Not incrementing resource count for system accounts, returning");
return; return;
@ -182,46 +181,46 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
long numToIncrement = (delta.length == 0) ? 1 : delta[0].longValue(); long numToIncrement = (delta.length == 0) ? 1 : delta[0].longValue();
if (!updateResourceCountForAccount(accountId, type, true, numToIncrement)) { if (!updateResourceCountForAccount(accountId, type, true, numToIncrement)) {
//we should fail the operation (resource creation) when failed to update the resource count // we should fail the operation (resource creation) when failed to update the resource count
throw new CloudRuntimeException("Failed to increment resource count of type " + type + " for account id=" + accountId); throw new CloudRuntimeException("Failed to increment resource count of type " + type + " for account id=" + accountId);
} }
} }
@Override @Override
public void decrementResourceCount(long accountId, ResourceType type, Long... delta) { public void decrementResourceCount(long accountId, ResourceType type, Long... delta) {
//don't upgrade resource count for system account // don't upgrade resource count for system account
if (accountId == Account.ACCOUNT_ID_SYSTEM) { if (accountId == Account.ACCOUNT_ID_SYSTEM) {
s_logger.trace("Not decrementing resource count for system accounts, returning"); s_logger.trace("Not decrementing resource count for system accounts, returning");
return; return;
} }
long numToDecrement = (delta.length == 0) ? 1 : delta[0].longValue(); long numToDecrement = (delta.length == 0) ? 1 : delta[0].longValue();
if (!updateResourceCountForAccount(accountId, type, false, numToDecrement)) { if (!updateResourceCountForAccount(accountId, type, false, numToDecrement)) {
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, "Failed to decrement resource count of type " + type + " for account id=" + accountId, _alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, "Failed to decrement resource count of type " + type + " for account id=" + accountId,
"Failed to decrement resource count of type " + type + " for account id=" + accountId + "; use updateResourceCount API to recalculate/fix the problem"); "Failed to decrement resource count of type " + type + " for account id=" + accountId + "; use updateResourceCount API to recalculate/fix the problem");
} }
} }
@Override @Override
public long findCorrectResourceLimitForAccount(Account account, ResourceType type) { public long findCorrectResourceLimitForAccount(Account account, ResourceType type) {
long max = Resource.RESOURCE_UNLIMITED; //if resource limit is not found, then we treat it as unlimited long max = Resource.RESOURCE_UNLIMITED; // if resource limit is not found, then we treat it as unlimited
ResourceLimitVO limit = _resourceLimitDao.findByOwnerIdAndType(account.getId(), ResourceOwnerType.Account, type); ResourceLimitVO limit = _resourceLimitDao.findByOwnerIdAndType(account.getId(), ResourceOwnerType.Account, type);
// Check if limit is configured for account // Check if limit is configured for account
if (limit != null) { if (limit != null) {
max = limit.getMax().longValue(); max = limit.getMax().longValue();
} else { } else {
// If the account has an no limit set, then return global default account limits // If the account has an no limit set, then return global default account limits
Long value = null; Long value = null;
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
value = projectResourceLimitMap.get(type); value = projectResourceLimitMap.get(type);
} else { } else {
value = accountResourceLimitMap.get(type); value = accountResourceLimitMap.get(type);
} }
if (value != null){ if (value != null) {
return value; return value;
} }
} }
return max; return max;
@ -230,9 +229,9 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
@Override @Override
public long findCorrectResourceLimitForDomain(Domain domain, ResourceType type) { public long findCorrectResourceLimitForDomain(Domain domain, ResourceType type) {
long max = Resource.RESOURCE_UNLIMITED; long max = Resource.RESOURCE_UNLIMITED;
//no limits on ROOT domain // no limits on ROOT domain
if(domain.getId() == Domain.ROOT_DOMAIN){ if (domain.getId() == Domain.ROOT_DOMAIN) {
return Resource.RESOURCE_UNLIMITED; return Resource.RESOURCE_UNLIMITED;
} }
// Check account // Check account
@ -244,8 +243,8 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
// check domain hierarchy // check domain hierarchy
Long domainId = domain.getParent(); Long domainId = domain.getParent();
while ((domainId != null) && (limit == null)) { while ((domainId != null) && (limit == null)) {
if(domainId == Domain.ROOT_DOMAIN){ if (domainId == Domain.ROOT_DOMAIN) {
return Resource.RESOURCE_UNLIMITED; return Resource.RESOURCE_UNLIMITED;
} }
limit = _resourceLimitDao.findByOwnerIdAndType(domainId, ResourceOwnerType.Domain, type); limit = _resourceLimitDao.findByOwnerIdAndType(domainId, ResourceOwnerType.Domain, type);
@ -261,8 +260,9 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
return max; return max;
} }
@Override @DB @Override
public void checkResourceLimit(Account account, ResourceType type, long... count) throws ResourceAllocationException{ @DB
public void checkResourceLimit(Account account, ResourceType type, long... count) throws ResourceAllocationException {
long numResources = ((count.length == 0) ? 1 : count[0]); long numResources = ((count.length == 0) ? 1 : count[0]);
Project project = null; Project project = null;
@ -270,15 +270,15 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
if (_accountMgr.isAdmin(account.getType())) { if (_accountMgr.isAdmin(account.getType())) {
return; return;
} }
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
project = _projectDao.findByProjectAccountId(account.getId()); project = _projectDao.findByProjectAccountId(account.getId());
} }
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
try { try {
//Lock all rows first so nobody else can read it // Lock all rows first so nobody else can read it
Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(account.getId(), ResourceOwnerType.Account, type); Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(account.getId(), ResourceOwnerType.Account, type);
SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create(); SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
sc.setParameters("id", rowIdsToLock.toArray()); sc.setParameters("id", rowIdsToLock.toArray());
@ -289,10 +289,10 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
long potentialCount = _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type) + numResources; long potentialCount = _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type) + numResources;
if (accountLimit != Resource.RESOURCE_UNLIMITED && potentialCount > accountLimit) { if (accountLimit != Resource.RESOURCE_UNLIMITED && potentialCount > accountLimit) {
String message = "Maximum number of resources of type '" + type + "' for account name=" + account.getAccountName() String message = "Maximum number of resources of type '" + type + "' for account name=" + account.getAccountName()
+ " in domain id=" + account.getDomainId() + " has been exceeded."; + " in domain id=" + account.getDomainId() + " has been exceeded.";
if (project != null) { if (project != null) {
message = "Maximum number of resources of type '" + type + "' for project name=" + project.getName() message = "Maximum number of resources of type '" + type + "' for project name=" + project.getName()
+ " in domain id=" + account.getDomainId() + " has been exceeded."; + " in domain id=" + account.getDomainId() + " has been exceeded.";
} }
throw new ResourceAllocationException(message, type); throw new ResourceAllocationException(message, type);
} }
@ -307,8 +307,8 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
while (domainId != null) { while (domainId != null) {
DomainVO domain = _domainDao.findById(domainId); DomainVO domain = _domainDao.findById(domainId);
//no limit check if it is ROOT domain // no limit check if it is ROOT domain
if(domainId != Domain.ROOT_DOMAIN){ if (domainId != Domain.ROOT_DOMAIN) {
ResourceLimitVO domainLimit = _resourceLimitDao.findByOwnerIdAndType(domainId, ResourceOwnerType.Domain, type); ResourceLimitVO domainLimit = _resourceLimitDao.findByOwnerIdAndType(domainId, ResourceOwnerType.Domain, type);
if (domainLimit != null && domainLimit.getMax().longValue() != Resource.RESOURCE_UNLIMITED) { if (domainLimit != null && domainLimit.getMax().longValue() != Resource.RESOURCE_UNLIMITED) {
long domainCount = _resourceCountDao.getResourceCount(domainId, ResourceOwnerType.Domain, type); long domainCount = _resourceCountDao.getResourceCount(domainId, ResourceOwnerType.Domain, type);
@ -323,151 +323,151 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
txn.commit(); txn.commit();
} }
} }
@Override @Override
public List<ResourceLimitVO> searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal) { public List<ResourceLimitVO> searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
List<ResourceLimitVO> limits = new ArrayList<ResourceLimitVO>(); List<ResourceLimitVO> limits = new ArrayList<ResourceLimitVO>();
boolean isAccount = true; boolean isAccount = true;
if (!_accountMgr.isAdmin(caller.getType())) {
accountId = caller.getId();
domainId = null;
} else {
if (domainId != null) {
//verify domain information and permissions
Domain domain = _domainDao.findById(domainId);
if (domain == null) {
//return empty set
return limits;
}
_accountMgr.checkAccess(caller, domain);
if (accountId != null) {
//Verify account information and permissions
Account account = _accountDao.findById(accountId);
if (account == null) {
//return empty set
return limits;
}
_accountMgr.checkAccess(caller, null, true, account);
domainId = null;
}
}
}
// Map resource type
ResourceType resourceType = null;
if (type != null) {
try {
resourceType = ResourceType.values()[type];
} catch (ArrayIndexOutOfBoundsException e) {
throw new InvalidParameterValueException("Please specify a valid resource type.");
}
}
//If id is passed in, get the record and return it if permission check has passed if (!_accountMgr.isAdmin(caller.getType())) {
if (id != null) { accountId = caller.getId();
ResourceLimitVO vo = _resourceLimitDao.findById(id); domainId = null;
if (vo.getAccountId() != null) { } else {
_accountMgr.checkAccess(caller, null, true, _accountDao.findById(vo.getAccountId())); if (domainId != null) {
limits.add(vo); // verify domain information and permissions
} else if (vo.getDomainId() != null) { Domain domain = _domainDao.findById(domainId);
_accountMgr.checkAccess(caller, _domainDao.findById(vo.getDomainId())); if (domain == null) {
limits.add(vo); // return empty set
} return limits;
}
return limits;
}
//If account is not specified, default it to caller account
if (accountId == null) {
if (domainId == null) {
accountId = caller.getId();
isAccount = true;
} else {
isAccount = false;
}
} else {
isAccount = true;
}
SearchBuilder<ResourceLimitVO> sb = _resourceLimitDao.createSearchBuilder();
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
SearchCriteria<ResourceLimitVO> sc = sb.create(); _accountMgr.checkAccess(caller, domain);
Filter filter = new Filter(ResourceLimitVO.class, "id", true, startIndex, pageSizeVal);
if (accountId != null) {
if (accountId != null) { // Verify account information and permissions
sc.setParameters("accountId", accountId); Account account = _accountDao.findById(accountId);
} if (account == null) {
// return empty set
if (domainId != null) { return limits;
sc.setParameters("domainId", domainId); }
sc.setParameters("accountId", (Object[])null);
} _accountMgr.checkAccess(caller, null, true, account);
domainId = null;
if (resourceType != null) { }
sc.setParameters("type", resourceType); }
} }
List<ResourceLimitVO> foundLimits = _resourceLimitDao.search(sc, filter); // Map resource type
ResourceType resourceType = null;
if (resourceType != null) { if (type != null) {
if (foundLimits.isEmpty()) { try {
if (isAccount) { resourceType = ResourceType.values()[type];
limits.add(new ResourceLimitVO(resourceType, findCorrectResourceLimitForAccount(_accountMgr.getAccount(accountId), resourceType), accountId, ResourceOwnerType.Account)); } catch (ArrayIndexOutOfBoundsException e) {
} else { throw new InvalidParameterValueException("Please specify a valid resource type.");
limits.add(new ResourceLimitVO(resourceType, findCorrectResourceLimitForDomain(_domainDao.findById(domainId), resourceType), domainId, ResourceOwnerType.Domain)); }
} }
} else {
limits.addAll(foundLimits); // If id is passed in, get the record and return it if permission check has passed
} if (id != null) {
} else { ResourceLimitVO vo = _resourceLimitDao.findById(id);
limits.addAll(foundLimits); if (vo.getAccountId() != null) {
_accountMgr.checkAccess(caller, null, true, _accountDao.findById(vo.getAccountId()));
//see if any limits are missing from the table, and if yes - get it from the config table and add limits.add(vo);
ResourceType[] resourceTypes = ResourceCount.ResourceType.values(); } else if (vo.getDomainId() != null) {
if (foundLimits.size() != resourceTypes.length) { _accountMgr.checkAccess(caller, _domainDao.findById(vo.getDomainId()));
List<String> accountLimitStr = new ArrayList<String>(); limits.add(vo);
List<String> domainLimitStr = new ArrayList<String>(); }
for (ResourceLimitVO foundLimit : foundLimits) {
if (foundLimit.getAccountId() != null) { return limits;
accountLimitStr.add(foundLimit.getType().toString()); }
} else {
domainLimitStr.add(foundLimit.getType().toString()); // If account is not specified, default it to caller account
} if (accountId == null) {
} if (domainId == null) {
accountId = caller.getId();
//get default from config values isAccount = true;
if (isAccount) { } else {
if (accountLimitStr.size() < resourceTypes.length) { isAccount = false;
for (ResourceType rt : resourceTypes) { }
if (!accountLimitStr.contains(rt.toString()) && rt.supportsOwner(ResourceOwnerType.Account)) { } else {
limits.add(new ResourceLimitVO(rt, findCorrectResourceLimitForAccount(_accountMgr.getAccount(accountId), rt), accountId, ResourceOwnerType.Account)); isAccount = true;
} }
}
} SearchBuilder<ResourceLimitVO> sb = _resourceLimitDao.createSearchBuilder();
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
} else { sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
if (domainLimitStr.size() < resourceTypes.length) { sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
for (ResourceType rt : resourceTypes) {
if (!domainLimitStr.contains(rt.toString()) && rt.supportsOwner(ResourceOwnerType.Domain)) { SearchCriteria<ResourceLimitVO> sc = sb.create();
limits.add(new ResourceLimitVO(rt, findCorrectResourceLimitForDomain(_domainDao.findById(domainId), rt), domainId, ResourceOwnerType.Domain)); Filter filter = new Filter(ResourceLimitVO.class, "id", true, startIndex, pageSizeVal);
}
} if (accountId != null) {
} sc.setParameters("accountId", accountId);
} }
}
} if (domainId != null) {
sc.setParameters("domainId", domainId);
return limits; sc.setParameters("accountId", (Object[]) null);
}
if (resourceType != null) {
sc.setParameters("type", resourceType);
}
List<ResourceLimitVO> foundLimits = _resourceLimitDao.search(sc, filter);
if (resourceType != null) {
if (foundLimits.isEmpty()) {
if (isAccount) {
limits.add(new ResourceLimitVO(resourceType, findCorrectResourceLimitForAccount(_accountMgr.getAccount(accountId), resourceType), accountId, ResourceOwnerType.Account));
} else {
limits.add(new ResourceLimitVO(resourceType, findCorrectResourceLimitForDomain(_domainDao.findById(domainId), resourceType), domainId, ResourceOwnerType.Domain));
}
} else {
limits.addAll(foundLimits);
}
} else {
limits.addAll(foundLimits);
// see if any limits are missing from the table, and if yes - get it from the config table and add
ResourceType[] resourceTypes = ResourceCount.ResourceType.values();
if (foundLimits.size() != resourceTypes.length) {
List<String> accountLimitStr = new ArrayList<String>();
List<String> domainLimitStr = new ArrayList<String>();
for (ResourceLimitVO foundLimit : foundLimits) {
if (foundLimit.getAccountId() != null) {
accountLimitStr.add(foundLimit.getType().toString());
} else {
domainLimitStr.add(foundLimit.getType().toString());
}
}
// get default from config values
if (isAccount) {
if (accountLimitStr.size() < resourceTypes.length) {
for (ResourceType rt : resourceTypes) {
if (!accountLimitStr.contains(rt.toString()) && rt.supportsOwner(ResourceOwnerType.Account)) {
limits.add(new ResourceLimitVO(rt, findCorrectResourceLimitForAccount(_accountMgr.getAccount(accountId), rt), accountId, ResourceOwnerType.Account));
}
}
}
} else {
if (domainLimitStr.size() < resourceTypes.length) {
for (ResourceType rt : resourceTypes) {
if (!domainLimitStr.contains(rt.toString()) && rt.supportsOwner(ResourceOwnerType.Domain)) {
limits.add(new ResourceLimitVO(rt, findCorrectResourceLimitForDomain(_domainDao.findById(domainId), rt), domainId, ResourceOwnerType.Domain));
}
}
}
}
}
}
return limits;
} }
@Override @Override
public ResourceLimitVO updateResourceLimit(Long accountId, Long domainId, Integer typeId, Long max) { public ResourceLimitVO updateResourceLimit(Long accountId, Long domainId, Integer typeId, Long max) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
@ -490,27 +490,27 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
throw new InvalidParameterValueException("Please specify valid resource type"); throw new InvalidParameterValueException("Please specify valid resource type");
} }
} }
ResourceOwnerType ownerType = null; ResourceOwnerType ownerType = null;
Long ownerId = null; Long ownerId = null;
if (accountId != null) { if (accountId != null) {
Account account = _entityMgr.findById(Account.class, accountId); Account account = _entityMgr.findById(Account.class, accountId);
if (account.getType() == Account.ACCOUNT_ID_SYSTEM) { if (account.getType() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException("Can't update system account"); throw new InvalidParameterValueException("Can't update system account");
} }
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
_accountMgr.checkAccess(caller, AccessType.ModifyProject, true, account); _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, account);
} else { } else {
_accountMgr.checkAccess(caller, null, true, account); _accountMgr.checkAccess(caller, null, true, account);
} }
ownerType = ResourceOwnerType.Account; ownerType = ResourceOwnerType.Account;
ownerId = accountId; ownerId = accountId;
} else if (domainId != null) { } else if (domainId != null) {
Domain domain = _entityMgr.findById(Domain.class, domainId); Domain domain = _entityMgr.findById(Domain.class, domainId);
_accountMgr.checkAccess(caller, domain); _accountMgr.checkAccess(caller, domain);
if (Domain.ROOT_DOMAIN == domainId.longValue()) { if (Domain.ROOT_DOMAIN == domainId.longValue()) {
@ -518,7 +518,6 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
throw new PermissionDeniedException("Cannot update resource limit for ROOT domain " + domainId + ", permission denied"); throw new PermissionDeniedException("Cannot update resource limit for ROOT domain " + domainId + ", permission denied");
} }
if ((caller.getDomainId() == domainId.longValue()) && caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { if ((caller.getDomainId() == domainId.longValue()) && caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// if the admin is trying to update their own domain, disallow... // if the admin is trying to update their own domain, disallow...
throw new PermissionDeniedException("Unable to update resource limit for domain " + domainId + ", permission denied"); throw new PermissionDeniedException("Unable to update resource limit for domain " + domainId + ", permission denied");
@ -534,8 +533,8 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
} }
ownerType = ResourceOwnerType.Domain; ownerType = ResourceOwnerType.Domain;
ownerId = domainId; ownerId = domainId;
} }
if (ownerId == null) { if (ownerId == null) {
throw new InvalidParameterValueException("AccountId or domainId have to be specified in order to update resource limit"); throw new InvalidParameterValueException("AccountId or domainId have to be specified in order to update resource limit");
} }
@ -551,9 +550,9 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
} }
@Override @Override
public List<ResourceCountVO> recalculateResourceCount(Long accountId, Long domainId, Integer typeId) throws InvalidParameterValueException, CloudRuntimeException, PermissionDeniedException{ public List<ResourceCountVO> recalculateResourceCount(Long accountId, Long domainId, Integer typeId) throws InvalidParameterValueException, CloudRuntimeException, PermissionDeniedException {
Account callerAccount = UserContext.current().getCaller(); Account callerAccount = UserContext.current().getCaller();
long count=0; long count = 0;
List<ResourceCountVO> counts = new ArrayList<ResourceCountVO>(); List<ResourceCountVO> counts = new ArrayList<ResourceCountVO>();
List<ResourceType> resourceTypes = new ArrayList<ResourceType>(); List<ResourceType> resourceTypes = new ArrayList<ResourceType>();
@ -575,7 +574,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
throw new InvalidParameterValueException("Please specify a valid domain ID."); throw new InvalidParameterValueException("Please specify a valid domain ID.");
} }
_accountMgr.checkAccess(callerAccount, domain); _accountMgr.checkAccess(callerAccount, domain);
if (resourceType != null) { if (resourceType != null) {
resourceTypes.add(resourceType); resourceTypes.add(resourceType);
} else { } else {
@ -588,39 +587,39 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
count = recalculateAccountResourceCount(accountId, type); count = recalculateAccountResourceCount(accountId, type);
counts.add(new ResourceCountVO(type, count, accountId, ResourceOwnerType.Account)); counts.add(new ResourceCountVO(type, count, accountId, ResourceOwnerType.Account));
} }
} else { } else {
if (type.supportsOwner(ResourceOwnerType.Domain)) { if (type.supportsOwner(ResourceOwnerType.Domain)) {
count = recalculateDomainResourceCount(domainId, type); count = recalculateDomainResourceCount(domainId, type);
counts.add(new ResourceCountVO(type, count, domainId, ResourceOwnerType.Domain)); counts.add(new ResourceCountVO(type, count, domainId, ResourceOwnerType.Domain));
} }
} }
} }
return counts; return counts;
} }
@DB @DB
protected boolean updateResourceCountForAccount(long accountId, ResourceType type, boolean increment, long delta) { protected boolean updateResourceCountForAccount(long accountId, ResourceType type, boolean increment, long delta) {
boolean result = true; boolean result = true;
try { try {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
Set<Long> rowsToLock = _resourceCountDao.listAllRowsToUpdate(accountId, ResourceOwnerType.Account, type); Set<Long> rowsToLock = _resourceCountDao.listAllRowsToUpdate(accountId, ResourceOwnerType.Account, type);
//Lock rows first // Lock rows first
SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create(); SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
sc.setParameters("id", rowsToLock.toArray()); sc.setParameters("id", rowsToLock.toArray());
List<ResourceCountVO> rowsToUpdate = _resourceCountDao.lockRows(sc, null, true); List<ResourceCountVO> rowsToUpdate = _resourceCountDao.lockRows(sc, null, true);
for (ResourceCountVO rowToUpdate : rowsToUpdate) { for (ResourceCountVO rowToUpdate : rowsToUpdate) {
if (!_resourceCountDao.updateById(rowToUpdate.getId(), increment, delta)) { if (!_resourceCountDao.updateById(rowToUpdate.getId(), increment, delta)) {
s_logger.trace("Unable to update resource count for the row " + rowToUpdate); s_logger.trace("Unable to update resource count for the row " + rowToUpdate);
result = false; result = false;
} }
} }
txn.commit(); txn.commit();
} catch (Exception ex) { } catch (Exception ex) {
s_logger.error("Failed to update resource count for account id=" + accountId); s_logger.error("Failed to update resource count for account id=" + accountId);
@ -628,16 +627,16 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
} }
return result; return result;
} }
@DB @DB
protected long recalculateDomainResourceCount(long domainId, ResourceType type) { protected long recalculateDomainResourceCount(long domainId, ResourceType type) {
long newCount=0; long newCount = 0;
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
try { try {
//Lock all rows first so nobody else can read it // Lock all rows first so nobody else can read it
Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(domainId, ResourceOwnerType.Domain, type); Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(domainId, ResourceOwnerType.Domain, type);
SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create(); SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
sc.setParameters("id", rowIdsToLock.toArray()); sc.setParameters("id", rowIdsToLock.toArray());
@ -649,18 +648,18 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
List<DomainVO> domainChildren = _domainDao.findImmediateChildrenForParent(domainId); List<DomainVO> domainChildren = _domainDao.findImmediateChildrenForParent(domainId);
// for each child domain update the resource count // for each child domain update the resource count
if (type.supportsOwner(ResourceOwnerType.Domain)) { if (type.supportsOwner(ResourceOwnerType.Domain)) {
//calculate project count here // calculate project count here
if (type == ResourceType.project) { if (type == ResourceType.project) {
newCount = newCount + _projectDao.countProjectsForDomain(domainId); newCount = newCount + _projectDao.countProjectsForDomain(domainId);
} }
for (DomainVO domainChild : domainChildren) { for (DomainVO domainChild : domainChildren) {
long domainCount = recalculateDomainResourceCount(domainChild.getId(), type); long domainCount = recalculateDomainResourceCount(domainChild.getId(), type);
newCount = newCount + domainCount; // add the child domain count to parent domain count newCount = newCount + domainCount; // add the child domain count to parent domain count
} }
} }
if (type.supportsOwner(ResourceOwnerType.Account)) { if (type.supportsOwner(ResourceOwnerType.Account)) {
List<AccountVO> accounts = _accountDao.findActiveAccountsForDomain(domainId); List<AccountVO> accounts = _accountDao.findActiveAccountsForDomain(domainId);
for (AccountVO account : accounts) { for (AccountVO account : accounts) {
@ -671,26 +670,26 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
_resourceCountDao.setResourceCount(domainId, ResourceOwnerType.Domain, type, newCount); _resourceCountDao.setResourceCount(domainId, ResourceOwnerType.Domain, type, newCount);
if (oldCount != newCount) { if (oldCount != newCount) {
s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " + s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " +
newCount + ") for type " + type + " for domain ID " + domainId + " is fixed during resource count recalculation." ); newCount + ") for type " + type + " for domain ID " + domainId + " is fixed during resource count recalculation.");
} }
} catch (Exception e) { } catch (Exception e) {
throw new CloudRuntimeException("Failed to update resource count for domain with Id " + domainId); throw new CloudRuntimeException("Failed to update resource count for domain with Id " + domainId);
} finally { } finally {
txn.commit(); txn.commit();
} }
return newCount; return newCount;
} }
@DB @DB
protected long recalculateAccountResourceCount(long accountId, ResourceType type) { protected long recalculateAccountResourceCount(long accountId, ResourceType type) {
Long newCount=null; Long newCount = null;
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
// this lock guards against the updates to user_vm, volume, snapshot, public _ip and template table // this lock guards against the updates to user_vm, volume, snapshot, public _ip and template table
// as any resource creation precedes with the resourceLimitExceeded check which needs this lock too // as any resource creation precedes with the resourceLimitExceeded check which needs this lock too
SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create(); SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
sc.setParameters("accountId", accountId); sc.setParameters("accountId", accountId);
@ -704,7 +703,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
} else if (type == Resource.ResourceType.volume) { } else if (type == Resource.ResourceType.volume) {
newCount = _volumeDao.countAllocatedVolumesForAccount(accountId); newCount = _volumeDao.countAllocatedVolumesForAccount(accountId);
long virtualRouterCount = _vmDao.countAllocatedVirtualRoutersForAccount(accountId); long virtualRouterCount = _vmDao.countAllocatedVirtualRoutersForAccount(accountId);
newCount = newCount - virtualRouterCount; // don't count the volumes of virtual router newCount = newCount - virtualRouterCount; // don't count the volumes of virtual router
} else if (type == Resource.ResourceType.snapshot) { } else if (type == Resource.ResourceType.snapshot) {
newCount = _snapshotDao.countSnapshotsForAccount(accountId); newCount = _snapshotDao.countSnapshotsForAccount(accountId);
} else if (type == Resource.ResourceType.public_ip) { } else if (type == Resource.ResourceType.public_ip) {
@ -712,29 +711,29 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
} else if (type == Resource.ResourceType.template) { } else if (type == Resource.ResourceType.template) {
newCount = _vmTemplateDao.countTemplatesForAccount(accountId); newCount = _vmTemplateDao.countTemplatesForAccount(accountId);
} else if (type == Resource.ResourceType.project) { } else if (type == Resource.ResourceType.project) {
newCount = _projectAccountDao.countByAccountIdAndRole(accountId, Role.Admin); newCount = _projectAccountDao.countByAccountIdAndRole(accountId, Role.Admin);
} else { } else {
throw new InvalidParameterValueException("Unsupported resource type " + type); throw new InvalidParameterValueException("Unsupported resource type " + type);
} }
_resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue()); _resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue());
if (oldCount != newCount) { if (oldCount != newCount) {
s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " + s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " +
newCount + ") for type " + type + " for account ID " + accountId + " is fixed during resource count recalculation." ); newCount + ") for type " + type + " for account ID " + accountId + " is fixed during resource count recalculation.");
} }
txn.commit(); txn.commit();
return (newCount == null) ? 0 : newCount.longValue(); return (newCount == null) ? 0 : newCount.longValue();
} }
@Override @Override
public long getResourceCount(Account account, ResourceType type) { public long getResourceCount(Account account, ResourceType type) {
return _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type); return _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type);
} }
protected class ResourceCountCheckTask implements Runnable { protected class ResourceCountCheckTask implements Runnable {
public ResourceCountCheckTask() { public ResourceCountCheckTask() {
} }
@Override @Override
@ -744,7 +743,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
// recalculateDomainResourceCount will take care of re-calculation of resource counts for sub-domains // recalculateDomainResourceCount will take care of re-calculation of resource counts for sub-domains
// and accounts of the sub-domains also. so just loop through immediate children of root domain // and accounts of the sub-domains also. so just loop through immediate children of root domain
for (Domain domain : domains ) { for (Domain domain : domains) {
for (ResourceType type : ResourceCount.ResourceType.values()) { for (ResourceType type : ResourceCount.ResourceType.values()) {
if (type.supportsOwner(ResourceOwnerType.Domain)) { if (type.supportsOwner(ResourceOwnerType.Domain)) {
recalculateDomainResourceCount(domain.getId(), type); recalculateDomainResourceCount(domain.getId(), type);

View File

@ -25,11 +25,13 @@ import com.cloud.exception.InternalErrorException;
* This is the Server that is run right before the Management Server. * This is the Server that is run right before the Management Server.
*/ */
public interface ConfigurationServer { public interface ConfigurationServer {
public static final String Name = "configuration-server"; public static final String Name = "configuration-server";
/** /**
* Persists default values for the configuration table, pods/zones, and VLANs * Persists default values for the configuration table, pods/zones, and VLANs
* @return *
* @return
*/ */
public void persistDefaultValues() throws InternalErrorException; public void persistDefaultValues() throws InternalErrorException;
} }

View File

@ -108,7 +108,7 @@ import com.cloud.uuididentity.dao.IdentityDao;
public class ConfigurationServerImpl implements ConfigurationServer { public class ConfigurationServerImpl implements ConfigurationServer {
public static final Logger s_logger = Logger.getLogger(ConfigurationServerImpl.class.getName()); public static final Logger s_logger = Logger.getLogger(ConfigurationServerImpl.class.getName());
private final ConfigurationDao _configDao; private final ConfigurationDao _configDao;
private final DataCenterDao _zoneDao; private final DataCenterDao _zoneDao;
private final HostPodDao _podDao; private final HostPodDao _podDao;
@ -124,7 +124,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
private final ResourceCountDao _resourceCountDao; private final ResourceCountDao _resourceCountDao;
private final NetworkOfferingServiceMapDao _ntwkOfferingServiceMapDao; private final NetworkOfferingServiceMapDao _ntwkOfferingServiceMapDao;
private final IdentityDao _identityDao; private final IdentityDao _identityDao;
public ConfigurationServerImpl() { public ConfigurationServerImpl() {
ComponentLocator locator = ComponentLocator.getLocator(Name); ComponentLocator locator = ComponentLocator.getLocator(Name);
_configDao = locator.getDao(ConfigurationDao.class); _configDao = locator.getDao(ConfigurationDao.class);
@ -143,21 +143,22 @@ public class ConfigurationServerImpl implements ConfigurationServer {
_identityDao = locator.getDao(IdentityDao.class); _identityDao = locator.getDao(IdentityDao.class);
} }
@Override @DB @Override
@DB
public void persistDefaultValues() throws InternalErrorException { public void persistDefaultValues() throws InternalErrorException {
// Create system user and admin user // Create system user and admin user
saveUser(); saveUser();
// Get init // Get init
String init = _configDao.getValue("init"); String init = _configDao.getValue("init");
// Get domain suffix - needed for network creation // Get domain suffix - needed for network creation
_domainSuffix = _configDao.getValue("guest.domain.suffix"); _domainSuffix = _configDao.getValue("guest.domain.suffix");
if (init == null || init.equals("false")) { if (init == null || init.equals("false")) {
s_logger.debug("ConfigurationServer is saving default values to the database."); s_logger.debug("ConfigurationServer is saving default values to the database.");
// Save default Configuration Table values // Save default Configuration Table values
List<String> categories = Config.getCategories(); List<String> categories = Config.getCategories();
for (String category : categories) { for (String category : categories) {
@ -165,16 +166,16 @@ public class ConfigurationServerImpl implements ConfigurationServer {
if (!_configDao.isPremium() && category.equals("Premium")) { if (!_configDao.isPremium() && category.equals("Premium")) {
continue; continue;
} }
List<Config> configs = Config.getConfigs(category); List<Config> configs = Config.getConfigs(category);
for (Config c : configs) { for (Config c : configs) {
String name = c.key(); String name = c.key();
//if the config value already present in the db, don't insert it again // if the config value already present in the db, don't insert it again
if (_configDao.findByName(name) != null) { if (_configDao.findByName(name) != null) {
continue; continue;
} }
String instance = "DEFAULT"; String instance = "DEFAULT";
String component = c.getComponent(); String component = c.getComponent();
String value = c.getDefaultValue(); String value = c.getDefaultValue();
@ -184,7 +185,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
_configDao.persist(configVO); _configDao.persist(configVO);
} }
} }
_configDao.update(Config.UseSecondaryStorageVm.key(), Config.UseSecondaryStorageVm.getCategory(), "true"); _configDao.update(Config.UseSecondaryStorageVm.key(), Config.UseSecondaryStorageVm.getCategory(), "true");
s_logger.debug("ConfigurationServer made secondary storage vm required."); s_logger.debug("ConfigurationServer made secondary storage vm required.");
@ -192,17 +193,16 @@ public class ConfigurationServerImpl implements ConfigurationServer {
s_logger.debug("ConfigurationServer made secondary storage copy encrypted."); s_logger.debug("ConfigurationServer made secondary storage copy encrypted.");
_configDao.update("secstorage.secure.copy.cert", "realhostip"); _configDao.update("secstorage.secure.copy.cert", "realhostip");
s_logger.debug("ConfigurationServer made secondary storage copy use realhostip."); s_logger.debug("ConfigurationServer made secondary storage copy use realhostip.");
// Save default service offerings // Save default service offerings
createServiceOffering(User.UID_SYSTEM, "Small Instance", 1, 512, 500, "Small Instance", false, false, null); createServiceOffering(User.UID_SYSTEM, "Small Instance", 1, 512, 500, "Small Instance", false, false, null);
createServiceOffering(User.UID_SYSTEM, "Medium Instance", 1, 1024, 1000, "Medium Instance", false, false, null); createServiceOffering(User.UID_SYSTEM, "Medium Instance", 1, 1024, 1000, "Medium Instance", false, false, null);
// Save default disk offerings // Save default disk offerings
createdefaultDiskOffering(null, "Small", "Small Disk, 5 GB", 5, null); createdefaultDiskOffering(null, "Small", "Small Disk, 5 GB", 5, null);
createdefaultDiskOffering(null, "Medium", "Medium Disk, 20 GB", 20, null); createdefaultDiskOffering(null, "Medium", "Medium Disk, 20 GB", 20, null);
createdefaultDiskOffering(null, "Large", "Large Disk, 100 GB", 100, null); createdefaultDiskOffering(null, "Large", "Large Disk, 100 GB", 100, null);
// Save the mount parent to the configuration table // Save the mount parent to the configuration table
String mountParent = getMountParent(); String mountParent = getMountParent();
if (mountParent != null) { if (mountParent != null) {
@ -220,32 +220,31 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// generate a single sign-on key // generate a single sign-on key
updateSSOKey(); updateSSOKey();
//Create default network offerings // Create default network offerings
createDefaultNetworkOfferings(); createDefaultNetworkOfferings();
//Create default networks // Create default networks
createDefaultNetworks(); createDefaultNetworks();
//Create userIpAddress ranges // Create userIpAddress ranges
// Update existing vlans with networkId
//Update existing vlans with networkId
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
List<VlanVO> vlans = _vlanDao.listAll(); List<VlanVO> vlans = _vlanDao.listAll();
if (vlans != null && !vlans.isEmpty()) { if (vlans != null && !vlans.isEmpty()) {
for (VlanVO vlan : vlans) { for (VlanVO vlan : vlans) {
if (vlan.getNetworkId().longValue() == 0) { if (vlan.getNetworkId().longValue() == 0) {
updateVlanWithNetworkId(vlan); updateVlanWithNetworkId(vlan);
} }
//Create vlan user_ip_address range // Create vlan user_ip_address range
String ipPange = vlan.getIpRange(); String ipPange = vlan.getIpRange();
String[] range = ipPange.split("-"); String[] range = ipPange.split("-");
String startIp = range[0]; String startIp = range[0];
String endIp = range[1]; String endIp = range[1];
txn.start(); txn.start();
IPRangeConfig config = new IPRangeConfig(); IPRangeConfig config = new IPRangeConfig();
long startIPLong = NetUtils.ip2Long(startIp); long startIPLong = NetUtils.ip2Long(startIp);
@ -255,9 +254,9 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
} }
} }
//Update resource count if needed // Update resource count if needed
updateResourceCount(); updateResourceCount();
// keystore for SSL/TLS connection // keystore for SSL/TLS connection
updateSSLKeystore(); updateSSLKeystore();
@ -269,14 +268,13 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// Update the cloud identifier // Update the cloud identifier
updateCloudIdentifier(); updateCloudIdentifier();
updateUuids(); updateUuids();
// Set init to true // Set init to true
_configDao.update("init", "Hidden", "true"); _configDao.update("init", "Hidden", "true");
} }
private void updateUuids() { private void updateUuids() {
_identityDao.initializeDefaultUuid("disk_offering"); _identityDao.initializeDefaultUuid("disk_offering");
_identityDao.initializeDefaultUuid("network_offerings"); _identityDao.initializeDefaultUuid("network_offerings");
@ -297,15 +295,15 @@ public class ConfigurationServerImpl implements ConfigurationServer {
_identityDao.initializeDefaultUuid("networks"); _identityDao.initializeDefaultUuid("networks");
_identityDao.initializeDefaultUuid("user_ip_address"); _identityDao.initializeDefaultUuid("user_ip_address");
} }
private String getMountParent() { private String getMountParent() {
return getEnvironmentProperty("mount.parent"); return getEnvironmentProperty("mount.parent");
} }
private String getEnvironmentProperty(String name) { private String getEnvironmentProperty(String name) {
try { try {
final File propsFile = PropertiesUtil.findConfigFile("environment.properties"); final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
if (propsFile == null) { if (propsFile == null) {
return null; return null;
} else { } else {
@ -319,8 +317,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
return null; return null;
} }
} }
@DB @DB
protected void saveUser() { protected void saveUser() {
// insert system account // insert system account
@ -339,21 +336,21 @@ public class ConfigurationServerImpl implements ConfigurationServer {
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
} }
// insert admin user // insert admin user
long id = 2; long id = 2;
String username = "admin"; String username = "admin";
String firstname = "admin"; String firstname = "admin";
String lastname = "cloud"; String lastname = "cloud";
String password = "password"; String password = "password";
MessageDigest md5 = null; MessageDigest md5 = null;
try { try {
md5 = MessageDigest.getInstance("MD5"); md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
return; return;
} }
md5.reset(); md5.reset();
BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));
String pwStr = pwInt.toString(16); String pwStr = pwInt.toString(16);
@ -376,7 +373,6 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// now insert the user // now insert the user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " + insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " +
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())"; "VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())";
txn = Transaction.currentTxn(); txn = Transaction.currentTxn();
try { try {
@ -384,8 +380,6 @@ public class ConfigurationServerImpl implements ConfigurationServer {
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
} }
try { try {
String tableName = "security_group"; String tableName = "security_group";
@ -396,19 +390,19 @@ public class ConfigurationServerImpl implements ConfigurationServer {
tableName = "network_group"; tableName = "network_group";
} catch (Exception ex) { } catch (Exception ex) {
// if network_groups table exists, create the default security group there // if network_groups table exists, create the default security group there
} }
insertSql = "SELECT * FROM " + tableName + " where account_id=2 and name='default'"; insertSql = "SELECT * FROM " + tableName + " where account_id=2 and name='default'";
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();
if (!rs.next()) { if (!rs.next()) {
//save default security group // save default security group
if (tableName.equals("security_group")) { if (tableName.equals("security_group")) {
insertSql = "INSERT INTO " + tableName +" (name, description, account_id, domain_id) " + insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id) " +
"VALUES ('default', 'Default Security Group', 2, 1)"; "VALUES ('default', 'Default Security Group', 2, 1)";
} else { } else {
insertSql = "INSERT INTO " + tableName +" (name, description, account_id, domain_id, account_name) " + insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id, account_name) " +
"VALUES ('default', 'Default Security Group', 2, 1, 'admin')"; "VALUES ('default', 'Default Security Group', 2, 1, 'admin')";
} }
txn = Transaction.currentTxn(); txn = Transaction.currentTxn();
@ -430,7 +424,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String currentCloudIdentifier = _configDao.getValue("cloud.identifier"); String currentCloudIdentifier = _configDao.getValue("cloud.identifier");
if (currentCloudIdentifier == null || currentCloudIdentifier.isEmpty()) { if (currentCloudIdentifier == null || currentCloudIdentifier.isEmpty()) {
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
_configDao.update(Config.CloudIdentifier.key(),Config.CloudIdentifier.getCategory(), uuid); _configDao.update(Config.CloudIdentifier.key(), Config.CloudIdentifier.getCategory(), uuid);
} }
} }
@ -459,10 +453,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
try { try {
ou = InetAddress.getLocalHost().getCanonicalHostName(); ou = InetAddress.getLocalHost().getCanonicalHostName();
String[] group = ou.split("\\."); String[] group = ou.split("\\.");
// Simple check to see if we got IP Address... // Simple check to see if we got IP Address...
boolean isIPAddress = Pattern.matches("[0-9]$", group[group.length - 1]); boolean isIPAddress = Pattern.matches("[0-9]$", group[group.length - 1]);
if (isIPAddress) { if (isIPAddress) {
ou = "cloud.com"; ou = "cloud.com";
} else { } else {
@ -477,7 +471,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String o = ou; String o = ou;
String c = "Unknown"; String c = "Unknown";
String dname = "cn=\"" + cn + "\",ou=\"" + ou +"\",o=\"" + o + "\",c=\"" + c + "\""; String dname = "cn=\"" + cn + "\",ou=\"" + ou + "\",o=\"" + o + "\",c=\"" + c + "\"";
Script script = new Script(true, "keytool", 5000, null); Script script = new Script(true, "keytool", 5000, null);
script.add("-genkey"); script.add("-genkey");
script.add("-keystore", keystorePath); script.add("-keystore", keystorePath);
@ -498,7 +492,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
String dbString = _configDao.getValue("ssl.keystore"); String dbString = _configDao.getValue("ssl.keystore");
File confFile= PropertiesUtil.findConfigFile("db.properties"); File confFile = PropertiesUtil.findConfigFile("db.properties");
/* This line may throw a NPE, but that's due to fail to find db.properities, meant some bugs in the other places */ /* This line may throw a NPE, but that's due to fail to find db.properities, meant some bugs in the other places */
String confPath = confFile.getParent(); String confPath = confFile.getParent();
String keystorePath = confPath + "/cloud.keystore"; String keystorePath = confPath + "/cloud.keystore";
@ -508,13 +502,13 @@ public class ConfigurationServerImpl implements ConfigurationServer {
s_logger.info("SSL keystore located at " + keystorePath); s_logger.info("SSL keystore located at " + keystorePath);
try { try {
if (!dbExisted) { if (!dbExisted) {
if (!keystoreFile.exists()) { if (!keystoreFile.exists()) {
generateDefaultKeystore(keystorePath); generateDefaultKeystore(keystorePath);
s_logger.info("Generated SSL keystore."); s_logger.info("Generated SSL keystore.");
} }
String base64Keystore = getBase64Keystore(keystorePath); String base64Keystore = getBase64Keystore(keystorePath);
ConfigurationVO configVO = new ConfigurationVO("Hidden", "DEFAULT", "management-server", "ssl.keystore", DBEncryptionUtil.encrypt(base64Keystore), "SSL Keystore for the management servers"); ConfigurationVO configVO = new ConfigurationVO("Hidden", "DEFAULT", "management-server", "ssl.keystore", DBEncryptionUtil.encrypt(base64Keystore), "SSL Keystore for the management servers");
_configDao.persist(configVO); _configDao.persist(configVO);
s_logger.info("Stored SSL keystore to database."); s_logger.info("Stored SSL keystore to database.");
} else if (keystoreFile.exists()) { // and dbExisted } else if (keystoreFile.exists()) { // and dbExisted
// Check if they are the same one, otherwise override with local keystore // Check if they are the same one, otherwise override with local keystore
@ -553,7 +547,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// Grab the SSH key pair and insert it into the database, if it is not present // Grab the SSH key pair and insert it into the database, if it is not present
String userid = System.getProperty("user.name"); String userid = System.getProperty("user.name");
if (!userid.startsWith("cloud")){ if (!userid.startsWith("cloud")) {
return; return;
} }
String already = _configDao.getValue("ssh.privatekey"); String already = _configDao.getValue("ssh.privatekey");
@ -567,13 +561,13 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
File privkeyfile = new File(homeDir + "/.ssh/id_rsa"); File privkeyfile = new File(homeDir + "/.ssh/id_rsa");
File pubkeyfile = new File(homeDir + "/.ssh/id_rsa.pub"); File pubkeyfile = new File(homeDir + "/.ssh/id_rsa.pub");
if (already == null || already.isEmpty()) { if (already == null || already.isEmpty()) {
if (s_logger.isInfoEnabled()) { if (s_logger.isInfoEnabled()) {
s_logger.info("Systemvm keypairs not found in database. Need to store them in the database"); s_logger.info("Systemvm keypairs not found in database. Need to store them in the database");
} }
//FIXME: take a global database lock here for safety. // FIXME: take a global database lock here for safety.
Script.runSimpleBashScript("if [ -f ~/.ssh/id_rsa ] ; then rm -f ~/.ssh/id_rsa ; fi; ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q"); Script.runSimpleBashScript("if [ -f ~/.ssh/id_rsa ] ; then rm -f ~/.ssh/id_rsa ; fi; ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q");
byte[] arr1 = new byte[4094]; // configuration table column value size byte[] arr1 = new byte[4094]; // configuration table column value size
@ -581,24 +575,24 @@ public class ConfigurationServerImpl implements ConfigurationServer {
new DataInputStream(new FileInputStream(privkeyfile)).readFully(arr1); new DataInputStream(new FileInputStream(privkeyfile)).readFully(arr1);
} catch (EOFException e) { } catch (EOFException e) {
} catch (Exception e) { } catch (Exception e) {
s_logger.error("Cannot read the private key file",e); s_logger.error("Cannot read the private key file", e);
throw new CloudRuntimeException("Cannot read the private key file"); throw new CloudRuntimeException("Cannot read the private key file");
} }
String privateKey = new String(arr1).trim(); String privateKey = new String(arr1).trim();
byte[] arr2 = new byte[4094]; // configuration table column value size byte[] arr2 = new byte[4094]; // configuration table column value size
try { try {
new DataInputStream(new FileInputStream(pubkeyfile)).readFully(arr2); new DataInputStream(new FileInputStream(pubkeyfile)).readFully(arr2);
} catch (EOFException e) { } catch (EOFException e) {
} catch (Exception e) { } catch (Exception e) {
s_logger.warn("Cannot read the public key file",e); s_logger.warn("Cannot read the public key file", e);
throw new CloudRuntimeException("Cannot read the public key file"); throw new CloudRuntimeException("Cannot read the public key file");
} }
String publicKey = new String(arr2).trim(); String publicKey = new String(arr2).trim();
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '"+DBEncryptionUtil.encrypt(privateKey)+"','Private key for the entire CloudStack')"; "VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + "','Private key for the entire CloudStack')";
String insertSql2 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + String insertSql2 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '"+DBEncryptionUtil.encrypt(publicKey)+"','Public key for the entire CloudStack')"; "VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + "','Public key for the entire CloudStack')";
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
@ -608,7 +602,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
s_logger.debug("Private key inserted into database"); s_logger.debug("Private key inserted into database");
} }
} catch (SQLException ex) { } catch (SQLException ex) {
s_logger.error("SQL of the private key failed",ex); s_logger.error("SQL of the private key failed", ex);
throw new CloudRuntimeException("SQL of the private key failed"); throw new CloudRuntimeException("SQL of the private key failed");
} }
@ -619,10 +613,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
s_logger.debug("Public key inserted into database"); s_logger.debug("Public key inserted into database");
} }
} catch (SQLException ex) { } catch (SQLException ex) {
s_logger.error("SQL of the public key failed",ex); s_logger.error("SQL of the public key failed", ex);
throw new CloudRuntimeException("SQL of the public key failed"); throw new CloudRuntimeException("SQL of the public key failed");
} }
} else { } else {
s_logger.info("Keypairs already in database"); s_logger.info("Keypairs already in database");
if (userid.startsWith("cloud")) { if (userid.startsWith("cloud")) {
@ -635,10 +629,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
s_logger.info("Going to update systemvm iso with generated keypairs if needed"); s_logger.info("Going to update systemvm iso with generated keypairs if needed");
injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath()); injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath());
} }
private void writeKeyToDisk(String key, String keyPath) { private void writeKeyToDisk(String key, String keyPath) {
Script.runSimpleBashScript("mkdir -p ~/.ssh"); Script.runSimpleBashScript("mkdir -p ~/.ssh");
File keyfile = new File( keyPath); File keyfile = new File(keyPath);
if (!keyfile.exists()) { if (!keyfile.exists()) {
try { try {
keyfile.createNewFile(); keyfile.createNewFile();
@ -647,7 +641,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
throw new CloudRuntimeException("Failed to update keypairs on disk: cannot create key file " + keyPath); throw new CloudRuntimeException("Failed to update keypairs on disk: cannot create key file " + keyPath);
} }
} }
if (keyfile.exists()) { if (keyfile.exists()) {
try { try {
FileOutputStream kStream = new FileOutputStream(keyfile); FileOutputStream kStream = new FileOutputStream(keyfile);
@ -663,9 +657,9 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
} }
private void updateKeyPairsOnDisk(String homeDir ) { private void updateKeyPairsOnDisk(String homeDir) {
String pubKey = _configDao.getValue("ssh.publickey"); String pubKey = _configDao.getValue("ssh.publickey");
String prvKey = _configDao.getValue("ssh.privatekey"); String prvKey = _configDao.getValue("ssh.privatekey");
writeKeyToDisk(prvKey, homeDir + "/.ssh/id_rsa"); writeKeyToDisk(prvKey, homeDir + "/.ssh/id_rsa");
@ -673,20 +667,20 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
protected void injectSshKeysIntoSystemVmIsoPatch(String publicKeyPath, String privKeyPath) { protected void injectSshKeysIntoSystemVmIsoPatch(String publicKeyPath, String privKeyPath) {
String injectScript = "scripts/vm/systemvm/injectkeys.sh"; String injectScript = "scripts/vm/systemvm/injectkeys.sh";
String scriptPath = Script.findScript("" , injectScript); String scriptPath = Script.findScript("", injectScript);
String systemVmIsoPath = Script.findScript("", "vms/systemvm.iso"); String systemVmIsoPath = Script.findScript("", "vms/systemvm.iso");
if ( scriptPath == null ) { if (scriptPath == null) {
throw new CloudRuntimeException("Unable to find key inject script " + injectScript); throw new CloudRuntimeException("Unable to find key inject script " + injectScript);
} }
if (systemVmIsoPath == null) { if (systemVmIsoPath == null) {
throw new CloudRuntimeException("Unable to find systemvm iso vms/systemvm.iso"); throw new CloudRuntimeException("Unable to find systemvm iso vms/systemvm.iso");
} }
final Script command = new Script(scriptPath, s_logger); final Script command = new Script(scriptPath, s_logger);
command.add(publicKeyPath); command.add(publicKeyPath);
command.add(privKeyPath); command.add(privKeyPath);
command.add(systemVmIsoPath); command.add(systemVmIsoPath);
final String result = command.execute(); final String result = command.execute();
if (result != null) { if (result != null) {
s_logger.warn("Failed to inject generated public key into systemvm iso " + result); s_logger.warn("Failed to inject generated public key into systemvm iso " + result);
@ -697,14 +691,14 @@ public class ConfigurationServerImpl implements ConfigurationServer {
@DB @DB
protected void generateSecStorageVmCopyPassword() { protected void generateSecStorageVmCopyPassword() {
String already = _configDao.getValue("secstorage.copy.password"); String already = _configDao.getValue("secstorage.copy.password");
if (already == null) { if (already == null) {
s_logger.info("Need to store secondary storage vm copy password in the database"); s_logger.info("Need to store secondary storage vm copy password in the database");
String password = PasswordGenerator.generateRandomPassword(12); String password = PasswordGenerator.generateRandomPassword(12);
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')"; "VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')";
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
@ -712,9 +706,9 @@ public class ConfigurationServerImpl implements ConfigurationServer {
stmt1.executeUpdate(); stmt1.executeUpdate();
s_logger.debug("secondary storage vm copy password inserted into database"); s_logger.debug("secondary storage vm copy password inserted into database");
} catch (SQLException ex) { } catch (SQLException ex) {
s_logger.warn("Failed to insert secondary storage vm copy password",ex); s_logger.warn("Failed to insert secondary storage vm copy password", ex);
} }
} }
} }
@ -738,13 +732,13 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String[] cidrPair = cidr.split("\\/"); String[] cidrPair = cidr.split("\\/");
String cidrAddress = cidrPair[0]; String cidrAddress = cidrPair[0];
int cidrSize = Integer.parseInt(cidrPair[1]); int cidrSize = Integer.parseInt(cidrPair[1]);
if (startIp != null) { if (startIp != null) {
if (endIp == null) { if (endIp == null) {
endIp = NetUtils.getIpRangeEndIpFromCidr(cidrAddress, cidrSize); endIp = NetUtils.getIpRangeEndIpFromCidr(cidrAddress, cidrSize);
} }
} }
// Create the new pod in the database // Create the new pod in the database
String ipRange; String ipRange;
if (startIp != null) { if (startIp != null) {
@ -755,17 +749,17 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} else { } else {
ipRange = ""; ipRange = "";
} }
HostPodVO pod = new HostPodVO(podName, zoneId, gateway, cidrAddress, cidrSize, ipRange); HostPodVO pod = new HostPodVO(podName, zoneId, gateway, cidrAddress, cidrSize, ipRange);
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
txn.start(); txn.start();
if (_podDao.persist(pod) == null) { if (_podDao.persist(pod) == null) {
txn.rollback(); txn.rollback();
throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support."); throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support.");
} }
if (startIp != null) { if (startIp != null) {
_zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp); _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp);
} }
@ -775,7 +769,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
if (nums > 16 || nums <= 0) { if (nums > 16 || nums <= 0) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16"); throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16");
} }
/*local link ip address starts from 169.254.0.2 - 169.254.(nums)*/ /* local link ip address starts from 169.254.0.2 - 169.254.(nums) */
String[] linkLocalIpRanges = NetUtils.getLinkLocalIPRange(nums); String[] linkLocalIpRanges = NetUtils.getLinkLocalIPRange(nums);
if (linkLocalIpRanges == null) { if (linkLocalIpRanges == null) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16"); throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16");
@ -785,12 +779,12 @@ public class ConfigurationServerImpl implements ConfigurationServer {
txn.commit(); txn.commit();
} catch(Exception e) { } catch (Exception e) {
txn.rollback(); txn.rollback();
s_logger.error("Unable to create new pod due to " + e.getMessage(), e); s_logger.error("Unable to create new pod due to " + e.getMessage(), e);
throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support."); throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support.");
} }
return pod; return pod;
} }
@ -799,7 +793,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
diskSize = diskSize * 1024 * 1024 * 1024; diskSize = diskSize * 1024 * 1024 * 1024;
tags = cleanupTags(tags); tags = cleanupTags(tags);
DiskOfferingVO newDiskOffering = new DiskOfferingVO(domainId, name, description, diskSize,tags,false); DiskOfferingVO newDiskOffering = new DiskOfferingVO(domainId, name, description, diskSize, tags, false);
newDiskOffering.setUniqueName("Cloud.Com-" + name); newDiskOffering.setUniqueName("Cloud.Com-" + name);
newDiskOffering = _diskOfferingDao.persistDeafultDiskOffering(newDiskOffering); newDiskOffering = _diskOfferingDao.persistDeafultDiskOffering(newDiskOffering);
return newDiskOffering; return newDiskOffering;
@ -823,10 +817,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
t.delete(t.length() - 1, t.length()); t.delete(t.length() - 1, t.length());
tags = t.toString(); tags = t.toString();
} }
return tags; return tags;
} }
@DB @DB
protected void createDefaultNetworkOfferings() { protected void createDefaultNetworkOfferings() {
@ -838,21 +832,21 @@ public class ConfigurationServerImpl implements ConfigurationServer {
controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering); controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering);
NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage, true); NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage, true);
storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering); storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering);
//populate providers // populate providers
Map<Network.Service, Network.Provider> defaultSharedNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>(); Map<Network.Service, Network.Provider> defaultSharedNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
defaultSharedNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter); defaultSharedNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
defaultSharedNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter); defaultSharedNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);
defaultSharedNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter); defaultSharedNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter);
Map<Network.Service, Network.Provider> defaultIsolatedNetworkOfferingProviders = defaultSharedNetworkOfferingProviders; Map<Network.Service, Network.Provider> defaultIsolatedNetworkOfferingProviders = defaultSharedNetworkOfferingProviders;
Map<Network.Service, Network.Provider> defaultSharedSGNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>(); Map<Network.Service, Network.Provider> defaultSharedSGNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
defaultSharedSGNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter); defaultSharedSGNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
defaultSharedSGNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter); defaultSharedSGNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);
defaultSharedSGNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter); defaultSharedSGNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter);
defaultSharedSGNetworkOfferingProviders.put(Service.SecurityGroup, Provider.SecurityGroupProvider); defaultSharedSGNetworkOfferingProviders.put(Service.SecurityGroup, Provider.SecurityGroupProvider);
Map<Network.Service, Network.Provider> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>(); Map<Network.Service, Network.Provider> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);
@ -864,7 +858,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.StaticNat, Provider.VirtualRouter); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.StaticNat, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, Provider.VirtualRouter); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, Provider.VirtualRouter); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, Provider.VirtualRouter);
Map<Network.Service, Network.Provider> netscalerServiceProviders = new HashMap<Network.Service, Network.Provider>(); Map<Network.Service, Network.Provider> netscalerServiceProviders = new HashMap<Network.Service, Network.Provider>();
netscalerServiceProviders.put(Service.Dhcp, Provider.VirtualRouter); netscalerServiceProviders.put(Service.Dhcp, Provider.VirtualRouter);
netscalerServiceProviders.put(Service.Dns, Provider.VirtualRouter); netscalerServiceProviders.put(Service.Dns, Provider.VirtualRouter);
@ -873,132 +867,131 @@ public class ConfigurationServerImpl implements ConfigurationServer {
netscalerServiceProviders.put(Service.StaticNat, Provider.Netscaler); netscalerServiceProviders.put(Service.StaticNat, Provider.Netscaler);
netscalerServiceProviders.put(Service.Lb, Provider.Netscaler); netscalerServiceProviders.put(Service.Lb, Provider.Netscaler);
// The only one diff between 1 and 2 network offerings is that the first one has SG enabled. In Basic zone only
//The only one diff between 1 and 2 network offerings is that the first one has SG enabled. In Basic zone only first network offering has to be enabled, in Advance zone - the second one // first network offering has to be enabled, in Advance zone - the second one
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
//Offering #1 // Offering #1
NetworkOfferingVO deafultSharedSGNetworkOffering = new NetworkOfferingVO( NetworkOfferingVO deafultSharedSGNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultSharedNetworkOfferingWithSGService, NetworkOffering.DefaultSharedNetworkOfferingWithSGService,
"Offering for Shared Security group enabled networks", "Offering for Shared Security group enabled networks",
TrafficType.Guest, TrafficType.Guest,
false, true, null, null, true, Availability.Optional, false, true, null, null, true, Availability.Optional,
null, Network.GuestType.Shared, true, true); null, Network.GuestType.Shared, true, true);
deafultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled); deafultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled);
deafultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(deafultSharedSGNetworkOffering); deafultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(deafultSharedSGNetworkOffering);
for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) { for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(deafultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service)); NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(deafultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService); s_logger.trace("Added service for the network offering: " + offService);
} }
//Offering #2 // Offering #2
NetworkOfferingVO defaultSharedNetworkOffering = new NetworkOfferingVO( NetworkOfferingVO defaultSharedNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultSharedNetworkOffering, NetworkOffering.DefaultSharedNetworkOffering,
"Offering for Shared networks", "Offering for Shared networks",
TrafficType.Guest, TrafficType.Guest,
false, true, null, null, true, Availability.Optional, false, true, null, null, true, Availability.Optional,
null, Network.GuestType.Shared, true, true); null, Network.GuestType.Shared, true, true);
defaultSharedNetworkOffering.setState(NetworkOffering.State.Enabled); defaultSharedNetworkOffering.setState(NetworkOffering.State.Enabled);
defaultSharedNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedNetworkOffering); defaultSharedNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedNetworkOffering);
for (Service service : defaultSharedNetworkOfferingProviders.keySet()) { for (Service service : defaultSharedNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedNetworkOffering.getId(), service, defaultSharedNetworkOfferingProviders.get(service)); NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedNetworkOffering.getId(), service, defaultSharedNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService); s_logger.trace("Added service for the network offering: " + offService);
} }
//Offering #3 // Offering #3
NetworkOfferingVO defaultIsolatedSourceNatEnabledNetworkOffering = new NetworkOfferingVO( NetworkOfferingVO defaultIsolatedSourceNatEnabledNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService,
"Offering for Isolated networks with Source Nat service enabled", "Offering for Isolated networks with Source Nat service enabled",
TrafficType.Guest, TrafficType.Guest,
false, false, null, null, true, Availability.Required, false, false, null, null, true, Availability.Required,
null, Network.GuestType.Isolated, true, false); null, Network.GuestType.Isolated, true, false);
defaultIsolatedSourceNatEnabledNetworkOffering.setState(NetworkOffering.State.Enabled); defaultIsolatedSourceNatEnabledNetworkOffering.setState(NetworkOffering.State.Enabled);
defaultIsolatedSourceNatEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedSourceNatEnabledNetworkOffering); defaultIsolatedSourceNatEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedSourceNatEnabledNetworkOffering);
for (Service service : defaultIsolatedSourceNatEnabledNetworkOfferingProviders.keySet()) { for (Service service : defaultIsolatedSourceNatEnabledNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service)); NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService); s_logger.trace("Added service for the network offering: " + offService);
} }
//Offering #4 // Offering #4
NetworkOfferingVO defaultIsolatedEnabledNetworkOffering = new NetworkOfferingVO( NetworkOfferingVO defaultIsolatedEnabledNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultIsolatedNetworkOffering, NetworkOffering.DefaultIsolatedNetworkOffering,
"Offering for Isolated networks with no Source Nat service", "Offering for Isolated networks with no Source Nat service",
TrafficType.Guest, TrafficType.Guest,
false, true, null, null, true, Availability.Optional, false, true, null, null, true, Availability.Optional,
null, Network.GuestType.Isolated, true, true); null, Network.GuestType.Isolated, true, true);
defaultIsolatedEnabledNetworkOffering.setState(NetworkOffering.State.Enabled); defaultIsolatedEnabledNetworkOffering.setState(NetworkOffering.State.Enabled);
defaultIsolatedEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedEnabledNetworkOffering); defaultIsolatedEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedEnabledNetworkOffering);
for (Service service : defaultIsolatedNetworkOfferingProviders.keySet()) { for (Service service : defaultIsolatedNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedEnabledNetworkOffering.getId(), service, defaultIsolatedNetworkOfferingProviders.get(service)); NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedEnabledNetworkOffering.getId(), service, defaultIsolatedNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService); s_logger.trace("Added service for the network offering: " + offService);
} }
//Offering #5 // Offering #5
NetworkOfferingVO defaultNetscalerNetworkOffering = new NetworkOfferingVO( NetworkOfferingVO defaultNetscalerNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultSharedEIPandELBNetworkOffering, NetworkOffering.DefaultSharedEIPandELBNetworkOffering,
"Offering for Shared networks with Elastic IP and Elastic LB capabilities", "Offering for Shared networks with Elastic IP and Elastic LB capabilities",
TrafficType.Guest, TrafficType.Guest,
false, true, null, null, true, Availability.Optional, false, true, null, null, true, Availability.Optional,
null, Network.GuestType.Shared, true, false, false, false, true, true, true); null, Network.GuestType.Shared, true, false, false, false, true, true, true);
defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled); defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled);
defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering); defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering);
for (Service service : netscalerServiceProviders.keySet()) { for (Service service : netscalerServiceProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultNetscalerNetworkOffering.getId(), service, netscalerServiceProviders.get(service)); NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultNetscalerNetworkOffering.getId(), service, netscalerServiceProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService); _ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService); s_logger.trace("Added service for the network offering: " + offService);
} }
txn.commit(); txn.commit();
} }
private void createDefaultNetworks() { private void createDefaultNetworks() {
List<DataCenterVO> zones = _dataCenterDao.listAll(); List<DataCenterVO> zones = _dataCenterDao.listAll();
long id = 1; long id = 1;
HashMap<TrafficType, String> guruNames = new HashMap<TrafficType, String>(); HashMap<TrafficType, String> guruNames = new HashMap<TrafficType, String>();
guruNames.put(TrafficType.Public, PublicNetworkGuru.class.getSimpleName()); guruNames.put(TrafficType.Public, PublicNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Management, PodBasedNetworkGuru.class.getSimpleName()); guruNames.put(TrafficType.Management, PodBasedNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Control, ControlNetworkGuru.class.getSimpleName()); guruNames.put(TrafficType.Control, ControlNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Storage, StorageNetworkGuru.class.getSimpleName()); guruNames.put(TrafficType.Storage, StorageNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Guest, DirectPodBasedNetworkGuru.class.getSimpleName()); guruNames.put(TrafficType.Guest, DirectPodBasedNetworkGuru.class.getSimpleName());
for (DataCenterVO zone : zones) { for (DataCenterVO zone : zones) {
long zoneId = zone.getId(); long zoneId = zone.getId();
long accountId = 1L; long accountId = 1L;
Long domainId = zone.getDomainId(); Long domainId = zone.getDomainId();
if (domainId == null) { if (domainId == null) {
domainId = 1L; domainId = 1L;
} }
//Create default networks - system only // Create default networks - system only
List<NetworkOfferingVO> ntwkOff = _networkOfferingDao.listSystemNetworkOfferings(); List<NetworkOfferingVO> ntwkOff = _networkOfferingDao.listSystemNetworkOfferings();
for (NetworkOfferingVO offering : ntwkOff) { for (NetworkOfferingVO offering : ntwkOff) {
if (offering.isSystemOnly()) { if (offering.isSystemOnly()) {
long related = id; long related = id;
long networkOfferingId = offering.getId(); long networkOfferingId = offering.getId();
Mode mode = Mode.Static; Mode mode = Mode.Static;
String networkDomain = null; String networkDomain = null;
BroadcastDomainType broadcastDomainType = null; BroadcastDomainType broadcastDomainType = null;
TrafficType trafficType= offering.getTrafficType(); TrafficType trafficType = offering.getTrafficType();
boolean specifyIpRanges = false; boolean specifyIpRanges = false;
if (trafficType == TrafficType.Management) { if (trafficType == TrafficType.Management) {
@ -1010,15 +1003,16 @@ public class ConfigurationServerImpl implements ConfigurationServer {
broadcastDomainType = BroadcastDomainType.LinkLocal; broadcastDomainType = BroadcastDomainType.LinkLocal;
} else if (offering.getTrafficType() == TrafficType.Public) { } else if (offering.getTrafficType() == TrafficType.Public) {
if ((zone.getNetworkType() == NetworkType.Advanced && !zone.isSecurityGroupEnabled()) || zone.getNetworkType() == NetworkType.Basic) { if ((zone.getNetworkType() == NetworkType.Advanced && !zone.isSecurityGroupEnabled()) || zone.getNetworkType() == NetworkType.Basic) {
specifyIpRanges = true; specifyIpRanges = true;
broadcastDomainType = BroadcastDomainType.Vlan; broadcastDomainType = BroadcastDomainType.Vlan;
} else { } else {
continue; continue;
} }
} }
if (broadcastDomainType != null) { if (broadcastDomainType != null) {
NetworkVO network = new NetworkVO(id, trafficType, mode, broadcastDomainType, networkOfferingId, domainId, accountId, related, null, null, networkDomain, Network.GuestType.Shared, zoneId, null, null, specifyIpRanges); NetworkVO network = new NetworkVO(id, trafficType, mode, broadcastDomainType, networkOfferingId, domainId, accountId, related, null, null, networkDomain, Network.GuestType.Shared, zoneId, null,
null, specifyIpRanges);
network.setGuruName(guruNames.get(network.getTrafficType())); network.setGuruName(guruNames.get(network.getTrafficType()));
network.setDns1(zone.getDns1()); network.setDns1(zone.getDns1());
network.setDns2(zone.getDns2()); network.setDns2(zone.getDns2());
@ -1026,50 +1020,48 @@ public class ConfigurationServerImpl implements ConfigurationServer {
_networkDao.persist(network, false, getServicesAndProvidersForNetwork(networkOfferingId)); _networkDao.persist(network, false, getServicesAndProvidersForNetwork(networkOfferingId));
id++; id++;
} }
} }
} }
} }
} }
private void updateVlanWithNetworkId(VlanVO vlan) { private void updateVlanWithNetworkId(VlanVO vlan) {
long zoneId = vlan.getDataCenterId(); long zoneId = vlan.getDataCenterId();
long networkId = 0L; long networkId = 0L;
DataCenterVO zone = _zoneDao.findById(zoneId); DataCenterVO zone = _zoneDao.findById(zoneId);
if (zone.getNetworkType() == NetworkType.Advanced) { if (zone.getNetworkType() == NetworkType.Advanced) {
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Public); networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Public);
} else { } else {
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Guest); networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Guest);
} }
vlan.setNetworkId(networkId); vlan.setNetworkId(networkId);
_vlanDao.update(vlan.getId(), vlan); _vlanDao.update(vlan.getId(), vlan);
} }
private long getSystemNetworkIdByZoneAndTrafficType(long zoneId, TrafficType trafficType) { private long getSystemNetworkIdByZoneAndTrafficType(long zoneId, TrafficType trafficType) {
//find system public network offering // find system public network offering
Long networkOfferingId = null; Long networkOfferingId = null;
List<NetworkOfferingVO> offerings = _networkOfferingDao.listSystemNetworkOfferings(); List<NetworkOfferingVO> offerings = _networkOfferingDao.listSystemNetworkOfferings();
for (NetworkOfferingVO offering: offerings) { for (NetworkOfferingVO offering : offerings) {
if (offering.getTrafficType() == trafficType) { if (offering.getTrafficType() == trafficType) {
networkOfferingId = offering.getId(); networkOfferingId = offering.getId();
break; break;
} }
} }
if (networkOfferingId == null) { if (networkOfferingId == null) {
throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType); throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType);
} }
List<NetworkVO> networks = _networkDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId); List<NetworkVO> networks = _networkDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId);
if (networks == null || networks.isEmpty()) { if (networks == null || networks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId); throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId);
} }
return networks.get(0).getId(); return networks.get(0).getId();
} }
@DB @DB
public void updateResourceCount() { public void updateResourceCount() {
ResourceType[] resourceTypes = Resource.ResourceType.values(); ResourceType[] resourceTypes = Resource.ResourceType.values();
@ -1077,10 +1069,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
List<DomainVO> domains = _domainDao.listAllIncludingRemoved(); List<DomainVO> domains = _domainDao.listAllIncludingRemoved();
List<ResourceCountVO> domainResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Domain); List<ResourceCountVO> domainResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Domain);
List<ResourceCountVO> accountResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Account); List<ResourceCountVO> accountResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Account);
List<ResourceType> accountSupportedResourceTypes = new ArrayList<ResourceType>(); List<ResourceType> accountSupportedResourceTypes = new ArrayList<ResourceType>();
List<ResourceType> domainSupportedResourceTypes = new ArrayList<ResourceType>(); List<ResourceType> domainSupportedResourceTypes = new ArrayList<ResourceType>();
for (ResourceType resourceType : resourceTypes) { for (ResourceType resourceType : resourceTypes) {
if (resourceType.supportsOwner(ResourceOwnerType.Account)) { if (resourceType.supportsOwner(ResourceOwnerType.Account)) {
accountSupportedResourceTypes.add(resourceType); accountSupportedResourceTypes.add(resourceType);
@ -1089,15 +1081,14 @@ public class ConfigurationServerImpl implements ConfigurationServer {
domainSupportedResourceTypes.add(resourceType); domainSupportedResourceTypes.add(resourceType);
} }
} }
int accountExpectedCount = accountSupportedResourceTypes.size(); int accountExpectedCount = accountSupportedResourceTypes.size();
int domainExpectedCount = domainSupportedResourceTypes.size(); int domainExpectedCount = domainSupportedResourceTypes.size();
if ((domainResourceCount.size() < domainExpectedCount * domains.size())) { if ((domainResourceCount.size() < domainExpectedCount * domains.size())) {
s_logger.debug("resource_count table has records missing for some domains...going to insert them"); s_logger.debug("resource_count table has records missing for some domains...going to insert them");
for (DomainVO domain : domains) { for (DomainVO domain : domains) {
//Lock domain // Lock domain
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
_domainDao.lockRow(domain.getId(), true); _domainDao.lockRow(domain.getId(), true);
@ -1119,11 +1110,11 @@ public class ConfigurationServerImpl implements ConfigurationServer {
txn.commit(); txn.commit();
} }
} }
if ((accountResourceCount.size() < accountExpectedCount * accounts.size())) { if ((accountResourceCount.size() < accountExpectedCount * accounts.size())) {
s_logger.debug("resource_count table has records missing for some accounts...going to insert them"); s_logger.debug("resource_count table has records missing for some accounts...going to insert them");
for (AccountVO account : accounts) { for (AccountVO account : accounts) {
//lock account // lock account
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
_accountDao.lockRow(account.getId(), true); _accountDao.lockRow(account.getId(), true);
@ -1132,7 +1123,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
for (ResourceCountVO accountCount : accountCounts) { for (ResourceCountVO accountCount : accountCounts) {
accountCountStr.add(accountCount.getType().toString()); accountCountStr.add(accountCount.getType().toString());
} }
if (accountCountStr.size() < accountExpectedCount) { if (accountCountStr.size() < accountExpectedCount) {
for (ResourceType resourceType : accountSupportedResourceTypes) { for (ResourceType resourceType : accountSupportedResourceTypes) {
if (!accountCountStr.contains(resourceType.toString())) { if (!accountCountStr.contains(resourceType.toString())) {
@ -1142,23 +1133,23 @@ public class ConfigurationServerImpl implements ConfigurationServer {
} }
} }
} }
txn.commit(); txn.commit();
} }
} }
} }
public Map<String, String> getServicesAndProvidersForNetwork(long networkOfferingId) { public Map<String, String> getServicesAndProvidersForNetwork(long networkOfferingId) {
Map<String, String> svcProviders = new HashMap<String, String>(); Map<String, String> svcProviders = new HashMap<String, String>();
List<NetworkOfferingServiceMapVO> servicesMap = _ntwkOfferingServiceMapDao.listByNetworkOfferingId(networkOfferingId); List<NetworkOfferingServiceMapVO> servicesMap = _ntwkOfferingServiceMapDao.listByNetworkOfferingId(networkOfferingId);
for (NetworkOfferingServiceMapVO serviceMap : servicesMap) { for (NetworkOfferingServiceMapVO serviceMap : servicesMap) {
if (svcProviders.containsKey(serviceMap.getService())) { if (svcProviders.containsKey(serviceMap.getService())) {
continue; continue;
} }
svcProviders.put(serviceMap.getService(), serviceMap.getProvider()); svcProviders.put(serviceMap.getService(), serviceMap.getProvider());
} }
return svcProviders; return svcProviders;
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -23,11 +23,11 @@ import java.util.Set;
import com.cloud.domain.Domain; import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO; import com.cloud.domain.DomainVO;
public interface DomainManager extends DomainService{ public interface DomainManager extends DomainService {
Set<Long> getDomainChildrenIds(String parentDomainPath); Set<Long> getDomainChildrenIds(String parentDomainPath);
Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain); Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain);
/** /**
* find the domain by its path * find the domain by its path
* *
@ -36,11 +36,11 @@ public interface DomainManager extends DomainService{
* @return domainVO the domain with the matching path, or null if no domain with the given path exists * @return domainVO the domain with the matching path, or null if no domain with the given path exists
*/ */
DomainVO findDomainByPath(String domainPath); DomainVO findDomainByPath(String domainPath);
Set<Long> getDomainParentIds(long domainId); Set<Long> getDomainParentIds(long domainId);
boolean removeDomain(long domainId); boolean removeDomain(long domainId);
List<? extends Domain> findInactiveDomains(); List<? extends Domain> findInactiveDomains();
boolean deleteDomain(DomainVO domain, Boolean cleanup); boolean deleteDomain(DomainVO domain, Boolean cleanup);

View File

@ -57,9 +57,9 @@ import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
@Local(value = { DomainManager.class, DomainService.class }) @Local(value = { DomainManager.class, DomainService.class })
public class DomainManagerImpl implements DomainManager, DomainService, Manager{ public class DomainManagerImpl implements DomainManager, DomainService, Manager {
public static final Logger s_logger = Logger.getLogger(DomainManagerImpl.class); public static final Logger s_logger = Logger.getLogger(DomainManagerImpl.class);
private String _name; private String _name;
@Inject @Inject
private DomainDao _domainDao; private DomainDao _domainDao;
@ -71,14 +71,14 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
private AccountDao _accountDao; private AccountDao _accountDao;
@Inject @Inject
private DiskOfferingDao _diskOfferingDao; private DiskOfferingDao _diskOfferingDao;
@Inject @Inject
private ServiceOfferingDao _offeringsDao; private ServiceOfferingDao _offeringsDao;
@Override @Override
public Domain getDomain(long domainId) { public Domain getDomain(long domainId) {
return _domainDao.findById(domainId); return _domainDao.findById(domainId);
} }
@Override @Override
public String getName() { public String getName() {
return _name; return _name;
@ -93,34 +93,34 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
public boolean stop() { public boolean stop() {
return true; return true;
} }
@Override @Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
return true; return true;
} }
@Override @Override
public Set<Long> getDomainChildrenIds(String parentDomainPath) { public Set<Long> getDomainChildrenIds(String parentDomainPath) {
Set<Long> childDomains = new HashSet<Long>(); Set<Long> childDomains = new HashSet<Long>();
SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria(); SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
sc.addAnd("path", SearchCriteria.Op.LIKE, parentDomainPath + "%"); sc.addAnd("path", SearchCriteria.Op.LIKE, parentDomainPath + "%");
List<DomainVO> domains = _domainDao.search(sc, null); List<DomainVO> domains = _domainDao.search(sc, null);
for (DomainVO domain : domains) { for (DomainVO domain : domains) {
childDomains.add(domain.getId()); childDomains.add(domain.getId());
} }
return childDomains; return childDomains;
} }
@Override @Override
public boolean isChildDomain(Long parentId, Long childId) { public boolean isChildDomain(Long parentId, Long childId) {
return _domainDao.isChildDomain(parentId, childId); return _domainDao.isChildDomain(parentId, childId);
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_CREATE, eventDescription = "creating Domain") @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_CREATE, eventDescription = "creating Domain")
public Domain createDomain(String name, Long parentId, String networkDomain) { public Domain createDomain(String name, Long parentId, String networkDomain) {
@ -134,27 +134,26 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
if (parentDomain == null) { if (parentDomain == null) {
throw new InvalidParameterValueException("Unable to create domain " + name + ", parent domain " + parentId + " not found."); throw new InvalidParameterValueException("Unable to create domain " + name + ", parent domain " + parentId + " not found.");
} }
if (parentDomain.getState().equals(Domain.State.Inactive)) { if (parentDomain.getState().equals(Domain.State.Inactive)) {
throw new CloudRuntimeException("The domain cannot be created as the parent domain " + parentDomain.getName() + " is being deleted"); throw new CloudRuntimeException("The domain cannot be created as the parent domain " + parentDomain.getName() + " is being deleted");
} }
_accountMgr.checkAccess(caller, parentDomain); _accountMgr.checkAccess(caller, parentDomain);
return createDomain(name, parentId, caller.getId(), networkDomain); return createDomain(name, parentId, caller.getId(), networkDomain);
} }
@Override @Override
@DB @DB
public Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain) { public Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain) {
//Verify network domain // Verify network domain
if (networkDomain != null) { if (networkDomain != null) {
if (!NetUtils.verifyDomainName(networkDomain)) { if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException( throw new InvalidParameterValueException(
"Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\""); + "and the hyphen ('-'); can't start or end with \"-\"");
} }
} }
@ -162,64 +161,63 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
sc.addAnd("name", SearchCriteria.Op.EQ, name); sc.addAnd("name", SearchCriteria.Op.EQ, name);
sc.addAnd("parent", SearchCriteria.Op.EQ, parentId); sc.addAnd("parent", SearchCriteria.Op.EQ, parentId);
List<DomainVO> domains = _domainDao.search(sc, null); List<DomainVO> domains = _domainDao.search(sc, null);
if (!domains.isEmpty()) { if (!domains.isEmpty()) {
throw new InvalidParameterValueException("Domain with name " + name + " already exists for the parent id=" + parentId); throw new InvalidParameterValueException("Domain with name " + name + " already exists for the parent id=" + parentId);
} }
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain)); DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain));
_resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain); _resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain);
txn.commit(); txn.commit();
return domain; return domain;
} }
@Override @Override
public DomainVO findDomainByPath(String domainPath) { public DomainVO findDomainByPath(String domainPath) {
return _domainDao.findDomainByPath(domainPath); return _domainDao.findDomainByPath(domainPath);
} }
@Override @Override
public Set<Long> getDomainParentIds(long domainId) { public Set<Long> getDomainParentIds(long domainId) {
return _domainDao.getDomainParentIds(domainId); return _domainDao.getDomainParentIds(domainId);
} }
@Override @Override
public boolean removeDomain(long domainId) { public boolean removeDomain(long domainId) {
return _domainDao.remove(domainId); return _domainDao.remove(domainId);
} }
@Override @Override
public List<? extends Domain> findInactiveDomains() { public List<? extends Domain> findInactiveDomains() {
return _domainDao.findInactiveDomains(); return _domainDao.findInactiveDomains();
} }
@Override @Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_DELETE, eventDescription = "deleting Domain", async = true) @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_DELETE, eventDescription = "deleting Domain", async = true)
public boolean deleteDomain(long domainId, Boolean cleanup) { public boolean deleteDomain(long domainId, Boolean cleanup) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
DomainVO domain = _domainDao.findById(domainId); DomainVO domain = _domainDao.findById(domainId);
if (domain == null) { if (domain == null) {
throw new InvalidParameterValueException("Failed to delete domain " + domainId + ", domain not found"); throw new InvalidParameterValueException("Failed to delete domain " + domainId + ", domain not found");
} else if (domainId == DomainVO.ROOT_DOMAIN) { } else if (domainId == DomainVO.ROOT_DOMAIN) {
throw new PermissionDeniedException("Can't delete ROOT domain"); throw new PermissionDeniedException("Can't delete ROOT domain");
} }
_accountMgr.checkAccess(caller, domain); _accountMgr.checkAccess(caller, domain);
return deleteDomain(domain, cleanup); return deleteDomain(domain, cleanup);
} }
@Override @Override
public boolean deleteDomain(DomainVO domain, Boolean cleanup) { public boolean deleteDomain(DomainVO domain, Boolean cleanup) {
//mark domain as inactive // mark domain as inactive
s_logger.debug("Marking domain id=" + domain.getId() + " as " + Domain.State.Inactive + " before actually deleting it"); s_logger.debug("Marking domain id=" + domain.getId() + " as " + Domain.State.Inactive + " before actually deleting it");
domain.setState(Domain.State.Inactive); domain.setState(Domain.State.Inactive);
_domainDao.update(domain.getId(), domain); _domainDao.update(domain.getId(), domain);
@ -231,20 +229,20 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
s_logger.error("Failed to clean up domain resources and sub domains, delete failed on domain " + domain.getName() + " (id: " + domain.getId() + ")."); s_logger.error("Failed to clean up domain resources and sub domains, delete failed on domain " + domain.getName() + " (id: " + domain.getId() + ").");
return false; return false;
} }
} else { } else {
List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domain.getId()); List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domain.getId());
if (accountsForCleanup.isEmpty()) { if (accountsForCleanup.isEmpty()) {
if (!_domainDao.remove(domain.getId())) { if (!_domainDao.remove(domain.getId())) {
s_logger.error("Delete failed on domain " + domain.getName() + " (id: " + domain.getId() s_logger.error("Delete failed on domain " + domain.getName() + " (id: " + domain.getId()
+ "); please make sure all users and sub domains have been removed from the domain before deleting"); + "); please make sure all users and sub domains have been removed from the domain before deleting");
return false; return false;
} }
} else { } else {
s_logger.warn("Can't delete the domain yet because it has " + accountsForCleanup.size() + "accounts that need a cleanup"); s_logger.warn("Can't delete the domain yet because it has " + accountsForCleanup.size() + "accounts that need a cleanup");
return false; return false;
} }
} }
cleanupDomainOfferings(domain.getId()); cleanupDomainOfferings(domain.getId());
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
@ -252,7 +250,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
return false; return false;
} }
} }
private void cleanupDomainOfferings(Long domainId) { private void cleanupDomainOfferings(Long domainId) {
// delete the service and disk offerings associated with this domain // delete the service and disk offerings associated with this domain
List<DiskOfferingVO> diskOfferingsForThisDomain = _diskOfferingDao.listByDomainId(domainId); List<DiskOfferingVO> diskOfferingsForThisDomain = _diskOfferingDao.listByDomainId(domainId);
@ -306,8 +304,8 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
s_logger.warn("Failed to cleanup account id=" + account.getId() + " as a part of domain cleanup"); s_logger.warn("Failed to cleanup account id=" + account.getId() + " as a part of domain cleanup");
} }
} }
//don't remove the domain if there are accounts required cleanup // don't remove the domain if there are accounts required cleanup
boolean deleteDomainSuccess = true; boolean deleteDomainSuccess = true;
List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domainId); List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domainId);
if (accountsForCleanup.isEmpty()) { if (accountsForCleanup.isEmpty()) {
@ -318,14 +316,14 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
return success && deleteDomainSuccess; return success && deleteDomainSuccess;
} }
@Override @Override
public List<DomainVO> searchForDomains(ListDomainsCmd cmd){ public List<DomainVO> searchForDomains(ListDomainsCmd cmd) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
Long domainId = cmd.getId(); Long domainId = cmd.getId();
boolean listAll = cmd.listAll(); boolean listAll = cmd.listAll();
boolean isRecursive = false; boolean isRecursive = false;
if (domainId != null) { if (domainId != null) {
Domain domain = getDomain(domainId); Domain domain = getDomain(domainId);
if (domain == null) { if (domain == null) {
@ -333,10 +331,10 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
} }
_accountMgr.checkAccess(caller, domain); _accountMgr.checkAccess(caller, domain);
} else { } else {
domainId = caller.getDomainId(); domainId = caller.getDomainId();
if (listAll) { if (listAll) {
isRecursive = true; isRecursive = true;
} }
} }
Filter searchFilter = new Filter(DomainVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); Filter searchFilter = new Filter(DomainVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
@ -368,31 +366,31 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
} }
if (domainId != null) { if (domainId != null) {
if (isRecursive) { if (isRecursive) {
sc.setParameters("path", getDomain(domainId).getPath() + "%"); sc.setParameters("path", getDomain(domainId).getPath() + "%");
} else { } else {
sc.setParameters("id", domainId); sc.setParameters("id", domainId);
} }
} }
//return only Active domains to the API // return only Active domains to the API
sc.setParameters("state", Domain.State.Active); sc.setParameters("state", Domain.State.Active);
return _domainDao.search(sc, searchFilter); return _domainDao.search(sc, searchFilter);
} }
@Override @Override
public List<DomainVO> searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException { public List<DomainVO> searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException {
Long domainId = cmd.getId(); Long domainId = cmd.getId();
String domainName = cmd.getDomainName(); String domainName = cmd.getDomainName();
Boolean isRecursive = cmd.isRecursive(); Boolean isRecursive = cmd.isRecursive();
Object keyword = cmd.getKeyword(); Object keyword = cmd.getKeyword();
boolean listAll = cmd.listAll(); boolean listAll = cmd.listAll();
String path = null; String path = null;
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
if (domainId != null) { if (domainId != null) {
_accountMgr.checkAccess(caller, getDomain(domainId)); _accountMgr.checkAccess(caller, getDomain(domainId));
} else { } else {
domainId = caller.getDomainId(); domainId = caller.getDomainId();
} }
@ -408,7 +406,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
return domainList; return domainList;
} }
private List<DomainVO> searchForDomainChildren(Filter searchFilter, Long domainId, String domainName, Object keyword, String path, boolean listActiveOnly) { private List<DomainVO> searchForDomainChildren(Filter searchFilter, Long domainId, String domainName, Object keyword, String path, boolean listActiveOnly) {
SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria(); SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
@ -431,11 +429,12 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
sc.addAnd("path", SearchCriteria.Op.NEQ, path); sc.addAnd("path", SearchCriteria.Op.NEQ, path);
sc.addAnd("path", SearchCriteria.Op.LIKE, path + "%"); sc.addAnd("path", SearchCriteria.Op.LIKE, path + "%");
} }
if (listActiveOnly) { if (listActiveOnly) {
sc.addAnd("state", SearchCriteria.Op.EQ, Domain.State.Active); sc.addAnd("state", SearchCriteria.Op.EQ, Domain.State.Active);
} }
return _domainDao.search(sc, searchFilter); return _domainDao.search(sc, searchFilter);
} }
} }

View File

@ -17,7 +17,6 @@
*/ */
package com.cloud.upgrade; package com.cloud.upgrade;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -37,32 +36,39 @@ import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
public class Test2214To30DBUpgrade extends TestCase { public class Test2214To30DBUpgrade extends TestCase {
private static final Logger s_logger = Logger.getLogger(Test2214To30DBUpgrade.class); private static final Logger s_logger = Logger
.getLogger(Test2214To30DBUpgrade.class);
@Override @Override
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
DbTestUtils.executeScript("PreviousDatabaseSchema/clean-db.sql", false, true); DbTestUtils.executeScript("PreviousDatabaseSchema/clean-db.sql", false,
true);
} }
@Override @Override
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
} }
public void test2213to30Upgrade() throws SQLException{ public void test2213to30Upgrade() throws SQLException {
s_logger.debug("Finding sample data from 2.2.14"); s_logger.debug("Finding sample data from 2.2.14");
DbTestUtils.executeScript("PreviousDatabaseSchema/2.2.14/cloud_usage_2214.sql", false, true); DbTestUtils.executeScript(
DbTestUtils.executeScript("PreviousDatabaseSchema/2.2.14/advance_zone_2.2.14.sql", false, true); "PreviousDatabaseSchema/2.2.14/cloud_usage_2214.sql", false,
true);
DatabaseUpgradeChecker checker = ComponentLocator.inject(DatabaseUpgradeChecker.class); DbTestUtils.executeScript(
"PreviousDatabaseSchema/2.2.14/advance_zone_2.2.14.sql", false,
true);
DatabaseUpgradeChecker checker = ComponentLocator
.inject(DatabaseUpgradeChecker.class);
checker.upgrade("2.2.14", "3.0.0"); checker.upgrade("2.2.14", "3.0.0");
Connection conn = Transaction.getStandaloneConnection(); Connection conn = Transaction.getStandaloneConnection();
try { try {
checkPhysicalNetworks(conn); checkPhysicalNetworks(conn);
checkNetworkOfferings(conn); checkNetworkOfferings(conn);
checkNetworks(conn); checkNetworks(conn);
} finally { } finally {
@ -71,125 +77,128 @@ public class Test2214To30DBUpgrade extends TestCase {
} catch (SQLException e) { } catch (SQLException e) {
} }
} }
} }
protected void checkPhysicalNetworks(Connection conn) throws SQLException { protected void checkPhysicalNetworks(Connection conn) throws SQLException {
PreparedStatement pstmt; PreparedStatement pstmt;
pstmt = conn.prepareStatement("SELECT version FROM version ORDER BY id DESC LIMIT 1"); pstmt = conn
.prepareStatement("SELECT version FROM version ORDER BY id DESC LIMIT 1");
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
assert rs.next() : "No version selected"; assert rs.next() : "No version selected";
assert rs.getString(1).equals("3.0.0") : "VERSION stored is not 3.0.0: " + rs.getString(1); assert rs.getString(1).equals("3.0.0") : "VERSION stored is not 3.0.0: "
+ rs.getString(1);
rs.close(); rs.close();
pstmt.close(); pstmt.close();
pstmt = conn.prepareStatement("SELECT COUNT(*) FROM physical_network"); pstmt = conn.prepareStatement("SELECT COUNT(*) FROM physical_network");
rs = pstmt.executeQuery(); rs = pstmt.executeQuery();
assert rs.next() : "No physical networks setup."; assert rs.next() : "No physical networks setup.";
rs.close(); rs.close();
pstmt.close(); pstmt.close();
}
}
protected void checkNetworkOfferings(Connection conn) throws SQLException { protected void checkNetworkOfferings(Connection conn) throws SQLException {
//1) verify that all fields are present // 1) verify that all fields are present
List<String> fields = new ArrayList<String>(); List<String> fields = new ArrayList<String>();
fields.add("id"); fields.add("id");
fields.add("name"); fields.add("name");
fields.add("unique_name"); fields.add("unique_name");
fields.add("display_text"); fields.add("display_text");
fields.add("nw_rate"); fields.add("nw_rate");
fields.add("mc_rate"); fields.add("mc_rate");
fields.add("traffic_type"); fields.add("traffic_type");
fields.add("specify_vlan"); fields.add("specify_vlan");
fields.add("system_only"); fields.add("system_only");
fields.add("service_offering_id"); fields.add("service_offering_id");
fields.add("tags"); fields.add("tags");
fields.add("default"); fields.add("default");
fields.add("availability"); fields.add("availability");
fields.add("state"); fields.add("state");
fields.add("removed"); fields.add("removed");
fields.add("created"); fields.add("created");
fields.add("guest_type"); fields.add("guest_type");
fields.add("dedicated_lb_service"); fields.add("dedicated_lb_service");
fields.add("shared_source_nat_service"); fields.add("shared_source_nat_service");
fields.add("specify_ip_ranges"); fields.add("specify_ip_ranges");
fields.add("sort_key"); fields.add("sort_key");
fields.add("uuid"); fields.add("uuid");
fields.add("redundant_router_service"); fields.add("redundant_router_service");
fields.add("conserve_mode"); fields.add("conserve_mode");
fields.add("elastic_ip_service"); fields.add("elastic_ip_service");
fields.add("elastic_lb_service"); fields.add("elastic_lb_service");
PreparedStatement pstmt; PreparedStatement pstmt;
for (String field : fields) { for (String field : fields) {
pstmt = conn.prepareStatement("SHOW COLUMNS FROM network_offerings LIKE ?"); pstmt = conn
pstmt.setString(1, field); .prepareStatement("SHOW COLUMNS FROM network_offerings LIKE ?");
ResultSet rs = pstmt.executeQuery(); pstmt.setString(1, field);
if (!rs.next()) { ResultSet rs = pstmt.executeQuery();
throw new CloudRuntimeException("Field " + field + " is missing in upgraded network_offerings table"); if (!rs.next()) {
} throw new CloudRuntimeException("Field " + field
rs.close(); + " is missing in upgraded network_offerings table");
pstmt.close(); }
rs.close();
pstmt.close();
} }
//2) compare default network offerings // 2) compare default network offerings
} }
protected void checkNetworks(Connection conn) throws SQLException { protected void checkNetworks(Connection conn) throws SQLException {
//1) verify that all fields are present // 1) verify that all fields are present
List<String> fields = new ArrayList<String>(); List<String> fields = new ArrayList<String>();
fields.add("id"); fields.add("id");
fields.add("name"); fields.add("name");
fields.add("mode");
fields.add("broadcast_domain_type"); fields.add("mode");
fields.add("traffic_type"); fields.add("broadcast_domain_type");
fields.add("display_text"); fields.add("traffic_type");
fields.add("broadcast_uri"); fields.add("display_text");
fields.add("gateway"); fields.add("broadcast_uri");
fields.add("cidr"); fields.add("gateway");
fields.add("network_offering_id"); fields.add("cidr");
fields.add("physical_network_id"); fields.add("network_offering_id");
fields.add("data_center_id"); fields.add("physical_network_id");
fields.add("related"); fields.add("data_center_id");
fields.add("guru_name"); fields.add("related");
fields.add("state"); fields.add("guru_name");
fields.add("dns1"); fields.add("state");
fields.add("domain_id"); fields.add("dns1");
fields.add("account_id"); fields.add("domain_id");
fields.add("set_fields"); fields.add("account_id");
fields.add("guru_data"); fields.add("set_fields");
fields.add("dns2"); fields.add("guru_data");
fields.add("network_domain"); fields.add("dns2");
fields.add("created"); fields.add("network_domain");
fields.add("removed"); fields.add("created");
fields.add("reservation_id"); fields.add("removed");
fields.add("uuid"); fields.add("reservation_id");
fields.add("guest_type"); fields.add("uuid");
fields.add("restart_required"); fields.add("guest_type");
fields.add("specify_ip_ranges"); fields.add("restart_required");
fields.add("acl_type"); fields.add("specify_ip_ranges");
fields.add("specified_cidr"); fields.add("acl_type");
fields.add("specified_cidr");
PreparedStatement pstmt;
PreparedStatement pstmt;
for (String field : fields) { for (String field : fields) {
pstmt = conn.prepareStatement("SHOW COLUMNS FROM networks LIKE ?"); pstmt = conn.prepareStatement("SHOW COLUMNS FROM networks LIKE ?");
pstmt.setString(1, field); pstmt.setString(1, field);
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
if (!rs.next()) { if (!rs.next()) {
throw new CloudRuntimeException("Field " + field + " is missing in upgraded networks table"); throw new CloudRuntimeException("Field " + field
} + " is missing in upgraded networks table");
rs.close(); }
pstmt.close(); rs.close();
pstmt.close();
} }
} }
} }