mirror of
https://github.com/apache/cloudstack.git
synced 2025-11-02 20:02:29 +01:00
Fixed format style in a bunch of files (replaced tabs with spaces as a part of it)
This commit is contained in:
parent
1f0ea28cc4
commit
1490e45a1c
@ -1,4 +1,5 @@
|
||||
/**
|
||||
|
||||
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
package com.cloud.api.commands;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.api.ApiConstants;
|
||||
import com.cloud.api.BaseCmd;
|
||||
*/
|
||||
package com.cloud.api.commands;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.api.ApiConstants;
|
||||
import com.cloud.api.BaseCmd;
|
||||
import com.cloud.api.IdentityMapper;
|
||||
import com.cloud.api.Implementation;
|
||||
import com.cloud.api.Parameter;
|
||||
import com.cloud.api.ServerApiException;
|
||||
import com.cloud.api.BaseCmd.CommandType;
|
||||
import com.cloud.api.response.SecurityGroupResponse;
|
||||
import com.cloud.network.security.SecurityGroup;
|
||||
import com.cloud.user.Account;
|
||||
import com.cloud.user.UserContext;
|
||||
|
||||
@Implementation(responseObject=SecurityGroupResponse.class, description="Creates a security group")
|
||||
public class CreateSecurityGroupCmd extends BaseCmd {
|
||||
public static final Logger s_logger = Logger.getLogger(CreateSecurityGroupCmd.class.getName());
|
||||
|
||||
private static final String s_name = "createsecuritygroupresponse";
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
//////////////// API parameters /////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
@Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.")
|
||||
private String accountName;
|
||||
|
||||
@IdentityMapper(entityTableName="domain")
|
||||
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.")
|
||||
private Long domainId;
|
||||
|
||||
@Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="the description of the security group")
|
||||
private String description;
|
||||
|
||||
@Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="name of the security group")
|
||||
import com.cloud.api.Implementation;
|
||||
import com.cloud.api.Parameter;
|
||||
import com.cloud.api.ServerApiException;
|
||||
import com.cloud.api.response.SecurityGroupResponse;
|
||||
import com.cloud.network.security.SecurityGroup;
|
||||
import com.cloud.user.Account;
|
||||
import com.cloud.user.UserContext;
|
||||
|
||||
@Implementation(responseObject = SecurityGroupResponse.class, description = "Creates a security group")
|
||||
public class CreateSecurityGroupCmd extends BaseCmd {
|
||||
public static final Logger s_logger = Logger.getLogger(CreateSecurityGroupCmd.class.getName());
|
||||
|
||||
private static final String s_name = "createsecuritygroupresponse";
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ////////////// API parameters /////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the security group. Must be used with domainId.")
|
||||
private String accountName;
|
||||
|
||||
@IdentityMapper(entityTableName = "domain")
|
||||
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "an optional domainId for the security group. If the account parameter is used, domainId must also be used.")
|
||||
private Long domainId;
|
||||
|
||||
@Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "the description of the security group")
|
||||
private String description;
|
||||
|
||||
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the security group")
|
||||
private String securityGroupName;
|
||||
|
||||
@IdentityMapper(entityTableName="projects")
|
||||
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Deploy vm for the project")
|
||||
private Long projectId;
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////////// Accessors ///////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public String getSecurityGroupName() {
|
||||
return securityGroupName;
|
||||
|
||||
@IdentityMapper(entityTableName = "projects")
|
||||
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "Deploy vm for the project")
|
||||
private Long projectId;
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////////// Accessors ///////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public String getSecurityGroupName() {
|
||||
return securityGroupName;
|
||||
}
|
||||
|
||||
public Long getProjectId() {
|
||||
return projectId;
|
||||
}
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////// API Implementation///////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return s_name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getEntityOwnerId() {
|
||||
Account account = UserContext.current().getCaller();
|
||||
if ((account == null) || isAdmin(account.getType())) {
|
||||
if ((domainId != null) && (accountName != null)) {
|
||||
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
|
||||
if (userAccount != null) {
|
||||
return userAccount.getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (account != null) {
|
||||
return account.getId();
|
||||
}
|
||||
|
||||
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(){
|
||||
SecurityGroup group = _securityGroupService.createSecurityGroup(this);
|
||||
if (group != null) {
|
||||
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponse(group);
|
||||
response.setResponseName(getCommandName());
|
||||
this.setResponseObject(response);
|
||||
} else {
|
||||
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create security group");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////// API Implementation///////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return s_name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getEntityOwnerId() {
|
||||
Account account = UserContext.current().getCaller();
|
||||
if ((account == null) || isAdmin(account.getType())) {
|
||||
if ((domainId != null) && (accountName != null)) {
|
||||
Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
|
||||
if (userAccount != null) {
|
||||
return userAccount.getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (account != null) {
|
||||
return account.getId();
|
||||
}
|
||||
|
||||
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are
|
||||
// tracked
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
SecurityGroup group = _securityGroupService.createSecurityGroup(this);
|
||||
if (group != null) {
|
||||
SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponse(group);
|
||||
response.setResponseName(getCommandName());
|
||||
this.setResponseObject(response);
|
||||
} else {
|
||||
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create security group");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -29,33 +29,33 @@ import com.cloud.api.response.InstanceGroupResponse;
|
||||
import com.cloud.user.UserContext;
|
||||
import com.cloud.vm.InstanceGroup;
|
||||
|
||||
@Implementation(description="Creates a vm group", responseObject=InstanceGroupResponse.class)
|
||||
public class CreateVMGroupCmd extends BaseCmd{
|
||||
@Implementation(description = "Creates a vm group", responseObject = InstanceGroupResponse.class)
|
||||
public class CreateVMGroupCmd extends BaseCmd {
|
||||
public static final Logger s_logger = Logger.getLogger(CreateVMGroupCmd.class.getName());
|
||||
|
||||
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;
|
||||
|
||||
@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;
|
||||
|
||||
@IdentityMapper(entityTableName="domain")
|
||||
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of account owning the instance group")
|
||||
@IdentityMapper(entityTableName = "domain")
|
||||
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "the domain ID of account owning the instance group")
|
||||
private Long domainId;
|
||||
|
||||
@IdentityMapper(entityTableName="projects")
|
||||
@Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="The project of the instance group")
|
||||
|
||||
@IdentityMapper(entityTableName = "projects")
|
||||
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "The project of the instance group")
|
||||
private Long projectId;
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////////// Accessors ///////////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////////// Accessors ///////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
public String getGroupName() {
|
||||
return groupName;
|
||||
@ -68,32 +68,32 @@ public class CreateVMGroupCmd extends BaseCmd{
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
|
||||
public Long getProjectId() {
|
||||
return projectId;
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
/////////////// API Implementation///////////////////
|
||||
/////////////////////////////////////////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
// ///////////// API Implementation///////////////////
|
||||
// ///////////////////////////////////////////////////
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return s_name;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public long getEntityOwnerId() {
|
||||
Long accountId = finalyzeAccountId(accountName, domainId, projectId, true);
|
||||
if (accountId == null) {
|
||||
return UserContext.current().getCaller().getId();
|
||||
}
|
||||
|
||||
|
||||
return accountId;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void execute(){
|
||||
public void execute() {
|
||||
InstanceGroup result = _userVmService.createVmGroup(this);
|
||||
if (result != null) {
|
||||
InstanceGroupResponse response = _responseGenerator.createInstanceGroupResponse(result);
|
||||
|
||||
@ -68,7 +68,8 @@ public interface ConfigurationService {
|
||||
* Create a service offering through the API
|
||||
*
|
||||
* @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
|
||||
*/
|
||||
ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd);
|
||||
@ -130,13 +131,21 @@ public interface ConfigurationService {
|
||||
|
||||
/**
|
||||
* Creates a new pod based on the parameters specified in the command object
|
||||
* @param zoneId TODO
|
||||
* @param name TODO
|
||||
* @param startIp TODO
|
||||
* @param endIp TODO
|
||||
* @param gateway TODO
|
||||
* @param netmask TODO
|
||||
* @param allocationState TODO
|
||||
*
|
||||
* @param zoneId
|
||||
* TODO
|
||||
* @param name
|
||||
* TODO
|
||||
* @param startIp
|
||||
* TODO
|
||||
* @param endIp
|
||||
* TODO
|
||||
* @param gateway
|
||||
* TODO
|
||||
* @param netmask
|
||||
* TODO
|
||||
* @param allocationState
|
||||
* TODO
|
||||
* @return the new pod if successful, null otherwise
|
||||
* @throws
|
||||
* @throws
|
||||
@ -188,12 +197,14 @@ public interface ConfigurationService {
|
||||
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
|
||||
*
|
||||
* @param userId
|
||||
* @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)
|
||||
* @param zoneId
|
||||
* @param accountId
|
||||
|
||||
@ -18,12 +18,12 @@
|
||||
|
||||
package com.cloud.configuration;
|
||||
|
||||
public interface ResourceLimit extends Resource{
|
||||
|
||||
public Long getId();
|
||||
|
||||
public Long getMax();
|
||||
|
||||
public void setMax(Long max);
|
||||
|
||||
public interface ResourceLimit extends Resource {
|
||||
|
||||
public Long getId();
|
||||
|
||||
public Long getMax();
|
||||
|
||||
public void setMax(Long max);
|
||||
|
||||
}
|
||||
|
||||
@ -84,7 +84,7 @@ public interface NetworkService {
|
||||
Integer getNetworkRate(long networkId, Long vmId);
|
||||
|
||||
Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType);
|
||||
|
||||
|
||||
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);
|
||||
@ -114,7 +114,7 @@ public interface NetworkService {
|
||||
PhysicalNetworkServiceProvider getPhysicalNetworkServiceProvider(Long providerId);
|
||||
|
||||
PhysicalNetworkServiceProvider getCreatedPhysicalNetworkServiceProvider(Long providerId);
|
||||
|
||||
|
||||
long findPhysicalNetworkId(long zoneId, String tag);
|
||||
|
||||
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);
|
||||
|
||||
PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType);
|
||||
|
||||
|
||||
Network getExclusiveGuestNetwork(long zoneId);
|
||||
|
||||
|
||||
List<Pair<TrafficType, String>> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd);
|
||||
|
||||
}
|
||||
|
||||
@ -10,18 +10,22 @@ import com.cloud.user.Account;
|
||||
|
||||
public interface FirewallService {
|
||||
FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException;
|
||||
|
||||
List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd);
|
||||
|
||||
|
||||
/**
|
||||
* Revokes a firewall rule
|
||||
* @param ruleId the id of the rule to revoke.
|
||||
* Revokes a firewall rule
|
||||
*
|
||||
* @param ruleId
|
||||
* the id of the rule to revoke.
|
||||
* @return
|
||||
*/
|
||||
boolean revokeFirewallRule(long ruleId, boolean apply);
|
||||
|
||||
|
||||
boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException;
|
||||
|
||||
|
||||
FirewallRule getFirewallRule(long ruleId);
|
||||
|
||||
|
||||
boolean revokeRelatedFirewallRule(long ruleId, boolean apply);
|
||||
|
||||
}
|
||||
|
||||
@ -18,57 +18,66 @@
|
||||
package com.cloud.network.lb;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.cloud.api.commands.CreateLBStickinessPolicyCmd;
|
||||
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
|
||||
import com.cloud.api.commands.ListLBStickinessPoliciesCmd;
|
||||
|
||||
import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd;
|
||||
import com.cloud.api.commands.ListLoadBalancerRulesCmd;
|
||||
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
|
||||
import com.cloud.exception.InsufficientAddressCapacityException;
|
||||
import com.cloud.exception.NetworkRuleConflictException;
|
||||
import com.cloud.exception.ResourceUnavailableException;
|
||||
import com.cloud.network.rules.StickinessPolicy;
|
||||
import com.cloud.network.rules.LoadBalancer;
|
||||
|
||||
|
||||
import com.cloud.network.rules.StickinessPolicy;
|
||||
import com.cloud.uservm.UserVm;
|
||||
|
||||
|
||||
public interface LoadBalancingRulesService {
|
||||
/**
|
||||
* 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
|
||||
* @throws InsufficientAddressCapacityException
|
||||
* @throws InsufficientAddressCapacityException
|
||||
*/
|
||||
LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException, InsufficientAddressCapacityException;
|
||||
|
||||
LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd);
|
||||
|
||||
|
||||
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.
|
||||
* @param cmd the command specifying the stickiness method name, params (name,value pairs), policy name and description.
|
||||
* Create a stickiness policy to a load balancer from the given stickiness method name and parameters in
|
||||
* (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
|
||||
* @thows NetworkRuleConflictException
|
||||
*/
|
||||
public StickinessPolicy createLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws NetworkRuleConflictException;
|
||||
|
||||
|
||||
public boolean applyLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws ResourceUnavailableException;
|
||||
|
||||
|
||||
boolean deleteLBStickinessPolicy(long stickinessPolicyId);
|
||||
|
||||
/**
|
||||
* Assign a virtual machine, or list of virtual machines, to a load balancer.
|
||||
*/
|
||||
boolean assignToLoadBalancer(long lbRuleId, List<Long> vmIds);
|
||||
|
||||
boolean removeFromLoadBalancer(long lbRuleId, List<Long> vmIds);
|
||||
|
||||
|
||||
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
|
||||
* @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
|
||||
* @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
|
||||
* @return list of load balancers that match the criteria
|
||||
*/
|
||||
List<? extends LoadBalancer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
List<? extends StickinessPolicy> searchForLBStickinessPolicies(ListLBStickinessPoliciesCmd cmd);
|
||||
|
||||
|
||||
|
||||
List<LoadBalancingRule> listByNetworkId(long networkId);
|
||||
|
||||
|
||||
LoadBalancer findById(long LoadBalancer);
|
||||
|
||||
}
|
||||
|
||||
@ -26,50 +26,61 @@ import com.cloud.exception.ResourceUnavailableException;
|
||||
import com.cloud.user.Account;
|
||||
|
||||
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
|
||||
* 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 openFirewall TODO
|
||||
*
|
||||
* @param rule
|
||||
* 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.
|
||||
* @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;
|
||||
|
||||
|
||||
/**
|
||||
* Revokes a port forwarding rule
|
||||
* @param ruleId the id of the rule to revoke.
|
||||
* @param caller
|
||||
* Revokes a port forwarding rule
|
||||
*
|
||||
* @param ruleId
|
||||
* the id of the rule to revoke.
|
||||
* @param caller
|
||||
* @return
|
||||
*/
|
||||
boolean revokePortForwardingRule(long ruleId, boolean apply);
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd);
|
||||
|
||||
boolean applyPortForwardingRules(long ipAdddressId, Account caller) throws ResourceUnavailableException;
|
||||
|
||||
|
||||
boolean enableStaticNat(long ipAddressId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException;
|
||||
|
||||
|
||||
PortForwardingRule getPortForwardigRule(long ruleId);
|
||||
|
||||
FirewallRule getFirewallRule(long ruleId);
|
||||
|
||||
|
||||
StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException;
|
||||
|
||||
|
||||
boolean revokeStaticNatRule(long ruleId, boolean apply);
|
||||
|
||||
|
||||
boolean applyStaticNatRules(long ipAdddressId, Account caller) throws ResourceUnavailableException;
|
||||
|
||||
|
||||
StaticNatRule buildStaticNatRule(FirewallRule rule);
|
||||
|
||||
|
||||
List<String> getSourceCidrs(long ruleId);
|
||||
|
||||
boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException;
|
||||
|
||||
boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException;
|
||||
|
||||
}
|
||||
|
||||
@ -22,29 +22,29 @@ import com.cloud.network.Networks.TrafficType;
|
||||
|
||||
/**
|
||||
* Describes network offering
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface NetworkOffering {
|
||||
|
||||
|
||||
public enum Availability {
|
||||
Required,
|
||||
Optional
|
||||
}
|
||||
|
||||
|
||||
public enum State {
|
||||
Disabled,
|
||||
Enabled
|
||||
}
|
||||
|
||||
|
||||
public final static String SystemPublicNetwork = "System-Public-Network";
|
||||
public final static String SystemControlNetwork = "System-Control-Network";
|
||||
public final static String SystemManagementNetwork = "System-Management-Network";
|
||||
public final static String SystemStorageNetwork = "System-Storage-Network";
|
||||
|
||||
|
||||
public final static String DefaultSharedNetworkOfferingWithSGService = "DefaultSharedNetworkOfferingWithSGService";
|
||||
public final static String DefaultIsolatedNetworkOfferingWithSourceNatService = "DefaultIsolatedNetworkOfferingWithSourceNatService";
|
||||
public final static String DefaultSharedNetworkOffering = "DefaultSharedNetworkOffering";
|
||||
public final static String DefaultIsolatedNetworkOffering= "DefaultIsolatedNetworkOffering";
|
||||
public final static String DefaultIsolatedNetworkOffering = "DefaultIsolatedNetworkOffering";
|
||||
public final static String DefaultSharedEIPandELBNetworkOffering = "DefaultSharedNetscalerEIPandELBNetworkOffering";
|
||||
|
||||
long getId();
|
||||
@ -53,32 +53,32 @@ public interface NetworkOffering {
|
||||
* @return name for the network offering.
|
||||
*/
|
||||
String getName();
|
||||
|
||||
|
||||
/**
|
||||
* @return text to display to the end user.
|
||||
*/
|
||||
String getDisplayText();
|
||||
|
||||
|
||||
/**
|
||||
* @return the rate in megabits per sec to which a VM's network interface is throttled to
|
||||
*/
|
||||
Integer getRateMbps();
|
||||
|
||||
|
||||
/**
|
||||
* @return the rate megabits per sec to which a VM's multicast&broadcast traffic is throttled to
|
||||
*/
|
||||
Integer getMulticastRateMbps();
|
||||
|
||||
|
||||
TrafficType getTrafficType();
|
||||
|
||||
|
||||
boolean getSpecifyVlan();
|
||||
|
||||
|
||||
String getTags();
|
||||
|
||||
|
||||
boolean isDefault();
|
||||
|
||||
|
||||
boolean isSystemOnly();
|
||||
|
||||
|
||||
Availability getAvailability();
|
||||
|
||||
String getUniqueName();
|
||||
@ -86,22 +86,23 @@ public interface NetworkOffering {
|
||||
void setState(State state);
|
||||
|
||||
State getState();
|
||||
|
||||
|
||||
GuestType getGuestType();
|
||||
|
||||
|
||||
Long getServiceOfferingId();
|
||||
|
||||
boolean getDedicatedLB();
|
||||
|
||||
boolean getSharedSourceNat();
|
||||
|
||||
|
||||
boolean getRedundantRouter();
|
||||
|
||||
|
||||
boolean isConserveMode();
|
||||
|
||||
boolean getElasticIp();
|
||||
boolean getElasticIp();
|
||||
|
||||
boolean getElasticLb();
|
||||
boolean getElasticLb();
|
||||
|
||||
boolean getSpecifyIpRanges();
|
||||
|
||||
boolean getSpecifyIpRanges();
|
||||
}
|
||||
|
||||
@ -27,9 +27,9 @@ import com.cloud.exception.PermissionDeniedException;
|
||||
public interface DomainService {
|
||||
|
||||
Domain createDomain(String name, Long parentId, String networkDomain);
|
||||
|
||||
|
||||
Domain getDomain(long id);
|
||||
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
List<? extends Domain> searchForDomains(ListDomainsCmd cmd)
|
||||
throws PermissionDeniedException;
|
||||
List<? extends Domain> searchForDomains(ListDomainsCmd cmd)
|
||||
throws PermissionDeniedException;
|
||||
|
||||
List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
|
||||
throws PermissionDeniedException;
|
||||
|
||||
List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
|
||||
throws PermissionDeniedException;
|
||||
}
|
||||
|
||||
@ -26,13 +26,18 @@ import com.cloud.domain.Domain;
|
||||
import com.cloud.exception.ResourceAllocationException;
|
||||
|
||||
public interface ResourceLimitService {
|
||||
|
||||
|
||||
/**
|
||||
* 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 resourceType TODO
|
||||
* @param max TODO
|
||||
*
|
||||
* @param accountId
|
||||
* TODO
|
||||
* @param domainId
|
||||
* TODO
|
||||
* @param resourceType
|
||||
* TODO
|
||||
* @param max
|
||||
* TODO
|
||||
*
|
||||
* @return the updated/created resource limit
|
||||
*/
|
||||
@ -40,26 +45,36 @@ public interface ResourceLimitService {
|
||||
|
||||
/**
|
||||
* Updates an existing resource count details for the account/domain
|
||||
* @param accountId TODO
|
||||
* @param domainId TODO
|
||||
* @param typeId TODO
|
||||
*
|
||||
* @param accountId
|
||||
* TODO
|
||||
* @param domainId
|
||||
* TODO
|
||||
* @param typeId
|
||||
* TODO
|
||||
* @return the updated/created resource counts
|
||||
*/
|
||||
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.
|
||||
* @param id TODO
|
||||
* @param accountId TODO
|
||||
* @param domainId TODO
|
||||
* @param type TODO
|
||||
*
|
||||
* @param id
|
||||
* TODO
|
||||
* @param accountId
|
||||
* TODO
|
||||
* @param domainId
|
||||
* TODO
|
||||
* @param type
|
||||
* TODO
|
||||
* @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);
|
||||
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @param account
|
||||
* @param type
|
||||
* @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
|
||||
* up the domain hierarchy
|
||||
*
|
||||
* @param account
|
||||
* @param type
|
||||
* @return resource limit
|
||||
@ -77,31 +93,37 @@ public interface ResourceLimitService {
|
||||
|
||||
/**
|
||||
* Increments the resource count
|
||||
*
|
||||
* @param accountId
|
||||
* @param type
|
||||
* @param delta
|
||||
*/
|
||||
public void incrementResourceCount(long accountId, ResourceType type, Long...delta);
|
||||
|
||||
public void incrementResourceCount(long accountId, ResourceType type, Long... delta);
|
||||
|
||||
/**
|
||||
* Decrements the resource count
|
||||
*
|
||||
* @param accountId
|
||||
* @param type
|
||||
* @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
|
||||
*
|
||||
* @param account
|
||||
* @param type
|
||||
* @param count the number of resources being allocated, count will be added to current allocation and compared against maximum allowed allocation
|
||||
* @throws ResourceAllocationException
|
||||
* @param count
|
||||
* 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
|
||||
*
|
||||
* @param account
|
||||
* @param type
|
||||
* @return count of resources
|
||||
|
||||
@ -28,100 +28,101 @@ import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="resource_limit")
|
||||
@Table(name = "resource_limit")
|
||||
public class ResourceLimitVO implements ResourceLimit {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
@Column(name="id")
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private Long id = null;
|
||||
|
||||
@Column(name="type")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private ResourceCount.ResourceType type;
|
||||
|
||||
@Column(name="domain_id")
|
||||
|
||||
@Column(name = "type")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private ResourceCount.ResourceType type;
|
||||
|
||||
@Column(name = "domain_id")
|
||||
private Long domainId;
|
||||
|
||||
@Column(name="account_id")
|
||||
|
||||
@Column(name = "account_id")
|
||||
private Long accountId;
|
||||
|
||||
@Column(name="max")
|
||||
private Long max;
|
||||
|
||||
public ResourceLimitVO() {}
|
||||
|
||||
public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) {
|
||||
this.type = type;
|
||||
this.max = max;
|
||||
|
||||
if (ownerType == ResourceOwnerType.Account) {
|
||||
|
||||
@Column(name = "max")
|
||||
private Long max;
|
||||
|
||||
public ResourceLimitVO() {
|
||||
}
|
||||
|
||||
public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) {
|
||||
this.type = type;
|
||||
this.max = max;
|
||||
|
||||
if (ownerType == ResourceOwnerType.Account) {
|
||||
this.accountId = ownerId;
|
||||
} else if (ownerType == ResourceOwnerType.Domain) {
|
||||
this.domainId = ownerId;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(ResourceCount.ResourceType type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public Long getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getMax() {
|
||||
return max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMax(Long max) {
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
@Override
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(ResourceCount.ResourceType type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public Long getDomainId() {
|
||||
return domainId;
|
||||
}
|
||||
|
||||
public Long getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getMax() {
|
||||
return max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMax(Long max) {
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getOwnerId() {
|
||||
if (accountId != null) {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return domainId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceOwnerType getResourceOwnerType() {
|
||||
if (accountId != null) {
|
||||
return ResourceOwnerType.Account;
|
||||
} else {
|
||||
return ResourceOwnerType.Domain;
|
||||
}
|
||||
}
|
||||
|
||||
public void setDomainId(Long domainId) {
|
||||
this.domainId = domainId;
|
||||
@Override
|
||||
public ResourceOwnerType getResourceOwnerType() {
|
||||
if (accountId != null) {
|
||||
return ResourceOwnerType.Account;
|
||||
} else {
|
||||
return ResourceOwnerType.Domain;
|
||||
}
|
||||
}
|
||||
|
||||
public void setAccountId(Long accountId) {
|
||||
this.accountId = accountId;
|
||||
}
|
||||
public void setDomainId(Long domainId) {
|
||||
this.domainId = domainId;
|
||||
}
|
||||
|
||||
public void setAccountId(Long accountId) {
|
||||
this.accountId = accountId;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,4 +1,5 @@
|
||||
/**
|
||||
|
||||
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
|
||||
*
|
||||
* 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_pluggableServiceCommands = null;
|
||||
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"));
|
||||
|
||||
static {
|
||||
@ -172,45 +173,45 @@ public class ApiServer implements HttpRequestHandler {
|
||||
public Properties get_apiCommands() {
|
||||
return _apiCommands;
|
||||
}
|
||||
|
||||
public static boolean isPluggableServiceCommand(String cmdClassName){
|
||||
if(s_pluggableServiceCommands != null){
|
||||
if(s_pluggableServiceCommands.contains(cmdClassName)){
|
||||
|
||||
public static boolean isPluggableServiceCommand(String cmdClassName) {
|
||||
if (s_pluggableServiceCommands != null) {
|
||||
if (s_pluggableServiceCommands.contains(cmdClassName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String[] getPluggableServicesApiConfigs(){
|
||||
private String[] getPluggableServicesApiConfigs() {
|
||||
List<String> pluggableServicesApiConfigs = new ArrayList<String>();
|
||||
|
||||
|
||||
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
|
||||
List<PluggableService> services = locator.getAllPluggableServices();
|
||||
for(PluggableService service : services){
|
||||
for (PluggableService service : services) {
|
||||
pluggableServicesApiConfigs.add(service.getPropertiesFile());
|
||||
}
|
||||
return pluggableServicesApiConfigs.toArray(new String[0]);
|
||||
}
|
||||
|
||||
private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig){
|
||||
try{
|
||||
if(_apiCommands == null){
|
||||
|
||||
private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig) {
|
||||
try {
|
||||
if (_apiCommands == null) {
|
||||
_apiCommands = new Properties();
|
||||
}
|
||||
Properties preProcessedCommands = new Properties();
|
||||
if (apiConfig != null) {
|
||||
for (String configFile : apiConfig) {
|
||||
File commandsFile = PropertiesUtil.findConfigFile(configFile);
|
||||
if(commandsFile != null){
|
||||
try{
|
||||
if (commandsFile != null) {
|
||||
try {
|
||||
preProcessedCommands.load(new FileInputStream(commandsFile));
|
||||
}catch (FileNotFoundException fnfex) {
|
||||
//in case of a file within a jar in classpath, try to open stream using url
|
||||
} catch (FileNotFoundException fnfex) {
|
||||
// in case of a file within a jar in classpath, try to open stream using url
|
||||
InputStream stream = PropertiesUtil.openStreamFromURL(configFile);
|
||||
if(stream != null){
|
||||
if (stream != null) {
|
||||
preProcessedCommands.load(stream);
|
||||
}else{
|
||||
} else {
|
||||
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[] commandParts = preProcessedCommand.split(";");
|
||||
_apiCommands.put(key, commandParts[0]);
|
||||
|
||||
if(pluggableServicesConfig){
|
||||
|
||||
if (pluggableServicesConfig) {
|
||||
s_pluggableServiceCommands.add(commandParts[0]);
|
||||
}
|
||||
|
||||
|
||||
if (commandParts.length > 1) {
|
||||
try {
|
||||
short cmdPermissions = Short.parseShort(commandParts[1]);
|
||||
@ -245,7 +246,7 @@ public class ApiServer implements HttpRequestHandler {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
s_allCommands.addAll(s_adminCommands);
|
||||
s_allCommands.addAll(s_resourceDomainAdminCommands);
|
||||
s_allCommands.addAll(s_userCommands);
|
||||
@ -257,13 +258,13 @@ public class ApiServer implements HttpRequestHandler {
|
||||
s_logger.error("Exception loading properties file", ioex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void init(String[] apiConfig) {
|
||||
BaseCmd.setComponents(new ApiResponseHelper());
|
||||
BaseListCmd.configure();
|
||||
processConfigFiles(apiConfig, false);
|
||||
|
||||
//get commands for all pluggable services
|
||||
|
||||
// get commands for all pluggable services
|
||||
String[] pluggableServicesApiConfigs = getPluggableServicesApiConfigs();
|
||||
processConfigFiles(pluggableServicesApiConfigs, true);
|
||||
|
||||
@ -284,9 +285,9 @@ public class ApiServer implements HttpRequestHandler {
|
||||
ConfigurationVO apiPortConfig = values.get(0);
|
||||
apiPort = Integer.parseInt(apiPortConfig.getValue());
|
||||
}
|
||||
|
||||
|
||||
encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key()));
|
||||
|
||||
|
||||
String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key());
|
||||
if (jsonType != null) {
|
||||
jsonContentType = jsonType;
|
||||
@ -333,7 +334,8 @@ public class ApiServer implements HttpRequestHandler {
|
||||
if ("response".equalsIgnoreCase(paramValue[0])) {
|
||||
responseType = paramValue[1];
|
||||
} 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
|
||||
parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] });
|
||||
}
|
||||
@ -501,7 +503,7 @@ public class ApiServer implements HttpRequestHandler {
|
||||
SerializationContext.current().setUuidTranslation(true);
|
||||
return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objectId, objectEntityTable);
|
||||
}
|
||||
|
||||
|
||||
SerializationContext.current().setUuidTranslation(true);
|
||||
return ApiResponseSerializer.toSerializedString(asyncCmd.getResponse(jobId), asyncCmd.getResponseType());
|
||||
} else {
|
||||
@ -512,9 +514,9 @@ public class ApiServer implements HttpRequestHandler {
|
||||
if (cmdObj instanceof BaseListCmd) {
|
||||
buildAsyncListResponse((BaseListCmd) cmdObj, caller);
|
||||
}
|
||||
|
||||
|
||||
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(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")){
|
||||
* 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(" "); 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
|
||||
* (pair.first().equals("jobid")){ // Its an async job so report the jobid auditTrailSb.append(" ");
|
||||
* auditTrailSb.append(pair.first()); auditTrailSb.append("="); auditTrailSb.append(pair.second()); } } }
|
||||
@ -619,7 +624,7 @@ public class ApiServer implements HttpRequestHandler {
|
||||
|
||||
String signatureVersion = null;
|
||||
String expires = null;
|
||||
|
||||
|
||||
for (String paramName : parameterNames) {
|
||||
// parameters come as name/value pairs in the form String/String[]
|
||||
String paramValue = ((String[]) requestParameters.get(paramName))[0];
|
||||
@ -631,11 +636,11 @@ public class ApiServer implements HttpRequestHandler {
|
||||
apiKey = paramValue;
|
||||
}
|
||||
else if ("signatureversion".equalsIgnoreCase(paramName)) {
|
||||
signatureVersion = paramValue;
|
||||
signatureVersion = paramValue;
|
||||
} else if ("expires".equalsIgnoreCase(paramName)) {
|
||||
expires = paramValue;
|
||||
expires = paramValue;
|
||||
}
|
||||
|
||||
|
||||
if (unsignedRequest == null) {
|
||||
unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
|
||||
} else {
|
||||
@ -653,27 +658,27 @@ public class ApiServer implements HttpRequestHandler {
|
||||
}
|
||||
|
||||
Date expiresTS = null;
|
||||
if("3".equals(signatureVersion)){
|
||||
// New signature authentication. Check for expire parameter and its validity
|
||||
if(expires == null){
|
||||
s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey);
|
||||
return false;
|
||||
}
|
||||
synchronized (_dateFormat) {
|
||||
try{
|
||||
expiresTS = _dateFormat.parse(expires);
|
||||
} catch (ParseException pe){
|
||||
s_logger.info("Incorrect date format for Expires parameter", pe);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Date now = new Date(System.currentTimeMillis());
|
||||
if(expiresTS.before(now)){
|
||||
s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
|
||||
return false;
|
||||
}
|
||||
if ("3".equals(signatureVersion)) {
|
||||
// New signature authentication. Check for expire parameter and its validity
|
||||
if (expires == null) {
|
||||
s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey);
|
||||
return false;
|
||||
}
|
||||
synchronized (_dateFormat) {
|
||||
try {
|
||||
expiresTS = _dateFormat.parse(expires);
|
||||
} catch (ParseException pe) {
|
||||
s_logger.info("Incorrect date format for Expires parameter", pe);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Date now = new Date(System.currentTimeMillis());
|
||||
if (expiresTS.before(now)) {
|
||||
s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
|
||||
txn.close();
|
||||
User user = null;
|
||||
@ -861,7 +866,8 @@ public class ApiServer implements HttpRequestHandler {
|
||||
|
||||
// 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
|
||||
// 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
|
||||
static class ListenerThread extends Thread {
|
||||
private HttpService _httpService = null;
|
||||
@ -970,25 +976,25 @@ public class ApiServer implements HttpRequestHandler {
|
||||
if (errorCode == BaseCmd.UNSUPPORTED_ACTION_ERROR || apiCommandParams == null || apiCommandParams.isEmpty()) {
|
||||
responseName = "errorresponse";
|
||||
} else {
|
||||
Object cmdObj = apiCommandParams.get("command");
|
||||
//cmd name can be null when "command" parameter is missing in the request
|
||||
if (cmdObj != null) {
|
||||
String cmdName = ((String[])cmdObj) [0];
|
||||
cmdClassName = _apiCommands.getProperty(cmdName);
|
||||
Object cmdObj = apiCommandParams.get("command");
|
||||
// cmd name can be null when "command" parameter is missing in the request
|
||||
if (cmdObj != null) {
|
||||
String cmdName = ((String[]) cmdObj)[0];
|
||||
cmdClassName = _apiCommands.getProperty(cmdName);
|
||||
if (cmdClassName != null) {
|
||||
Class<?> claz = Class.forName(cmdClassName);
|
||||
responseName = ((BaseCmd) claz.newInstance()).getCommandName();
|
||||
} else {
|
||||
responseName = "errorresponse";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ExceptionResponse apiResponse = new ExceptionResponse();
|
||||
apiResponse.setErrorCode(errorCode);
|
||||
apiResponse.setErrorText(errorText);
|
||||
apiResponse.setResponseName(responseName);
|
||||
|
||||
|
||||
SerializationContext.current().setUuidTranslation(true);
|
||||
responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType);
|
||||
|
||||
|
||||
@ -48,66 +48,75 @@ import com.cloud.utils.component.Manager;
|
||||
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 {
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @param name
|
||||
* @param cpu
|
||||
* @param ramSize
|
||||
* @param speed
|
||||
* @param displayText
|
||||
* @param localStorageRequired
|
||||
* @param offerHA
|
||||
* @param domainId
|
||||
* @param hostTag
|
||||
* @param networkRate TODO
|
||||
* @param id
|
||||
* @param useVirtualNetwork
|
||||
* @return ID
|
||||
*/
|
||||
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);
|
||||
|
||||
/**
|
||||
* Creates a new disk offering
|
||||
* @param domainId
|
||||
* @param name
|
||||
* @param description
|
||||
* @param numGibibytes
|
||||
* @param tags
|
||||
* @param isCustomized
|
||||
* @return newly created disk offering
|
||||
*/
|
||||
DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @param name
|
||||
* @param cpu
|
||||
* @param ramSize
|
||||
* @param speed
|
||||
* @param displayText
|
||||
* @param localStorageRequired
|
||||
* @param offerHA
|
||||
* @param domainId
|
||||
* @param hostTag
|
||||
* @param networkRate
|
||||
* TODO
|
||||
* @param id
|
||||
* @param useVirtualNetwork
|
||||
* @return ID
|
||||
*/
|
||||
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);
|
||||
|
||||
/**
|
||||
* Creates a new disk offering
|
||||
*
|
||||
* @param domainId
|
||||
* @param name
|
||||
* @param description
|
||||
* @param numGibibytes
|
||||
* @param tags
|
||||
* @param isCustomized
|
||||
* @return newly created disk offering
|
||||
*/
|
||||
DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized);
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @param userId
|
||||
* @param zoneName
|
||||
* @param dns1
|
||||
@ -116,108 +125,129 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
|
||||
* @param internalDns2
|
||||
* @param zoneType
|
||||
* @param allocationState
|
||||
* @param networkDomain TODO
|
||||
* @param isSecurityGroupEnabled TODO
|
||||
* @param networkDomain
|
||||
* TODO
|
||||
* @param isSecurityGroupEnabled
|
||||
* TODO
|
||||
* @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.
|
||||
* @param userId
|
||||
* @param vlanDbId
|
||||
* @return success/failure
|
||||
*/
|
||||
boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId);
|
||||
/**
|
||||
* Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated
|
||||
* IP addresses.
|
||||
*
|
||||
* @param userId
|
||||
* @param vlanDbId
|
||||
* @return success/failure
|
||||
*/
|
||||
boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId);
|
||||
|
||||
|
||||
/**
|
||||
* Adds/deletes private IPs
|
||||
* @param add - either true or false
|
||||
* @param podId
|
||||
* @param startIP
|
||||
* @param endIP
|
||||
* @return Message to display to user
|
||||
* @throws if 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);
|
||||
/**
|
||||
* Adds/deletes private IPs
|
||||
*
|
||||
* @param add
|
||||
* - either true or false
|
||||
* @param podId
|
||||
* @param startIP
|
||||
* @param endIP
|
||||
* @return Message to display to user
|
||||
* @throws if
|
||||
* unable to add private ip range
|
||||
*/
|
||||
String changePrivateIPRange(boolean add, long podId, String startIP, String endIP);
|
||||
|
||||
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)
|
||||
throws PermissionDeniedException;
|
||||
|
||||
|
||||
/**
|
||||
void checkAccess(Account caller, DataCenter zone)
|
||||
throws PermissionDeniedException;
|
||||
|
||||
void checkServiceOfferingAccess(Account caller, ServiceOffering so)
|
||||
throws PermissionDeniedException;
|
||||
|
||||
void checkDiskOfferingAccess(Account caller, DiskOffering dof)
|
||||
throws PermissionDeniedException;
|
||||
|
||||
/**
|
||||
* Creates a new network offering
|
||||
* @param name
|
||||
* @param displayText
|
||||
* @param trafficType
|
||||
* @param tags
|
||||
* @param networkRate TODO
|
||||
* @param serviceProviderMap TODO
|
||||
* @param isDefault TODO
|
||||
* @param type TODO
|
||||
* @param systemOnly TODO
|
||||
* @param serviceOfferingId
|
||||
* @param specifyIpRanges TODO
|
||||
* @param id
|
||||
* @param specifyVlan;
|
||||
* @param conserveMode;
|
||||
* @return network offering object
|
||||
*
|
||||
* @param name
|
||||
* @param displayText
|
||||
* @param trafficType
|
||||
* @param tags
|
||||
* @param networkRate
|
||||
* TODO
|
||||
* @param serviceProviderMap
|
||||
* TODO
|
||||
* @param isDefault
|
||||
* TODO
|
||||
* @param type
|
||||
* TODO
|
||||
* @param systemOnly
|
||||
* 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;
|
||||
|
||||
|
||||
HostPodVO getPod(long id);
|
||||
|
||||
|
||||
ClusterVO getCluster(long id);
|
||||
|
||||
|
||||
boolean deleteAccountSpecificVirtualRanges(long accountId);
|
||||
|
||||
|
||||
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.
|
||||
*
|
||||
* @param id
|
||||
* @param name
|
||||
* @param startIp
|
||||
* @param endIp
|
||||
* @param gateway
|
||||
* @param netmask
|
||||
* @param allocationState
|
||||
* @param allocationState
|
||||
* @return Pod
|
||||
* @throws
|
||||
* @throws
|
||||
* @throws
|
||||
* @throws
|
||||
*/
|
||||
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 checkCidrVlanOverlap(long zoneId, String cidr);
|
||||
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -26,9 +26,12 @@ import com.cloud.configuration.ResourceLimitVO;
|
||||
import com.cloud.utils.db.GenericDao;
|
||||
|
||||
public interface ResourceLimitDao extends GenericDao<ResourceLimitVO, Long> {
|
||||
|
||||
List<ResourceLimitVO> listByOwner(Long ownerId, ResourceOwnerType ownerType);
|
||||
boolean update(Long id, Long max);
|
||||
ResourceCount.ResourceType getLimitType(String type);
|
||||
ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type);
|
||||
|
||||
List<ResourceLimitVO> listByOwner(Long ownerId, ResourceOwnerType ownerType);
|
||||
|
||||
boolean update(Long id, Long max);
|
||||
|
||||
ResourceCount.ResourceType getLimitType(String type);
|
||||
|
||||
ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type);
|
||||
}
|
||||
|
||||
@ -32,23 +32,23 @@ import com.cloud.utils.db.GenericDaoBase;
|
||||
import com.cloud.utils.db.SearchBuilder;
|
||||
import com.cloud.utils.db.SearchCriteria;
|
||||
|
||||
@Local(value={ResourceLimitDao.class})
|
||||
@Local(value = { ResourceLimitDao.class })
|
||||
public class ResourceLimitDaoImpl extends GenericDaoBase<ResourceLimitVO, Long> implements ResourceLimitDao {
|
||||
private SearchBuilder<ResourceLimitVO> IdTypeSearch;
|
||||
private SearchBuilder<ResourceLimitVO> IdTypeSearch;
|
||||
|
||||
public ResourceLimitDaoImpl () {
|
||||
IdTypeSearch = createSearchBuilder();
|
||||
IdTypeSearch.and("type", IdTypeSearch.entity().getType(), SearchCriteria.Op.EQ);
|
||||
IdTypeSearch.and("domainId", IdTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
|
||||
IdTypeSearch.and("accountId", IdTypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
|
||||
IdTypeSearch.done();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourceLimitVO> listByOwner(Long ownerId, ResourceOwnerType ownerType) {
|
||||
SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create();
|
||||
|
||||
if (ownerType == ResourceOwnerType.Account) {
|
||||
public ResourceLimitDaoImpl() {
|
||||
IdTypeSearch = createSearchBuilder();
|
||||
IdTypeSearch.and("type", IdTypeSearch.entity().getType(), SearchCriteria.Op.EQ);
|
||||
IdTypeSearch.and("domainId", IdTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
|
||||
IdTypeSearch.and("accountId", IdTypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
|
||||
IdTypeSearch.done();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourceLimitVO> listByOwner(Long ownerId, ResourceOwnerType ownerType) {
|
||||
SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create();
|
||||
|
||||
if (ownerType == ResourceOwnerType.Account) {
|
||||
sc.setParameters("accountId", ownerId);
|
||||
return listBy(sc);
|
||||
} else if (ownerType == ResourceOwnerType.Domain) {
|
||||
@ -57,44 +57,43 @@ public class ResourceLimitDaoImpl extends GenericDaoBase<ResourceLimitVO, Long>
|
||||
} else {
|
||||
return new ArrayList<ResourceLimitVO>();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean update(Long id, Long max) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean update(Long id, Long max) {
|
||||
ResourceLimitVO limit = findById(id);
|
||||
if (max != null)
|
||||
limit.setMax(max);
|
||||
limit.setMax(max);
|
||||
else
|
||||
limit.setMax(new Long(-1));
|
||||
limit.setMax(new Long(-1));
|
||||
return update(id, limit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceCount.ResourceType getLimitType(String type) {
|
||||
ResourceType[] validTypes = Resource.ResourceType.values();
|
||||
|
||||
for (ResourceType validType : validTypes) {
|
||||
if (validType.getName().equals(type)) {
|
||||
return validType;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type) {
|
||||
SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create();
|
||||
|
||||
@Override
|
||||
public ResourceCount.ResourceType getLimitType(String type) {
|
||||
ResourceType[] validTypes = Resource.ResourceType.values();
|
||||
|
||||
for (ResourceType validType : validTypes) {
|
||||
if (validType.getName().equals(type)) {
|
||||
return validType;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type) {
|
||||
SearchCriteria<ResourceLimitVO> sc = IdTypeSearch.create();
|
||||
sc.setParameters("type", type);
|
||||
|
||||
if (ownerType == ResourceOwnerType.Account) {
|
||||
sc.setParameters("accountId", ownerId);
|
||||
return findOneBy(sc);
|
||||
|
||||
if (ownerType == ResourceOwnerType.Account) {
|
||||
sc.setParameters("accountId", ownerId);
|
||||
return findOneBy(sc);
|
||||
} else if (ownerType == ResourceOwnerType.Domain) {
|
||||
sc.setParameters("domainId", ownerId);
|
||||
return findOneBy(sc);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
|
||||
*
|
||||
*
|
||||
*
|
||||
* 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;
|
||||
@Inject
|
||||
ResourceManager _resourceMgr;
|
||||
@Inject
|
||||
@Inject
|
||||
IPAddressDao _ipAddressDao;
|
||||
@Inject
|
||||
VlanDao _vlanDao;
|
||||
@ -157,29 +157,29 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
NetworkOfferingDao _networkOfferingDao;
|
||||
@Inject
|
||||
AccountDao _accountDao;
|
||||
@Inject
|
||||
@Inject
|
||||
PhysicalNetworkDao _physicalNetworkDao;
|
||||
@Inject
|
||||
@Inject
|
||||
PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao;
|
||||
@Inject
|
||||
@Inject
|
||||
AccountManager _accountMgr;
|
||||
@Inject
|
||||
@Inject
|
||||
UserStatisticsDao _userStatsDao;
|
||||
@Inject
|
||||
NetworkDao _networkDao;
|
||||
@Inject
|
||||
@Inject
|
||||
DomainRouterDao _routerDao;
|
||||
@Inject
|
||||
@Inject
|
||||
LoadBalancerDao _loadBalancerDao;
|
||||
@Inject
|
||||
@Inject
|
||||
PortForwardingRulesDao _portForwardingRulesDao;
|
||||
@Inject
|
||||
@Inject
|
||||
ConfigurationDao _configDao;
|
||||
@Inject
|
||||
HostDetailsDao _hostDetailDao;
|
||||
@Inject
|
||||
@Inject
|
||||
NetworkExternalLoadBalancerDao _networkLBDao;
|
||||
@Inject
|
||||
@Inject
|
||||
NetworkServiceMapDao _ntwkSrvcProviderDao;
|
||||
@Inject
|
||||
NetworkExternalFirewallDao _networkExternalFirewallDao;
|
||||
@ -187,7 +187,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
ExternalFirewallDeviceDao _externalFirewallDeviceDao;
|
||||
@Inject
|
||||
protected HostPodDao _podDao = null;
|
||||
|
||||
|
||||
ScheduledExecutorService _executor;
|
||||
private int _externalNetworkStatsInterval;
|
||||
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) {
|
||||
|
||||
String guid;
|
||||
PhysicalNetworkVO pNetwork=null;
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName);
|
||||
Transaction txn = null;
|
||||
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," +
|
||||
" 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();
|
||||
|
||||
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder());
|
||||
if (ntwkSvcProvider == null ) {
|
||||
throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() +
|
||||
" is not enabled in the physical network: " + physicalNetworkId + "to add this device" );
|
||||
if (ntwkSvcProvider == null) {
|
||||
throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() +
|
||||
" is not enabled in the physical network: " + physicalNetworkId + "to add this device");
|
||||
} else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
|
||||
throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() +
|
||||
" is in shutdown state in the physical network: " + physicalNetworkId + "to add this device" );
|
||||
throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() +
|
||||
" is in shutdown state in the physical network: " + physicalNetworkId + "to add this device");
|
||||
}
|
||||
|
||||
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 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(),
|
||||
deviceName, capacity, dedicatedUse, inline);
|
||||
@ -300,7 +300,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
_hostDao.update(hostId, externalLoadBalancer);
|
||||
_resourceMgr.deleteHost(hostId, false, false);
|
||||
|
||||
// delete the external load balancer entry
|
||||
// delete the external load balancer entry
|
||||
_externalLoadBalancerDeviceDao.remove(lbDeviceId);
|
||||
|
||||
return true;
|
||||
@ -314,19 +314,19 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
public List<Host> listExternalLoadBalancers(long physicalNetworkId, String deviceName) {
|
||||
List<Host> lbHosts = new ArrayList<Host>();
|
||||
NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName);
|
||||
PhysicalNetworkVO pNetwork=null;
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
|
||||
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
|
||||
|
||||
|
||||
if ((pNetwork == null) || (lbNetworkDevice == null)) {
|
||||
throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid.");
|
||||
}
|
||||
|
||||
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(),
|
||||
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) {
|
||||
return null;
|
||||
return null;
|
||||
}
|
||||
|
||||
List<ExternalLoadBalancerDeviceVO> lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId,
|
||||
@ -359,7 +359,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
if (lbDeviceForNetwork != null) {
|
||||
long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId();
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId);
|
||||
assert(lbDeviceVo != null);
|
||||
assert (lbDeviceVo != null);
|
||||
return lbDeviceVo;
|
||||
}
|
||||
return null;
|
||||
@ -380,17 +380,18 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb);
|
||||
|
||||
while (retry) {
|
||||
GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock");
|
||||
GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock");
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
try {
|
||||
if (deviceMapLock.lock(120)) {
|
||||
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;
|
||||
|
||||
txn.start();
|
||||
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??
|
||||
|
||||
// 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();
|
||||
|
||||
// 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);
|
||||
_networkExternalLBDao.persist(networkLB);
|
||||
|
||||
@ -412,14 +414,16 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
tryLbProvisioning = false;
|
||||
retry = false;
|
||||
} 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) {
|
||||
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");
|
||||
throw exception;
|
||||
} 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 {
|
||||
@ -433,14 +437,16 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
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) {
|
||||
// check if LB appliance can be dynamically provisioned
|
||||
List<ExternalLoadBalancerDeviceVO> providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider);
|
||||
if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) {
|
||||
for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) {
|
||||
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());
|
||||
if (dcPrivateIp == null) {
|
||||
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 privateIf = createLbAnswer.getPrivateInterface();
|
||||
|
||||
//we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer
|
||||
String dedicatedLb = offering.getDedicatedLB()?"true":"false";
|
||||
// we have provisioned load balancer so add the appliance as cloudstack provisioned external
|
||||
// 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);
|
||||
String publicIPNetmask = publicIp.getVlanNetmask();
|
||||
String publicIPgateway = publicIp.getVlanGateway();
|
||||
@ -481,7 +489,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
String publicIP = publicIp.getAddress().toString();
|
||||
|
||||
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;
|
||||
try {
|
||||
lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource());
|
||||
@ -490,7 +498,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
}
|
||||
|
||||
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());
|
||||
managedLb.setIsManagedDevice(true);
|
||||
managedLb.setParentHostId(lbProviderDevice.getHostId());
|
||||
@ -504,7 +513,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
if (answer == null || !answer.getResult()) {
|
||||
s_logger.warn("Failed to destroy load balancer appliance created");
|
||||
} 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);
|
||||
_networkMgr.releasePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount());
|
||||
}
|
||||
@ -524,9 +534,9 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
@Override
|
||||
public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException {
|
||||
long physicalNetworkId = network.getPhysicalNetworkId();
|
||||
List<ExternalLoadBalancerDeviceVO> lbDevices =null;
|
||||
List<ExternalLoadBalancerDeviceVO> lbDevices = null;
|
||||
String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb);
|
||||
assert(provider != null);
|
||||
assert (provider != null);
|
||||
|
||||
if (dedicatedLb) {
|
||||
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
|
||||
for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) {
|
||||
if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) {
|
||||
return lbdevice;
|
||||
return lbdevice;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -547,24 +557,24 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null;
|
||||
long maxFreeCapacity = 0;
|
||||
|
||||
// loop through the LB device in the physical network and pick the one with maximum free capacity
|
||||
for (ExternalLoadBalancerDeviceVO lbdevice: lbDevices) {
|
||||
// loop through the LB device in the physical network and pick the one with maximum free capacity
|
||||
for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) {
|
||||
|
||||
// skip if device is not enabled
|
||||
// skip if device is not enabled
|
||||
if (lbdevice.getState() != LBDeviceState.Enabled) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// get the used capacity from the list of guest networks that are mapped to this load balancer
|
||||
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
|
||||
long fullCapacity = lbdevice.getCapacity();
|
||||
if (fullCapacity == 0) {
|
||||
fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default
|
||||
}
|
||||
|
||||
|
||||
long freeCapacity = fullCapacity - usedCapacity;
|
||||
if (freeCapacity > 0) {
|
||||
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
|
||||
lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free);
|
||||
if (lbDevices != null && !lbDevices.isEmpty()) {
|
||||
@ -603,7 +614,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
@DB
|
||||
protected boolean freeLoadBalancerForNetwork(Network guestConfig) {
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock");
|
||||
GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock");
|
||||
|
||||
try {
|
||||
if (deviceMapLock.lock(120)) {
|
||||
@ -619,12 +630,13 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
boolean lbCloudManaged = lbDevice.getIsManagedDevice();
|
||||
|
||||
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);
|
||||
_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();
|
||||
|
||||
if (!lbInUse && lbCloudManaged) {
|
||||
@ -669,7 +681,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
} catch (Exception exception) {
|
||||
txn.rollback();
|
||||
s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage());
|
||||
}finally {
|
||||
} finally {
|
||||
deviceMapLock.releaseRef();
|
||||
}
|
||||
|
||||
@ -680,16 +692,16 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
HostVO fwHost = null;
|
||||
|
||||
// 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")) {
|
||||
//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 {
|
||||
NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId());
|
||||
assert (fwDeviceForNetwork != null) : "Why firewall provider is not ready for the network to apply static nat rules?";
|
||||
long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId();
|
||||
ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId);
|
||||
fwHost = _hostDao.findById(fwDevice.getHostId());
|
||||
fwHost = _hostDao.findById(fwDevice.getHostId());
|
||||
}
|
||||
|
||||
return fwHost;
|
||||
@ -707,7 +719,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
nic.setState(State.Reserved);
|
||||
return _nicDao.persist(nic);
|
||||
}
|
||||
|
||||
|
||||
private NicVO getPlaceholderNic(Network network) {
|
||||
List<NicVO> guestIps = _nicDao.listByNetworkId(network.getId());
|
||||
for (NicVO guestIp : guestIps) {
|
||||
@ -730,7 +742,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
StaticNatRule rule = new StaticNatRuleImpl(fwRule, privateIp);
|
||||
StaticNatRuleTO ruleTO = new StaticNatRuleTO(rule, vlan.getVlanTag(), publicIp, privateIp);
|
||||
staticNatRules.add(ruleTO);
|
||||
|
||||
|
||||
applyStaticNatRules(staticNatRules, network, firewallHost.getId());
|
||||
}
|
||||
|
||||
@ -765,7 +777,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
return true;
|
||||
}
|
||||
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
|
||||
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");
|
||||
return true;
|
||||
@ -805,7 +817,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
if (mapping == null) {
|
||||
// Acquire a new guest IP address and save it as the load balancing IP address
|
||||
String loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null);
|
||||
|
||||
|
||||
if (loadBalancingIpAddress == null) {
|
||||
String msg = "Ran out of guest IP addresses.";
|
||||
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
|
||||
loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId());
|
||||
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
|
||||
mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId());
|
||||
_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());
|
||||
} else {
|
||||
loadBalancingIpNic = _nicDao.findById(mapping.getNicId());
|
||||
@ -832,7 +845,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
// Find the NIC that the mapping refers to
|
||||
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());
|
||||
|
||||
// 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) {
|
||||
int numLoadBalancersForCommand = loadBalancersToApply.size();
|
||||
int numLoadBalancersForCommand = loadBalancersToApply.size();
|
||||
LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
|
||||
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand);
|
||||
long guestVlanTag = Integer.parseInt(network.getBroadcastUri().getHost());
|
||||
@ -899,7 +913,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig);
|
||||
if (lbDeviceVO == null) {
|
||||
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;
|
||||
}
|
||||
|
||||
@ -923,7 +937,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
}
|
||||
} else {
|
||||
// get the self-ip used by the load balancer
|
||||
NicVO selfipNic = getPlaceholderNic(guestConfig);
|
||||
NicVO selfipNic = getPlaceholderNic(guestConfig);
|
||||
selfIp = selfipNic.getIp4Address();
|
||||
}
|
||||
|
||||
@ -946,7 +960,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
savePlaceholderNic(guestConfig, selfIp);
|
||||
} else {
|
||||
// release the self-ip obtained from guest network
|
||||
NicVO selfipNic = getPlaceholderNic(guestConfig);
|
||||
NicVO selfipNic = getPlaceholderNic(guestConfig);
|
||||
_nicDao.remove(selfipNic.getId());
|
||||
|
||||
// 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 {
|
||||
super.configure(name, params);
|
||||
_externalNetworkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ExternalNetworkStatsInterval.key()), 300);
|
||||
if (_externalNetworkStatsInterval > 0){
|
||||
if (_externalNetworkStatsInterval > 0) {
|
||||
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ExternalNetworkMonitor"));
|
||||
}
|
||||
|
||||
@ -981,7 +995,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
|
||||
@Override
|
||||
public boolean start() {
|
||||
if (_externalNetworkStatsInterval > 0){
|
||||
if (_externalNetworkStatsInterval > 0) {
|
||||
_executor.scheduleAtFixedRate(new ExternalLoadBalancerDeviceNetworkUsageTask(), _externalNetworkStatsInterval, _externalNetworkStatsInterval, TimeUnit.SECONDS);
|
||||
}
|
||||
return true;
|
||||
@ -1026,17 +1040,17 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
}
|
||||
Map<Long, ExternalNetworkResourceUsageAnswer> lbDeviceUsageAnswerMap = new HashMap<Long, ExternalNetworkResourceUsageAnswer>();
|
||||
List<Long> accountsProcessed = new ArrayList<Long>();
|
||||
|
||||
|
||||
for (DomainRouterVO domainRouter : domainRoutersInZone) {
|
||||
long accountId = domainRouter.getAccountId();
|
||||
|
||||
if(accountsProcessed.contains(new Long(accountId))){
|
||||
if(s_logger.isTraceEnabled()){
|
||||
|
||||
if (accountsProcessed.contains(new Long(accountId))) {
|
||||
if (s_logger.isTraceEnabled()) {
|
||||
s_logger.trace("Networks for Account " + accountId + " are already processed for external network usage, so skipping usage check.");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
long zoneId = zone.getId();
|
||||
|
||||
List<NetworkVO> networksForAccount = _networkDao.listBy(accountId, zoneId, Network.GuestType.Isolated);
|
||||
@ -1050,7 +1064,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
continue;
|
||||
}
|
||||
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
|
||||
if (lbDeviceVO == null) {
|
||||
continue;
|
||||
}
|
||||
@ -1060,7 +1074,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
|
||||
if (externalLoadBalancer != null) {
|
||||
Long lbDeviceId = new Long(externalLoadBalancer.getId());
|
||||
if(!lbDeviceUsageAnswerMap.containsKey(lbDeviceId)){
|
||||
if (!lbDeviceUsageAnswerMap.containsKey(lbDeviceId)) {
|
||||
ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand();
|
||||
lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd);
|
||||
if (lbAnswer == null || !lbAnswer.getResult()) {
|
||||
@ -1070,9 +1084,9 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
continue;
|
||||
}
|
||||
lbDeviceUsageAnswerMap.put(lbDeviceId, lbAnswer);
|
||||
}else{
|
||||
if(s_logger.isTraceEnabled()){
|
||||
s_logger.trace("Reusing usage Answer for device id "+ lbDeviceId + "for Network " + network.getId());
|
||||
} else {
|
||||
if (s_logger.isTraceEnabled()) {
|
||||
s_logger.trace("Reusing usage Answer for device id " + lbDeviceId + "for Network " + network.getId());
|
||||
}
|
||||
lbAnswer = lbDeviceUsageAnswerMap.get(lbDeviceId);
|
||||
}
|
||||
@ -1090,7 +1104,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
|
||||
manageStatsEntries(false, accountId, zoneId, network, externalLoadBalancer, lbAnswer);
|
||||
}
|
||||
|
||||
|
||||
accountsProcessed.add(new Long(accountId));
|
||||
}
|
||||
}
|
||||
@ -1102,23 +1116,23 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
long oldCurrentBytesSent = userStats.getCurrentBytesSent();
|
||||
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() + ".";
|
||||
|
||||
|
||||
userStats.setCurrentBytesSent(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.setCurrentBytesReceived(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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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) {
|
||||
HostVO host = _hostDao.findById(hostId);
|
||||
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);
|
||||
NetworkVO network = _networkDao.findById(networkId);
|
||||
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 newCurrentBytesReceived = 0;
|
||||
|
||||
|
||||
if (publicIp != null) {
|
||||
long[] bytesSentAndReceived = null;
|
||||
statsEntryIdentifier += ", public IP: " + publicIp;
|
||||
|
||||
|
||||
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
|
||||
InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp);
|
||||
|
||||
|
||||
if (mapping != null) {
|
||||
NicVO nic = _nicDao.findById(mapping.getNicId());
|
||||
String loadBalancingIpAddress = nic.getIp4Address();
|
||||
bytesSentAndReceived = answer.ipBytes.get(loadBalancingIpAddress);
|
||||
|
||||
|
||||
if (bytesSentAndReceived != null) {
|
||||
bytesSentAndReceived[0] = 0;
|
||||
}
|
||||
@ -1160,7 +1174,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
} else {
|
||||
bytesSentAndReceived = answer.ipBytes.get(publicIp);
|
||||
}
|
||||
|
||||
|
||||
if (bytesSentAndReceived == null) {
|
||||
s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp);
|
||||
} else {
|
||||
@ -1174,17 +1188,17 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
return true;
|
||||
} else {
|
||||
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) {
|
||||
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 {
|
||||
newCurrentBytesSent += bytesSentAndReceived[0];
|
||||
newCurrentBytesReceived += bytesSentAndReceived[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
UserStatisticsVO userStats;
|
||||
try {
|
||||
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.
|
||||
* 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,
|
||||
HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) {
|
||||
HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) {
|
||||
String accountErrorMsg = "Failed to update external network stats entry. Details: account ID = " + accountId;
|
||||
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
|
||||
try {
|
||||
@ -1390,4 +1405,5 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
|
||||
}
|
||||
return new DeleteHostAnswer(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -35,7 +35,6 @@ import com.cloud.exception.ConcurrentOperationException;
|
||||
import com.cloud.exception.InsufficientAddressCapacityException;
|
||||
import com.cloud.exception.InsufficientCapacityException;
|
||||
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
|
||||
import com.cloud.exception.InvalidParameterValueException;
|
||||
import com.cloud.exception.ResourceUnavailableException;
|
||||
import com.cloud.hypervisor.Hypervisor.HypervisorType;
|
||||
import com.cloud.network.Network.Capability;
|
||||
@ -73,11 +72,14 @@ public interface NetworkManager extends NetworkService {
|
||||
* @param owner
|
||||
* @param type
|
||||
* @param networkId
|
||||
* @param requestedIp TODO
|
||||
* @param allocatedBy TODO
|
||||
* @param requestedIp
|
||||
* TODO
|
||||
* @param allocatedBy
|
||||
* TODO
|
||||
* @return
|
||||
* @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 prepare(VirtualMachineProfile<? extends VMInstanceVO> profile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException,
|
||||
ResourceUnavailableException;
|
||||
ResourceUnavailableException;
|
||||
|
||||
void release(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, boolean forced);
|
||||
|
||||
@ -144,7 +146,7 @@ public interface NetworkManager extends NetworkService {
|
||||
String getNextAvailableMacAddressInNetwork(long networkConfigurationId) throws InsufficientAddressCapacityException;
|
||||
|
||||
boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError) throws ResourceUnavailableException;
|
||||
|
||||
|
||||
public boolean validateRule(FirewallRule rule);
|
||||
|
||||
List<? extends RemoteAccessVPNServiceProvider> getRemoteAccessVpnElements();
|
||||
@ -154,7 +156,7 @@ public interface NetworkManager extends NetworkService {
|
||||
List<? extends Vlan> listPodVlans(long podId);
|
||||
|
||||
Pair<NetworkGuru, NetworkVO> implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException,
|
||||
InsufficientCapacityException;
|
||||
InsufficientCapacityException;
|
||||
|
||||
List<NetworkVO> listNetworksUsedByVm(long vmId, boolean isSystem);
|
||||
|
||||
@ -169,7 +171,8 @@ public interface NetworkManager extends NetworkService {
|
||||
|
||||
/**
|
||||
* @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.
|
||||
* @param userId
|
||||
* @param accountId
|
||||
@ -179,7 +182,7 @@ public interface NetworkManager extends NetworkService {
|
||||
* @throws
|
||||
*/
|
||||
boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network networkToAssociateWith) throws InsufficientCapacityException, ConcurrentOperationException,
|
||||
ResourceUnavailableException;
|
||||
ResourceUnavailableException;
|
||||
|
||||
Nic getNicInNetwork(long vmId, long networkId);
|
||||
|
||||
@ -252,50 +255,50 @@ public interface NetworkManager extends NetworkService {
|
||||
|
||||
Long getPhysicalNetworkId(Network network);
|
||||
|
||||
boolean getAllowSubdomainAccessGlobal();
|
||||
|
||||
boolean isProviderForNetwork(Provider provider, long networkId);
|
||||
|
||||
boolean isProviderForNetworkOffering(Provider provider, long networkOfferingId);
|
||||
boolean getAllowSubdomainAccessGlobal();
|
||||
|
||||
void canProviderSupportServices(Map<Provider, Set<Service>> providersMap);
|
||||
boolean isProviderForNetwork(Provider provider, long networkId);
|
||||
|
||||
PhysicalNetworkServiceProvider addDefaultSecurityGroupProviderToPhysicalNetwork(
|
||||
long physicalNetworkId);
|
||||
boolean isProviderForNetworkOffering(Provider provider, long networkOfferingId);
|
||||
|
||||
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<Provider, ArrayList<PublicIp>> getProviderToIpList(Network network, Map<PublicIp, Set<Service>> ipToServices);
|
||||
|
||||
|
||||
public boolean checkIpForService(IPAddressVO ip, Service service);
|
||||
|
||||
void checkVirtualNetworkCidrOverlap(Long zoneId, String cidr);
|
||||
|
||||
void checkCapabilityForProvider(Set<Provider> providers, Service service,
|
||||
Capability cap, String capValue);
|
||||
void checkCapabilityForProvider(Set<Provider> providers, Service service,
|
||||
Capability cap, String capValue);
|
||||
|
||||
Provider getDefaultUniqueProviderForService(String serviceName);
|
||||
Provider getDefaultUniqueProviderForService(String serviceName);
|
||||
|
||||
IpAddress assignElasticIp(long networkId, Account owner,
|
||||
boolean forElasticLb, boolean forElasticIp)
|
||||
throws InsufficientAddressCapacityException;
|
||||
IpAddress assignElasticIp(long networkId, Account owner,
|
||||
boolean forElasticLb, boolean forElasticIp)
|
||||
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,
|
||||
VirtualMachineProfile<? extends VirtualMachine> vm,
|
||||
Network network, String requestedIp)
|
||||
throws InsufficientVirtualNetworkCapcityException,
|
||||
InsufficientAddressCapacityException;
|
||||
void allocateDirectIp(NicProfile nic, DataCenter dc,
|
||||
VirtualMachineProfile<? extends VirtualMachine> vm,
|
||||
Network network, String requestedIp)
|
||||
throws InsufficientVirtualNetworkCapcityException,
|
||||
InsufficientAddressCapacityException;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -16,44 +16,45 @@
|
||||
*
|
||||
*/
|
||||
|
||||
package com.cloud.network.dao;
|
||||
|
||||
package com.cloud.network.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.cloud.network.rules.FirewallRule;
|
||||
import com.cloud.network.rules.FirewallRuleVO;
|
||||
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> {
|
||||
|
||||
|
||||
List<FirewallRuleVO> listByIpAndPurposeAndNotRevoked(long ipAddressId, FirewallRule.Purpose purpose);
|
||||
|
||||
|
||||
List<FirewallRuleVO> listByNetworkAndPurposeAndNotRevoked(long networkId, FirewallRule.Purpose purpose);
|
||||
|
||||
|
||||
boolean setStateToAdd(FirewallRuleVO rule);
|
||||
|
||||
|
||||
boolean revoke(FirewallRuleVO rule);
|
||||
|
||||
|
||||
boolean releasePorts(long ipAddressId, String protocol, FirewallRule.Purpose purpose, int[] ports);
|
||||
|
||||
|
||||
List<FirewallRuleVO> listByIpAndPurpose(long ipAddressId, FirewallRule.Purpose purpose);
|
||||
|
||||
|
||||
List<FirewallRuleVO> listByNetworkAndPurpose(long networkId, FirewallRule.Purpose purpose);
|
||||
|
||||
|
||||
List<FirewallRuleVO> listStaticNatByVmId(long vmId);
|
||||
|
||||
|
||||
List<FirewallRuleVO> listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose);
|
||||
|
||||
FirewallRuleVO findByRelatedId(long ruleId);
|
||||
|
||||
List<FirewallRuleVO> listSystemRules();
|
||||
|
||||
List<FirewallRuleVO> listSystemRules();
|
||||
|
||||
List<FirewallRuleVO> listByIp(long ipAddressId);
|
||||
|
||||
|
||||
List<FirewallRuleVO> listByIpAndNotRevoked(long ipAddressId);
|
||||
|
||||
|
||||
long countRulesByIpId(long sourceIpId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -16,8 +16,8 @@
|
||||
*
|
||||
*/
|
||||
|
||||
package com.cloud.network.dao;
|
||||
|
||||
package com.cloud.network.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
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.Op;
|
||||
import com.cloud.utils.db.Transaction;
|
||||
|
||||
@Local(value=FirewallRulesDao.class) @DB(txn=false)
|
||||
public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> implements FirewallRulesDao {
|
||||
|
||||
|
||||
@Local(value = FirewallRulesDao.class)
|
||||
@DB(txn = false)
|
||||
public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> implements FirewallRulesDao {
|
||||
|
||||
protected final SearchBuilder<FirewallRuleVO> AllFieldsSearch;
|
||||
protected final SearchBuilder<FirewallRuleVO> NotRevokedSearch;
|
||||
protected final SearchBuilder<FirewallRuleVO> ReleaseSearch;
|
||||
protected SearchBuilder<FirewallRuleVO> VmSearch;
|
||||
protected final SearchBuilder<FirewallRuleVO> SystemRuleSearch;
|
||||
protected final GenericSearchBuilder<FirewallRuleVO, Long> RulesByIpCount;
|
||||
|
||||
|
||||
protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class);
|
||||
|
||||
|
||||
protected FirewallRulesDaoImpl() {
|
||||
super();
|
||||
|
||||
|
||||
AllFieldsSearch = createSearchBuilder();
|
||||
AllFieldsSearch.and("ipId", AllFieldsSearch.entity().getSourceIpAddressId(), 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("related", AllFieldsSearch.entity().getRelated(), Op.EQ);
|
||||
AllFieldsSearch.done();
|
||||
|
||||
|
||||
NotRevokedSearch = createSearchBuilder();
|
||||
NotRevokedSearch.and("ipId", NotRevokedSearch.entity().getSourceIpAddressId(), Op.EQ);
|
||||
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("networkId", NotRevokedSearch.entity().getNetworkId(), Op.EQ);
|
||||
NotRevokedSearch.done();
|
||||
|
||||
|
||||
ReleaseSearch = createSearchBuilder();
|
||||
ReleaseSearch.and("protocol", ReleaseSearch.entity().getProtocol(), Op.EQ);
|
||||
ReleaseSearch.and("ipId", ReleaseSearch.entity().getSourceIpAddressId(), Op.EQ);
|
||||
ReleaseSearch.and("purpose", ReleaseSearch.entity().getPurpose(), Op.EQ);
|
||||
ReleaseSearch.and("ports", ReleaseSearch.entity().getSourcePortStart(), Op.IN);
|
||||
ReleaseSearch.done();
|
||||
|
||||
|
||||
SystemRuleSearch = createSearchBuilder();
|
||||
SystemRuleSearch.and("type", SystemRuleSearch.entity().getType(), Op.EQ);
|
||||
SystemRuleSearch.and("ipId", SystemRuleSearch.entity().getSourceIpAddressId(), Op.NULL);
|
||||
SystemRuleSearch.done();
|
||||
|
||||
|
||||
RulesByIpCount = createSearchBuilder(Long.class);
|
||||
RulesByIpCount.select(null, Func.COUNT, RulesByIpCount.entity().getId());
|
||||
RulesByIpCount.and("ipAddressId", RulesByIpCount.entity().getSourceIpAddressId(), Op.EQ);
|
||||
RulesByIpCount.done();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<FirewallRuleVO> listSystemRules() {
|
||||
SearchCriteria<FirewallRuleVO> sc = SystemRuleSearch.create();
|
||||
sc.setParameters("type", FirewallRuleType.System.toString());
|
||||
return listBy(sc);
|
||||
SearchCriteria<FirewallRuleVO> sc = SystemRuleSearch.create();
|
||||
sc.setParameters("type", FirewallRuleType.System.toString());
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean releasePorts(long ipId, String protocol, FirewallRule.Purpose purpose, int[] ports) {
|
||||
SearchCriteria<FirewallRuleVO> sc = ReleaseSearch.create();
|
||||
@ -108,17 +109,17 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
|
||||
sc.setParameters("ipId", ipId);
|
||||
sc.setParameters("purpose", purpose);
|
||||
sc.setParameters("ports", ports);
|
||||
|
||||
|
||||
int results = remove(sc);
|
||||
return results == ports.length;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<FirewallRuleVO> listByIpAndPurpose(long ipId, FirewallRule.Purpose purpose) {
|
||||
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
|
||||
sc.setParameters("ipId", ipId);
|
||||
sc.setParameters("purpose", purpose);
|
||||
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
@ -127,123 +128,122 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
|
||||
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
|
||||
sc.setParameters("ipId", ipId);
|
||||
sc.setParameters("state", State.Revoke);
|
||||
|
||||
|
||||
if (purpose != null) {
|
||||
sc.setParameters("purpose", purpose);
|
||||
}
|
||||
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<FirewallRuleVO> listByNetworkAndPurposeAndNotRevoked(long networkId, FirewallRule.Purpose purpose) {
|
||||
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
|
||||
sc.setParameters("networkId", networkId);
|
||||
sc.setParameters("state", State.Revoke);
|
||||
|
||||
|
||||
if (purpose != null) {
|
||||
sc.setParameters("purpose", purpose);
|
||||
}
|
||||
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<FirewallRuleVO> listByNetworkAndPurpose(long networkId, FirewallRule.Purpose purpose) {
|
||||
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
|
||||
sc.setParameters("purpose", purpose);
|
||||
sc.setParameters("networkId", networkId);
|
||||
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean setStateToAdd(FirewallRuleVO rule) {
|
||||
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
|
||||
sc.setParameters("id", rule.getId());
|
||||
sc.setParameters("state", State.Staged);
|
||||
|
||||
|
||||
rule.setState(State.Add);
|
||||
|
||||
|
||||
return update(rule, sc) > 0;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean revoke(FirewallRuleVO rule) {
|
||||
rule.setState(State.Revoke);
|
||||
return update(rule.getId(), rule);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<FirewallRuleVO> listStaticNatByVmId(long vmId) {
|
||||
public List<FirewallRuleVO> listStaticNatByVmId(long vmId) {
|
||||
IPAddressDao _ipDao = ComponentLocator.getLocator("management-server").getDao(IPAddressDao.class);
|
||||
|
||||
if (VmSearch == null) {
|
||||
|
||||
if (VmSearch == null) {
|
||||
SearchBuilder<IPAddressVO> IpSearch = _ipDao.createSearchBuilder();
|
||||
IpSearch.and("associatedWithVmId", IpSearch.entity().getAssociatedWithVmId(), SearchCriteria.Op.EQ);
|
||||
IpSearch.and("oneToOneNat", IpSearch.entity().isOneToOneNat(), SearchCriteria.Op.NNULL);
|
||||
|
||||
|
||||
VmSearch = createSearchBuilder();
|
||||
VmSearch.and("purpose", VmSearch.entity().getPurpose(), Op.EQ);
|
||||
VmSearch.join("ipSearch", IpSearch, VmSearch.entity().getSourceIpAddressId(), IpSearch.entity().getId(), JoinBuilder.JoinType.INNER);
|
||||
VmSearch.done();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
SearchCriteria<FirewallRuleVO> sc = VmSearch.create();
|
||||
sc.setParameters("purpose", Purpose.StaticNat);
|
||||
sc.setJoinParameters("ipSearch", "associatedWithVmId", vmId);
|
||||
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
@Override @DB
|
||||
public FirewallRuleVO persist(FirewallRuleVO firewallRule) {
|
||||
|
||||
@Override
|
||||
@DB
|
||||
public FirewallRuleVO persist(FirewallRuleVO firewallRule) {
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
|
||||
FirewallRuleVO dbfirewallRule = super.persist(firewallRule);
|
||||
saveSourceCidrs(firewallRule, firewallRule.getSourceCidrList());
|
||||
|
||||
|
||||
txn.commit();
|
||||
return dbfirewallRule;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void saveSourceCidrs(FirewallRuleVO firewallRule, List<String> cidrList) {
|
||||
if (cidrList == null) {
|
||||
return;
|
||||
}
|
||||
_firewallRulesCidrsDao.persist(firewallRule.getId(), cidrList);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<FirewallRuleVO> listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose) {
|
||||
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
|
||||
sc.setParameters("ipId", ipAddressId);
|
||||
sc.setParameters("state", State.Revoke);
|
||||
|
||||
|
||||
if (purpose != null) {
|
||||
sc.setParameters("purpose", purpose);
|
||||
}
|
||||
|
||||
|
||||
if (protocol != null) {
|
||||
sc.setParameters("protocol", protocol);
|
||||
}
|
||||
|
||||
|
||||
sc.setParameters("sourcePortStart", startPort);
|
||||
|
||||
|
||||
sc.setParameters("sourcePortEnd", endPort);
|
||||
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public FirewallRuleVO findByRelatedId(long ruleId) {
|
||||
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
|
||||
sc.setParameters("related", ruleId);
|
||||
sc.setParameters("purpose", Purpose.Firewall);
|
||||
|
||||
|
||||
return findOneBy(sc);
|
||||
}
|
||||
|
||||
@ -251,23 +251,24 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
|
||||
public List<FirewallRuleVO> listByIp(long ipId) {
|
||||
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
|
||||
sc.setParameters("ipId", ipId);
|
||||
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<FirewallRuleVO> listByIpAndNotRevoked(long ipId) {
|
||||
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
|
||||
sc.setParameters("ipId", ipId);
|
||||
sc.setParameters("state", State.Revoke);
|
||||
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public long countRulesByIpId(long sourceIpId) {
|
||||
SearchCriteria<Long> sc = RulesByIpCount.create();
|
||||
SearchCriteria<Long> sc = RulesByIpCount.create();
|
||||
sc.setParameters("ipAddressId", sourceIpId);
|
||||
return customSearch(sc, null).get(0);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -16,18 +16,24 @@
|
||||
*
|
||||
*/
|
||||
|
||||
package com.cloud.network.dao;
|
||||
|
||||
package com.cloud.network.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.cloud.network.LoadBalancerVO;
|
||||
import com.cloud.utils.db.GenericDao;
|
||||
|
||||
public interface LoadBalancerDao extends GenericDao<LoadBalancerVO, Long> {
|
||||
List<Long> listInstancesByLoadBalancer(long loadBalancerId);
|
||||
List<LoadBalancerVO> listByIpAddress(long ipAddressId);
|
||||
|
||||
public interface LoadBalancerDao extends GenericDao<LoadBalancerVO, Long> {
|
||||
List<Long> listInstancesByLoadBalancer(long loadBalancerId);
|
||||
|
||||
List<LoadBalancerVO> listByIpAddress(long ipAddressId);
|
||||
|
||||
LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort);
|
||||
|
||||
LoadBalancerVO findByAccountAndName(Long accountId, String name);
|
||||
|
||||
List<LoadBalancerVO> listByNetworkId(long networkId);
|
||||
List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId);
|
||||
}
|
||||
|
||||
List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId);
|
||||
|
||||
}
|
||||
|
||||
@ -16,8 +16,8 @@
|
||||
*
|
||||
*/
|
||||
|
||||
package com.cloud.network.dao;
|
||||
|
||||
package com.cloud.network.dao;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
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.Op;
|
||||
import com.cloud.utils.db.Transaction;
|
||||
|
||||
@Local(value={LoadBalancerDao.class})
|
||||
public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> implements LoadBalancerDao {
|
||||
|
||||
@Local(value = { LoadBalancerDao.class })
|
||||
public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> implements LoadBalancerDao {
|
||||
private static final Logger s_logger = Logger.getLogger(LoadBalancerDaoImpl.class);
|
||||
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 " +
|
||||
" WHERE lb.id = ? AND " +
|
||||
" fwd.group_id = lb.id AND " +
|
||||
" fwd.forwarding = 0 AND " +
|
||||
" fwd.private_ip_address = vm.private_ip_address AND " +
|
||||
" lb.ip_address = ip.public_ip_address AND " +
|
||||
" ip.data_center_id = vm.data_center_id ";
|
||||
private final SearchBuilder<LoadBalancerVO> ListByIp;
|
||||
private final SearchBuilder<LoadBalancerVO> IpAndPublicPortSearch;
|
||||
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 " +
|
||||
" WHERE lb.id = ? AND " +
|
||||
" fwd.group_id = lb.id AND " +
|
||||
" fwd.forwarding = 0 AND " +
|
||||
" fwd.private_ip_address = vm.private_ip_address AND " +
|
||||
" lb.ip_address = ip.public_ip_address AND " +
|
||||
" ip.data_center_id = vm.data_center_id ";
|
||||
private final SearchBuilder<LoadBalancerVO> ListByIp;
|
||||
private final SearchBuilder<LoadBalancerVO> IpAndPublicPortSearch;
|
||||
private final SearchBuilder<LoadBalancerVO> AccountAndNameSearch;
|
||||
protected final SearchBuilder<LoadBalancerVO> TransitionStateSearch;
|
||||
|
||||
|
||||
protected final FirewallRulesCidrsDaoImpl _portForwardingRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class);
|
||||
|
||||
protected LoadBalancerDaoImpl() {
|
||||
ListByIp = createSearchBuilder();
|
||||
|
||||
protected LoadBalancerDaoImpl() {
|
||||
ListByIp = createSearchBuilder();
|
||||
ListByIp.and("ipAddressId", ListByIp.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
|
||||
ListByIp.and("networkId", ListByIp.entity().getNetworkId(), SearchCriteria.Op.EQ);
|
||||
ListByIp.done();
|
||||
|
||||
IpAndPublicPortSearch = createSearchBuilder();
|
||||
IpAndPublicPortSearch.and("ipAddressId", IpAndPublicPortSearch.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
|
||||
IpAndPublicPortSearch.and("publicPort", IpAndPublicPortSearch.entity().getSourcePortStart(), SearchCriteria.Op.EQ);
|
||||
IpAndPublicPortSearch.done();
|
||||
ListByIp.and("networkId", ListByIp.entity().getNetworkId(), SearchCriteria.Op.EQ);
|
||||
ListByIp.done();
|
||||
|
||||
IpAndPublicPortSearch = createSearchBuilder();
|
||||
IpAndPublicPortSearch.and("ipAddressId", IpAndPublicPortSearch.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
|
||||
IpAndPublicPortSearch.and("publicPort", IpAndPublicPortSearch.entity().getSourcePortStart(), SearchCriteria.Op.EQ);
|
||||
IpAndPublicPortSearch.done();
|
||||
|
||||
AccountAndNameSearch = createSearchBuilder();
|
||||
AccountAndNameSearch.and("accountId", AccountAndNameSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
|
||||
AccountAndNameSearch.and("name", AccountAndNameSearch.entity().getName(), SearchCriteria.Op.EQ);
|
||||
AccountAndNameSearch.done();
|
||||
|
||||
|
||||
TransitionStateSearch = createSearchBuilder();
|
||||
TransitionStateSearch.and("networkId", TransitionStateSearch.entity().getNetworkId(), Op.EQ);
|
||||
TransitionStateSearch.and("state", TransitionStateSearch.entity().getState(), Op.IN);
|
||||
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
|
||||
public List<LoadBalancerVO> listByNetworkId(long networkId) {
|
||||
SearchCriteria<LoadBalancerVO> sc = ListByIp.create();
|
||||
sc.setParameters("networkId", networkId);
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort) {
|
||||
SearchCriteria<LoadBalancerVO> sc = IpAndPublicPortSearch.create();
|
||||
sc.setParameters("ipAddressId", ipAddressId);
|
||||
sc.setParameters("publicPort", publicPort);
|
||||
return findOneBy(sc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort) {
|
||||
SearchCriteria<LoadBalancerVO> sc = IpAndPublicPortSearch.create();
|
||||
sc.setParameters("ipAddressId", ipAddressId);
|
||||
sc.setParameters("publicPort", publicPort);
|
||||
return findOneBy(sc);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -126,12 +126,13 @@ public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> im
|
||||
sc.setParameters("name", name);
|
||||
return findOneBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId) {
|
||||
SearchCriteria<LoadBalancerVO> sc = TransitionStateSearch.create();
|
||||
sc.setParameters("networkId", networkId);
|
||||
sc.setParameters("state", State.Add.toString(), State.Revoke.toString());
|
||||
return listBy(sc);
|
||||
}
|
||||
}
|
||||
SearchCriteria<LoadBalancerVO> sc = TransitionStateSearch.create();
|
||||
sc.setParameters("networkId", networkId);
|
||||
sc.setParameters("state", State.Add.toString(), State.Revoke.toString());
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -46,7 +46,7 @@ public interface NetworkDao extends GenericDao<NetworkVO, Long> {
|
||||
@Override
|
||||
@Deprecated
|
||||
NetworkVO persist(NetworkVO vo);
|
||||
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
void persistNetworkServiceProviders(long networkId, Map<String, String> serviceProviderMap);
|
||||
|
||||
boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap);
|
||||
|
||||
List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType);
|
||||
void persistNetworkServiceProviders(long networkId, Map<String, String> serviceProviderMap);
|
||||
|
||||
boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap);
|
||||
|
||||
List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType);
|
||||
|
||||
}
|
||||
|
||||
@ -49,7 +49,8 @@ import com.cloud.utils.db.SequenceFetcher;
|
||||
import com.cloud.utils.db.Transaction;
|
||||
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 {
|
||||
final SearchBuilder<NetworkVO> AllFieldsSearch;
|
||||
final SearchBuilder<NetworkVO> AccountSearch;
|
||||
@ -60,7 +61,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
|
||||
final GenericSearchBuilder<NetworkVO, Long> CountByOfferingId;
|
||||
final SearchBuilder<NetworkVO> PhysicalNetworkSearch;
|
||||
final SearchBuilder<NetworkVO> securityGroupSearch;
|
||||
|
||||
|
||||
NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class);
|
||||
NetworkDomainDaoImpl _domainsDao = ComponentLocator.inject(NetworkDomainDaoImpl.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("related", AllFieldsSearch.entity().getRelated(), 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();
|
||||
|
||||
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.done();
|
||||
|
||||
|
||||
ZoneBroadcastUriSearch = createSearchBuilder();
|
||||
ZoneBroadcastUriSearch.and("dataCenterId", ZoneBroadcastUriSearch.entity().getDataCenterId(), 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);
|
||||
ZoneSecurityGroupSearch.join("services", join1, ZoneSecurityGroupSearch.entity().getId(), join1.entity().getNetworkId(), JoinBuilder.JoinType.INNER);
|
||||
ZoneSecurityGroupSearch.done();
|
||||
|
||||
|
||||
CountByOfferingId = createSearchBuilder(Long.class);
|
||||
CountByOfferingId.select(null, Func.COUNT, CountByOfferingId.entity().getId());
|
||||
CountByOfferingId.and("offeringId", CountByOfferingId.entity().getNetworkOfferingId(), Op.EQ);
|
||||
CountByOfferingId.and("removed", CountByOfferingId.entity().getRemoved(), Op.NULL);
|
||||
CountByOfferingId.done();
|
||||
|
||||
|
||||
PhysicalNetworkSearch = createSearchBuilder();
|
||||
PhysicalNetworkSearch.and("physicalNetworkId", PhysicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ);
|
||||
PhysicalNetworkSearch.done();
|
||||
|
||||
|
||||
securityGroupSearch = createSearchBuilder();
|
||||
SearchBuilder<NetworkServiceMapVO> join3 = _ntwkSvcMap.createSearchBuilder();
|
||||
join3.and("service", join3.entity().getService(), Op.EQ);
|
||||
securityGroupSearch.join("services", join3, securityGroupSearch.entity().getId(), join3.entity().getNetworkId(), JoinBuilder.JoinType.INNER);
|
||||
securityGroupSearch.done();
|
||||
|
||||
|
||||
_tgMacAddress = _tgs.get("macAddress");
|
||||
|
||||
}
|
||||
@ -184,51 +183,52 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
@Override @DB
|
||||
@Override
|
||||
@DB
|
||||
public NetworkVO persist(NetworkVO network, boolean gc, Map<String, String> serviceProviderMap) {
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
//1) create network
|
||||
|
||||
// 1) create network
|
||||
NetworkVO newNetwork = super.persist(network);
|
||||
//2) add account to the network
|
||||
// 2) add account to the network
|
||||
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);
|
||||
_opDao.persist(op);
|
||||
//4) add services/providers for the network
|
||||
// 4) add services/providers for the network
|
||||
persistNetworkServiceProviders(newNetwork.getId(), serviceProviderMap);
|
||||
|
||||
txn.commit();
|
||||
return newNetwork;
|
||||
}
|
||||
|
||||
|
||||
@Override @DB
|
||||
|
||||
@Override
|
||||
@DB
|
||||
public boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap) {
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
|
||||
super.update(networkId, network);
|
||||
if (serviceProviderMap != null) {
|
||||
_ntwkSvcMap.deleteByNetworkId(networkId);
|
||||
persistNetworkServiceProviders(networkId, serviceProviderMap);
|
||||
}
|
||||
|
||||
|
||||
txn.commit();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@DB
|
||||
public void persistNetworkServiceProviders(long networkId, Map<String, String> serviceProviderMap) {
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
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)));
|
||||
_ntwkSvcMap.persist(serviceMap);
|
||||
}
|
||||
txn.commit();
|
||||
txn.commit();
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@ -350,9 +350,9 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
|
||||
sc.setParameters("physicalNetworkId", physicalNetworkId);
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<NetworkVO> listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType){
|
||||
public List<NetworkVO> listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType) {
|
||||
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
|
||||
sc.setParameters("trafficType", trafficType);
|
||||
sc.setParameters("physicalNetworkId", physicalNetworkId);
|
||||
@ -375,7 +375,7 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
|
||||
|
||||
return listBy(sc);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<NetworkVO> listBy(long accountId, long dataCenterId, Network.GuestType type, TrafficType trafficType) {
|
||||
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
|
||||
@ -383,16 +383,17 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
|
||||
sc.setParameters("account", accountId);
|
||||
sc.setParameters("guestType", type);
|
||||
sc.setParameters("trafficType", trafficType);
|
||||
|
||||
|
||||
return listBy(sc, null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType) {
|
||||
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
|
||||
SearchCriteria<NetworkVO> sc = AllFieldsSearch.create();
|
||||
sc.setParameters("datacenter", zoneId);
|
||||
sc.setParameters("trafficType", trafficType);
|
||||
|
||||
|
||||
return listBy(sc, null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
|
||||
*
|
||||
*
|
||||
*
|
||||
* 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.UserVmDao;
|
||||
|
||||
|
||||
@Local(value=NetworkElement.class)
|
||||
@Local(value = NetworkElement.class)
|
||||
public class CloudZonesNetworkElement extends AdapterBase implements NetworkElement, UserDataServiceProvider {
|
||||
private static final Logger s_logger = Logger.getLogger(CloudZonesNetworkElement.class);
|
||||
|
||||
|
||||
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
|
||||
|
||||
@Inject NetworkDao _networkConfigDao;
|
||||
@Inject NetworkManager _networkMgr;
|
||||
@Inject VirtualNetworkApplianceManager _routerMgr;
|
||||
@Inject UserVmManager _userVmMgr;
|
||||
@Inject UserVmDao _userVmDao;
|
||||
@Inject DomainRouterDao _routerDao;
|
||||
@Inject ConfigurationManager _configMgr;
|
||||
@Inject DataCenterDao _dcDao;
|
||||
@Inject AgentManager _agentManager;
|
||||
@Inject ServiceOfferingDao _serviceOfferingDao;
|
||||
|
||||
|
||||
@Inject
|
||||
NetworkDao _networkConfigDao;
|
||||
@Inject
|
||||
NetworkManager _networkMgr;
|
||||
@Inject
|
||||
VirtualNetworkApplianceManager _routerMgr;
|
||||
@Inject
|
||||
UserVmManager _userVmMgr;
|
||||
@Inject
|
||||
UserVmDao _userVmDao;
|
||||
@Inject
|
||||
DomainRouterDao _routerDao;
|
||||
@Inject
|
||||
ConfigurationManager _configMgr;
|
||||
@Inject
|
||||
DataCenterDao _dcDao;
|
||||
@Inject
|
||||
AgentManager _agentManager;
|
||||
@Inject
|
||||
ServiceOfferingDao _serviceOfferingDao;
|
||||
|
||||
private boolean canHandle(DeployDestination dest, TrafficType trafficType) {
|
||||
DataCenterVO dc = (DataCenterVO)dest.getDataCenter();
|
||||
|
||||
if (dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName())){
|
||||
DataCenterVO dc = (DataCenterVO) dest.getDataCenter();
|
||||
|
||||
if (dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName())) {
|
||||
_dcDao.loadDetails(dc);
|
||||
String dhcpStrategy = dc.getDetail(ZoneConfig.DhcpStrategy.key());
|
||||
if ("external".equalsIgnoreCase(dhcpStrategy)) {
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@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())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@ -129,39 +140,39 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
|
||||
public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
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
|
||||
public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException{
|
||||
return false; //assume that the agent will remove userdata etc
|
||||
public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return false; // assume that the agent will remove userdata etc
|
||||
}
|
||||
|
||||
@Override
|
||||
public Provider getProvider() {
|
||||
return Provider.ExternalDhcpServer;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Map<Service, Map<Capability, String>> getCapabilities() {
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
|
||||
private static Map<Service, Map<Capability, String>> setCapabilities() {
|
||||
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
|
||||
|
||||
|
||||
capabilities.put(Service.UserData, null);
|
||||
|
||||
|
||||
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) {
|
||||
VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName);
|
||||
|
||||
|
||||
cmd.addVmData("userdata", "user-data", userData);
|
||||
cmd.addVmData("metadata", "service-offering", serviceOffering);
|
||||
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)
|
||||
throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
|
||||
if (canHandle(dest, network.getTrafficType())) {
|
||||
|
||||
|
||||
if (vm.getType() != VirtualMachine.Type.User) {
|
||||
return false;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm;
|
||||
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
|
||||
_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 sshPublicKey = uservm.getVirtualMachine().getDetail("SSH.PublicKey");
|
||||
|
||||
@ -219,7 +230,8 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
|
||||
|
||||
cmds.addCommand(
|
||||
"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 {
|
||||
_agentManager.send(dest.getHost().getId(), cmds);
|
||||
} catch (OperationTimedoutException e) {
|
||||
@ -242,9 +254,10 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean verifyServicesCombination(List<String> services) {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
|
||||
*
|
||||
*
|
||||
*
|
||||
* 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.VirtualMachineProfile;
|
||||
|
||||
@Local(value=NetworkElement.class)
|
||||
@Local(value = NetworkElement.class)
|
||||
public class ExternalDhcpElement extends AdapterBase implements NetworkElement, DhcpServiceProvider {
|
||||
private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class);
|
||||
@Inject 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;
|
||||
}
|
||||
private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class);
|
||||
@Inject
|
||||
ExternalDhcpManager _dhcpMgr;
|
||||
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
|
||||
|
||||
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() {
|
||||
//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>>();
|
||||
// capabilities.put(Service.Dhcp, null);
|
||||
// capabilities.put(Service.Dhcp, null);
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Service, Map<Capability, String>> getCapabilities() {
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Provider getProvider() {
|
||||
return Provider.ExternalDhcpServer;
|
||||
}
|
||||
@Override
|
||||
public Map<Service, Map<Capability, String>> getCapabilities() {
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
|
||||
if (!canHandle(dest, offering.getTrafficType(), network.getGuestType())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public Provider getProvider() {
|
||||
return Provider.ExternalDhcpServer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest,
|
||||
ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
|
||||
if (!canHandle(dest, offering.getTrafficType(), network.getGuestType())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest,
|
||||
ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady(PhysicalNetworkServiceProvider provider) {
|
||||
@ -142,12 +142,12 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement,
|
||||
throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
|
||||
Host host = dest.getHost();
|
||||
if (host.getHypervisorType() == HypervisorType.BareMetal || !canHandle(dest, network.getTrafficType(), network.getGuestType())) {
|
||||
//BareMetalElement or DhcpElement handle this
|
||||
// BareMetalElement or DhcpElement handle this
|
||||
return false;
|
||||
}
|
||||
return _dhcpMgr.addVirtualMachineIntoNetwork(network, nic, vm, dest, context);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean verifyServicesCombination(List<String> services) {
|
||||
return true;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
|
||||
*
|
||||
*
|
||||
*
|
||||
* 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.ConfigurationManager;
|
||||
import com.cloud.configuration.dao.ConfigurationDao;
|
||||
import com.cloud.dc.DataCenter;
|
||||
import com.cloud.dc.DataCenterVO;
|
||||
import com.cloud.dc.dao.DataCenterDao;
|
||||
import com.cloud.deploy.DeployDestination;
|
||||
@ -57,15 +56,15 @@ import com.cloud.host.dao.HostDetailsDao;
|
||||
import com.cloud.network.ExternalLoadBalancerDeviceManager;
|
||||
import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl;
|
||||
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.ExternalNetworkDeviceManager.NetworkDevice;
|
||||
import com.cloud.network.Network;
|
||||
import com.cloud.network.Network.Capability;
|
||||
import com.cloud.network.Network.Provider;
|
||||
import com.cloud.network.Network.Service;
|
||||
import com.cloud.network.NetworkExternalLoadBalancerVO;
|
||||
import com.cloud.network.NetworkManager;
|
||||
import com.cloud.network.NetworkVO;
|
||||
import com.cloud.network.Networks.TrafficType;
|
||||
import com.cloud.network.PhysicalNetworkServiceProvider;
|
||||
import com.cloud.network.PhysicalNetworkVO;
|
||||
@ -91,36 +90,47 @@ import com.cloud.vm.VirtualMachine;
|
||||
import com.cloud.vm.VirtualMachineProfile;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
@Local(value=NetworkElement.class)
|
||||
@Local(value = NetworkElement.class)
|
||||
public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, IpDeployer, F5ExternalLoadBalancerElementService, ExternalLoadBalancerDeviceManager {
|
||||
|
||||
private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class);
|
||||
|
||||
@Inject NetworkManager _networkManager;
|
||||
@Inject ConfigurationManager _configMgr;
|
||||
@Inject NetworkServiceMapDao _ntwkSrvcDao;
|
||||
@Inject DataCenterDao _dcDao;
|
||||
@Inject PhysicalNetworkDao _physicalNetworkDao;
|
||||
@Inject HostDao _hostDao;
|
||||
@Inject ExternalLoadBalancerDeviceDao _lbDeviceDao;
|
||||
@Inject NetworkExternalLoadBalancerDao _networkLBDao;
|
||||
@Inject NetworkDao _networkDao;
|
||||
@Inject HostDetailsDao _detailsDao;
|
||||
@Inject ConfigurationDao _configDao;
|
||||
|
||||
@Inject
|
||||
NetworkManager _networkManager;
|
||||
@Inject
|
||||
ConfigurationManager _configMgr;
|
||||
@Inject
|
||||
NetworkServiceMapDao _ntwkSrvcDao;
|
||||
@Inject
|
||||
DataCenterDao _dcDao;
|
||||
@Inject
|
||||
PhysicalNetworkDao _physicalNetworkDao;
|
||||
@Inject
|
||||
HostDao _hostDao;
|
||||
@Inject
|
||||
ExternalLoadBalancerDeviceDao _lbDeviceDao;
|
||||
@Inject
|
||||
NetworkExternalLoadBalancerDao _networkLBDao;
|
||||
@Inject
|
||||
NetworkDao _networkDao;
|
||||
@Inject
|
||||
HostDetailsDao _detailsDao;
|
||||
@Inject
|
||||
ConfigurationDao _configDao;
|
||||
|
||||
private boolean canHandle(Network config) {
|
||||
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());
|
||||
return false;
|
||||
}
|
||||
|
||||
return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) &&
|
||||
_ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), Service.Lb, Network.Provider.F5BigIp));
|
||||
|
||||
return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), Service.Lb, Network.Provider.F5BigIp));
|
||||
}
|
||||
|
||||
@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)) {
|
||||
return false;
|
||||
}
|
||||
@ -128,18 +138,20 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
|
||||
try {
|
||||
return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig);
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@ -148,75 +160,75 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
|
||||
if (!canHandle(guestConfig)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
return manageGuestNetworkWithExternalLoadBalancer(false, guestConfig);
|
||||
return manageGuestNetworkWithExternalLoadBalancer(false, guestConfig);
|
||||
} catch (InsufficientCapacityException capacityException) {
|
||||
// TODO: handle out of capacity exception
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean destroy(Network config) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean validateLBRule(Network network, LoadBalancingRule rule) {
|
||||
public boolean validateLBRule(Network network, LoadBalancingRule rule) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyLBRules(Network config, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
|
||||
if (!canHandle(config)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return applyLoadBalancerRules(config, rules);
|
||||
|
||||
return applyLoadBalancerRules(config, rules);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Map<Service, Map<Capability, String>> getCapabilities() {
|
||||
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");
|
||||
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
|
||||
|
||||
// specifies that F5 BIG IP network element can provide shared mode only
|
||||
lbCapabilities.put(Capability.SupportedLBIsolation, "shared");
|
||||
// Set capabilities for LB service
|
||||
Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
|
||||
|
||||
// Specifies that load balancing rules can be made for either TCP or UDP traffic
|
||||
lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
|
||||
|
||||
// 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");
|
||||
// Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
|
||||
lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn");
|
||||
|
||||
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);
|
||||
// specifies that F5 BIG IP network element can provide shared mode only
|
||||
lbCapabilities.put(Capability.SupportedLBIsolation, "shared");
|
||||
|
||||
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);
|
||||
// Specifies that load balancing rules can be made for either TCP or UDP traffic
|
||||
lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
|
||||
|
||||
Gson gson = new Gson();
|
||||
String stickyMethodList = gson.toJson(methodList);
|
||||
lbCapabilities.put(Capability.SupportedStickinessMethods,stickyMethodList);
|
||||
// Specifies that this element can measure network usage on a per public IP basis
|
||||
lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
|
||||
|
||||
capabilities.put(Service.Lb, lbCapabilities);
|
||||
|
||||
return capabilities;
|
||||
// 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;
|
||||
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
|
||||
public Provider getProvider() {
|
||||
return Provider.F5BigIp;
|
||||
@ -258,8 +270,8 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
|
||||
@Deprecated
|
||||
public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd) {
|
||||
Long zoneId = cmd.getZoneId();
|
||||
DataCenterVO zone =null;
|
||||
PhysicalNetworkVO pNetwork=null;
|
||||
DataCenterVO zone = null;
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVO = 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());
|
||||
|
||||
if (lbDeviceVO != null) {
|
||||
lbHost = _hostDao.findById(lbDeviceVO.getHostId());
|
||||
lbHost = _hostDao.findById(lbDeviceVO.getHostId());
|
||||
}
|
||||
|
||||
return lbHost;
|
||||
@ -295,8 +307,8 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
|
||||
@Deprecated
|
||||
public List<Host> listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd) {
|
||||
Long zoneId = cmd.getZoneId();
|
||||
DataCenterVO zone =null;
|
||||
PhysicalNetworkVO pNetwork=null;
|
||||
DataCenterVO zone = null;
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
|
||||
if (zoneId != null) {
|
||||
zone = _dcDao.findById(zoneId);
|
||||
@ -378,7 +390,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
|
||||
Long physcialNetworkId = cmd.getPhysicalNetworkId();
|
||||
Long lbDeviceId = cmd.getLoadBalancerDeviceId();
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO> ();
|
||||
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO>();
|
||||
|
||||
if (physcialNetworkId == null && lbDeviceId == null) {
|
||||
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");
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean verifyServicesCombination(List<String> services) {
|
||||
return true;
|
||||
@ -459,7 +471,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
|
||||
*
|
||||
*
|
||||
*
|
||||
* 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 javax.ejb.Local;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.api.commands.AddExternalFirewallCmd;
|
||||
@ -41,8 +42,8 @@ import com.cloud.configuration.Config;
|
||||
import com.cloud.configuration.ConfigurationManager;
|
||||
import com.cloud.configuration.dao.ConfigurationDao;
|
||||
import com.cloud.dc.DataCenter;
|
||||
import com.cloud.dc.DataCenterVO;
|
||||
import com.cloud.dc.DataCenter.NetworkType;
|
||||
import com.cloud.dc.DataCenterVO;
|
||||
import com.cloud.dc.dao.DataCenterDao;
|
||||
import com.cloud.deploy.DeployDestination;
|
||||
import com.cloud.exception.ConcurrentOperationException;
|
||||
@ -54,14 +55,14 @@ import com.cloud.host.Host;
|
||||
import com.cloud.host.HostVO;
|
||||
import com.cloud.host.dao.HostDao;
|
||||
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.ExternalNetworkDeviceManager.NetworkDevice;
|
||||
import com.cloud.network.Network;
|
||||
import com.cloud.network.Network.Capability;
|
||||
import com.cloud.network.Network.Provider;
|
||||
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.NetworkManager;
|
||||
import com.cloud.network.NetworkVO;
|
||||
@ -90,28 +91,41 @@ import com.cloud.vm.ReservationContext;
|
||||
import com.cloud.vm.VirtualMachine;
|
||||
import com.cloud.vm.VirtualMachineProfile;
|
||||
|
||||
@Local(value=NetworkElement.class)
|
||||
@Local(value = NetworkElement.class)
|
||||
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 Map<Service, Map<Capability, String>> capabilities = setCapabilities();
|
||||
|
||||
@Inject NetworkManager _networkManager;
|
||||
@Inject HostDao _hostDao;
|
||||
@Inject ConfigurationManager _configMgr;
|
||||
@Inject NetworkOfferingDao _networkOfferingDao;
|
||||
@Inject NetworkDao _networksDao;
|
||||
@Inject DataCenterDao _dcDao;
|
||||
@Inject PhysicalNetworkDao _physicalNetworkDao;
|
||||
@Inject ExternalFirewallDeviceDao _fwDevicesDao;
|
||||
@Inject NetworkExternalFirewallDao _networkFirewallDao;
|
||||
@Inject NetworkDao _networkDao;
|
||||
@Inject NetworkServiceMapDao _ntwkSrvcDao;
|
||||
@Inject HostDetailsDao _hostDetailDao;
|
||||
@Inject ConfigurationDao _configDao;
|
||||
|
||||
|
||||
@Inject
|
||||
NetworkManager _networkManager;
|
||||
@Inject
|
||||
HostDao _hostDao;
|
||||
@Inject
|
||||
ConfigurationManager _configMgr;
|
||||
@Inject
|
||||
NetworkOfferingDao _networkOfferingDao;
|
||||
@Inject
|
||||
NetworkDao _networksDao;
|
||||
@Inject
|
||||
DataCenterDao _dcDao;
|
||||
@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) {
|
||||
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)) {
|
||||
@ -130,20 +144,21 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@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());
|
||||
|
||||
//don't have to implement network is Basic zone
|
||||
|
||||
// don't have to implement network is Basic zone
|
||||
if (zone.getNetworkType() == NetworkType.Basic) {
|
||||
s_logger.debug("Not handling network implement in zone of type " + NetworkType.Basic);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (!canHandle(network, null)) {
|
||||
return false;
|
||||
}
|
||||
@ -151,13 +166,15 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
try {
|
||||
return manageGuestNetworkWithExternalFirewall(true, network);
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@ -169,35 +186,35 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
@Override
|
||||
public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException {
|
||||
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) {
|
||||
s_logger.debug("Not handling network shutdown in zone of type " + NetworkType.Basic);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (!canHandle(network, null)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return manageGuestNetworkWithExternalFirewall(false, network);
|
||||
} catch (InsufficientCapacityException capacityException) {
|
||||
// TODO: handle out of capacity exception
|
||||
// TODO: handle out of capacity exception
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean destroy(Network config) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyFWRules(Network config, List<? extends FirewallRule> rules) throws ResourceUnavailableException {
|
||||
if (!canHandle(config, Service.Firewall)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return applyFirewallRules(config, rules);
|
||||
}
|
||||
|
||||
@ -206,7 +223,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
if (!canHandle(config, Service.Vpn)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return manageRemoteAccessVpn(true, config, vpn);
|
||||
|
||||
}
|
||||
@ -216,24 +233,24 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
if (!canHandle(config, Service.Vpn)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return manageRemoteAccessVpn(false, config, vpn);
|
||||
}
|
||||
|
||||
@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());
|
||||
|
||||
|
||||
if (!canHandle(config, Service.Vpn)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
boolean result = manageRemoteAccessVpnUsers(config, vpn, users);
|
||||
String[] results = new String[users.size()];
|
||||
for (int i = 0; i < results.length; i++) {
|
||||
results[i] = String.valueOf(result);
|
||||
}
|
||||
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
@ -249,49 +266,49 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
|
||||
private static Map<Service, Map<Capability, String>> setCapabilities() {
|
||||
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
|
||||
|
||||
|
||||
// Set capabilities for Firewall service
|
||||
Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>();
|
||||
firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
|
||||
Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>();
|
||||
firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
|
||||
firewallCapabilities.put(Capability.MultipleIps, "true");
|
||||
firewallCapabilities.put(Capability.TrafficStatistics, "per public ip");
|
||||
capabilities.put(Service.Firewall, firewallCapabilities);
|
||||
|
||||
//Disabling VPN for Juniper in Acton as it 1) Was never tested 2) probably just doesn't work
|
||||
// // Set VPN capabilities
|
||||
// Map<Capability, String> vpnCapabilities = new HashMap<Capability, String>();
|
||||
// vpnCapabilities.put(Capability.SupportedVpnTypes, "ipsec");
|
||||
// capabilities.put(Service.Vpn, vpnCapabilities);
|
||||
|
||||
|
||||
// Disabling VPN for Juniper in Acton as it 1) Was never tested 2) probably just doesn't work
|
||||
// // Set VPN capabilities
|
||||
// Map<Capability, String> vpnCapabilities = new HashMap<Capability, String>();
|
||||
// vpnCapabilities.put(Capability.SupportedVpnTypes, "ipsec");
|
||||
// capabilities.put(Service.Vpn, vpnCapabilities);
|
||||
|
||||
capabilities.put(Service.Gateway, null);
|
||||
|
||||
|
||||
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;
|
||||
// in the latter case a shared interface NAT rule will be used
|
||||
// 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
|
||||
sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "per account, per zone");
|
||||
capabilities.put(Service.SourceNat, sourceNatCapabilities);
|
||||
|
||||
|
||||
// Specifies that port forwarding rules are supported by this element
|
||||
capabilities.put(Service.PortForwarding, null);
|
||||
|
||||
|
||||
// Specifies that static NAT rules are supported by this element
|
||||
capabilities.put(Service.StaticNat, null);
|
||||
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyPFRules(Network network, List<PortForwardingRule> rules) throws ResourceUnavailableException {
|
||||
if (!canHandle(network, Service.PortForwarding)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return applyFirewallRules(network, rules);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady(PhysicalNetworkServiceProvider provider) {
|
||||
|
||||
|
||||
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
|
||||
if (fwDevices != null && !fwDevices.isEmpty()) {
|
||||
@ -317,11 +334,12 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
}
|
||||
|
||||
@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) {
|
||||
Long zoneId = cmd.getZoneId();
|
||||
DataCenterVO zone =null;
|
||||
PhysicalNetworkVO pNetwork=null;
|
||||
DataCenterVO zone = null;
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
HostVO fwHost = null;
|
||||
|
||||
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());
|
||||
if (fwDeviceVO != null) {
|
||||
fwHost = _hostDao.findById(fwDeviceVO.getHostId());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return fwHost;
|
||||
}
|
||||
|
||||
@ -351,12 +369,13 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated // should use more generic listNetworkDevice command
|
||||
@Deprecated
|
||||
// should use more generic listNetworkDevice command
|
||||
public List<Host> listExternalFirewalls(ListExternalFirewallsCmd cmd) {
|
||||
List<Host> firewallHosts = new ArrayList<Host>();
|
||||
Long zoneId = cmd.getZoneId();
|
||||
DataCenterVO zone =null;
|
||||
PhysicalNetworkVO pNetwork=null;
|
||||
DataCenterVO zone = null;
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
|
||||
if (zoneId != null) {
|
||||
zone = _dcDao.findById(zoneId);
|
||||
@ -391,7 +410,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
if (!deviceName.equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) {
|
||||
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());
|
||||
}
|
||||
|
||||
@ -415,7 +434,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
if (fwDeviceVO == null || !fwDeviceVO.getDeviceName().equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) {
|
||||
throw new InvalidParameterValueException("No SRX firewall device found with ID: " + fwDeviceId);
|
||||
}
|
||||
|
||||
|
||||
if (deviceCapacity != null) {
|
||||
// check if any networks are using this SRX device
|
||||
List<NetworkExternalFirewallVO> networks = _networkFirewallDao.listByFirewallDeviceId(fwDeviceId);
|
||||
@ -439,7 +458,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
Long physcialNetworkId = cmd.getPhysicalNetworkId();
|
||||
Long fwDeviceId = cmd.getFirewallDeviceId();
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
List<ExternalFirewallDeviceVO> fwDevices = new ArrayList<ExternalFirewallDeviceVO> ();
|
||||
List<ExternalFirewallDeviceVO> fwDevices = new ArrayList<ExternalFirewallDeviceVO>();
|
||||
|
||||
if (physcialNetworkId == null && fwDeviceId == null) {
|
||||
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");
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean verifyServicesCombination(List<String> services) {
|
||||
return true;
|
||||
@ -524,9 +543,9 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service) throws ResourceUnavailableException {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service) throws ResourceUnavailableException {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved
|
||||
*
|
||||
*
|
||||
*
|
||||
* 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 com.cloud.agent.AgentManager;
|
||||
import com.cloud.agent.AgentManager.OnError;
|
||||
import com.cloud.agent.api.Answer;
|
||||
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.SetStaticNatRulesCommand;
|
||||
import com.cloud.agent.api.to.LoadBalancerTO;
|
||||
import com.cloud.agent.api.to.StaticNatRuleTO;
|
||||
import com.cloud.agent.manager.Commands;
|
||||
import com.cloud.api.ApiConstants;
|
||||
import com.cloud.api.commands.AddNetscalerLoadBalancerCmd;
|
||||
import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd;
|
||||
@ -51,7 +48,6 @@ import com.cloud.configuration.Config;
|
||||
import com.cloud.configuration.ConfigurationManager;
|
||||
import com.cloud.configuration.dao.ConfigurationDao;
|
||||
import com.cloud.dc.DataCenter;
|
||||
import com.cloud.dc.DataCenterVO;
|
||||
import com.cloud.dc.DataCenter.NetworkType;
|
||||
import com.cloud.dc.dao.DataCenterDao;
|
||||
import com.cloud.deploy.DeployDestination;
|
||||
@ -67,9 +63,9 @@ import com.cloud.host.dao.HostDetailsDao;
|
||||
import com.cloud.network.ExternalLoadBalancerDeviceManager;
|
||||
import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl;
|
||||
import com.cloud.network.ExternalLoadBalancerDeviceVO;
|
||||
import com.cloud.network.IpAddress;
|
||||
import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState;
|
||||
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
|
||||
import com.cloud.network.IpAddress;
|
||||
import com.cloud.network.Network;
|
||||
import com.cloud.network.Network.Capability;
|
||||
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.resource.NetscalerResource;
|
||||
import com.cloud.network.rules.FirewallRule;
|
||||
import com.cloud.network.rules.LbStickinessMethod;
|
||||
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.StaticNat;
|
||||
import com.cloud.offering.NetworkOffering;
|
||||
@ -108,37 +104,50 @@ import com.cloud.vm.VirtualMachine;
|
||||
import com.cloud.vm.VirtualMachineProfile;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
@Local(value=NetworkElement.class)
|
||||
public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, NetscalerLoadBalancerElementService, ExternalLoadBalancerDeviceManager, IpDeployer, StaticNatServiceProvider {
|
||||
@Local(value = NetworkElement.class)
|
||||
public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, NetscalerLoadBalancerElementService, ExternalLoadBalancerDeviceManager, IpDeployer,
|
||||
StaticNatServiceProvider {
|
||||
|
||||
private static final Logger s_logger = Logger.getLogger(NetscalerElement.class);
|
||||
|
||||
@Inject NetworkManager _networkManager;
|
||||
@Inject ConfigurationManager _configMgr;
|
||||
@Inject NetworkServiceMapDao _ntwkSrvcDao;
|
||||
@Inject AgentManager _agentMgr;
|
||||
@Inject NetworkManager _networkMgr;
|
||||
@Inject HostDao _hostDao;
|
||||
@Inject DataCenterDao _dcDao;
|
||||
@Inject ExternalLoadBalancerDeviceDao _lbDeviceDao;
|
||||
@Inject NetworkExternalLoadBalancerDao _networkLBDao;
|
||||
@Inject PhysicalNetworkDao _physicalNetworkDao;
|
||||
@Inject NetworkDao _networkDao;
|
||||
@Inject HostDetailsDao _detailsDao;
|
||||
@Inject ConfigurationDao _configDao;
|
||||
@Inject
|
||||
NetworkManager _networkManager;
|
||||
@Inject
|
||||
ConfigurationManager _configMgr;
|
||||
@Inject
|
||||
NetworkServiceMapDao _ntwkSrvcDao;
|
||||
@Inject
|
||||
AgentManager _agentMgr;
|
||||
@Inject
|
||||
NetworkManager _networkMgr;
|
||||
@Inject
|
||||
HostDao _hostDao;
|
||||
@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) {
|
||||
DataCenter zone = _dcDao.findById(config.getDataCenterId());
|
||||
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);
|
||||
|
||||
|
||||
if (!(handleInAdvanceZone || handleInBasicZone)) {
|
||||
s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType() + " in zone of type " + zone.getNetworkType());
|
||||
return false;
|
||||
}
|
||||
|
||||
return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) &&
|
||||
_ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), service, Network.Provider.Netscaler));
|
||||
|
||||
return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), service, Network.Provider.Netscaler));
|
||||
}
|
||||
|
||||
private boolean isBasicZoneNetwok(Network config) {
|
||||
@ -147,8 +156,9 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
}
|
||||
|
||||
@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)) {
|
||||
return false;
|
||||
}
|
||||
@ -158,16 +168,17 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
} catch (InsufficientCapacityException capacityException) {
|
||||
// TODO: handle out of capacity exception gracefully in case of multple providers available
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@ -189,12 +200,12 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
public boolean destroy(Network config) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean validateLBRule(Network network, LoadBalancingRule rule) {
|
||||
public boolean validateLBRule(Network network, LoadBalancingRule rule) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyLBRules(Network config, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
|
||||
if (!canHandle(config, Service.Lb)) {
|
||||
@ -210,62 +221,61 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
|
||||
@Override
|
||||
public Map<Service, Map<Capability, String>> getCapabilities() {
|
||||
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");
|
||||
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
|
||||
|
||||
// specifies that Netscaler network element can provided both shared and isolation modes
|
||||
lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared");
|
||||
// Set capabilities for LB service
|
||||
Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
|
||||
|
||||
// Specifies that load balancing rules can be made for either TCP or UDP traffic
|
||||
lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
|
||||
|
||||
// Specifies that this element can measure network usage on a per public IP basis
|
||||
lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
|
||||
// Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
|
||||
lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn");
|
||||
|
||||
// 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;
|
||||
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);
|
||||
// specifies that Netscaler network element can provided both shared and isolation modes
|
||||
lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared");
|
||||
|
||||
method = new LbStickinessMethod(StickinessMethodType.AppCookieBased,"This is app session based sticky method, can be used only for http");
|
||||
methodList.add(method);
|
||||
method.addParam("name", true, "cookie name passed in http header by apllication to the client",false);
|
||||
// Specifies that load balancing rules can be made for either TCP or UDP traffic
|
||||
lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
|
||||
|
||||
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);
|
||||
// Specifies that this element can measure network usage on a per public IP basis
|
||||
lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
|
||||
|
||||
Gson gson = new Gson();
|
||||
String stickyMethodList = gson.toJson(methodList);
|
||||
lbCapabilities.put(Capability.SupportedStickinessMethods,stickyMethodList);
|
||||
|
||||
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;
|
||||
// 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;
|
||||
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");
|
||||
methodList.add(method);
|
||||
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.");
|
||||
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);
|
||||
|
||||
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
|
||||
@ -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");
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
@ -370,7 +380,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
// FIXME how to interpret configured capacity of the SDX device
|
||||
}
|
||||
|
||||
if(dedicatedUse != null) {
|
||||
if (dedicatedUse != null) {
|
||||
lbDeviceVo.setIsDedicatedDevice(dedicatedUse);
|
||||
}
|
||||
|
||||
@ -427,7 +437,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
Long physcialNetworkId = cmd.getPhysicalNetworkId();
|
||||
Long lbDeviceId = cmd.getLoadBalancerDeviceId();
|
||||
PhysicalNetworkVO pNetwork = null;
|
||||
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO> ();
|
||||
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO>();
|
||||
|
||||
if (physcialNetworkId == null && lbDeviceId == null) {
|
||||
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) {
|
||||
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()) {
|
||||
for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) {
|
||||
if (lbDevice.getState() == LBDeviceState.Enabled) {
|
||||
@ -503,7 +514,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
@Override
|
||||
public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
|
||||
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;
|
||||
}
|
||||
|
||||
@ -513,7 +524,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
}
|
||||
|
||||
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.NetscalerVPXLoadBalancer.getName())))) {
|
||||
return false;
|
||||
@ -521,7 +532,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean verifyServicesCombination(List<String> services) {
|
||||
return true;
|
||||
@ -552,7 +563,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
}
|
||||
|
||||
String errMsg = null;
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
|
||||
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
|
||||
if (lbDeviceVO == null) {
|
||||
try {
|
||||
lbDeviceVO = allocateLoadBalancerForNetwork(network);
|
||||
@ -586,7 +597,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
}
|
||||
|
||||
if (loadBalancersToApply.size() > 0) {
|
||||
int numLoadBalancersForCommand = loadBalancersToApply.size();
|
||||
int numLoadBalancersForCommand = loadBalancersToApply.size();
|
||||
LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
|
||||
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand);
|
||||
|
||||
@ -641,7 +652,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
}
|
||||
|
||||
SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO);
|
||||
answer = (SetStaticNatRulesAnswer )_agentMgr.send(lbDevice.getHostId(), cmd);
|
||||
answer = (SetStaticNatRulesAnswer) _agentMgr.send(lbDevice.getHostId(), cmd);
|
||||
if (answer == null) {
|
||||
return false;
|
||||
} else {
|
||||
@ -652,4 +663,5 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -44,82 +44,83 @@ import com.cloud.vm.ReservationContext;
|
||||
import com.cloud.vm.VirtualMachine;
|
||||
import com.cloud.vm.VirtualMachineProfile;
|
||||
|
||||
@Local(value=NetworkElement.class)
|
||||
@Local(value = NetworkElement.class)
|
||||
public class OvsElement extends AdapterBase implements NetworkElement {
|
||||
@Inject OvsNetworkManager _ovsVlanMgr;
|
||||
@Inject OvsTunnelManager _ovsTunnelMgr;
|
||||
|
||||
@Override
|
||||
public boolean destroy(Network network)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
@Inject
|
||||
OvsNetworkManager _ovsVlanMgr;
|
||||
@Inject
|
||||
OvsTunnelManager _ovsTunnelMgr;
|
||||
|
||||
@Override
|
||||
public Map<Service, Map<Capability, String>> getCapabilities() {
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public boolean destroy(Network network)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Provider getProvider() {
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public Map<Service, Map<Capability, String>> getCapabilities() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean implement(Network network, NetworkOffering offering,
|
||||
DeployDestination dest, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException,
|
||||
InsufficientCapacityException {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public Provider getProvider() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean prepare(Network network, NicProfile nic,
|
||||
VirtualMachineProfile<? extends VirtualMachine> vm,
|
||||
DeployDestination dest, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException,
|
||||
InsufficientCapacityException {
|
||||
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
|
||||
public boolean implement(Network network, NetworkOffering offering,
|
||||
DeployDestination dest, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException,
|
||||
InsufficientCapacityException {
|
||||
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) {
|
||||
@Override
|
||||
public boolean prepare(Network network, NicProfile nic,
|
||||
VirtualMachineProfile<? extends VirtualMachine> vm,
|
||||
DeployDestination dest, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException,
|
||||
InsufficientCapacityException {
|
||||
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;
|
||||
}
|
||||
|
||||
_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
|
||||
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
|
||||
public boolean isReady(PhysicalNetworkServiceProvider provider) {
|
||||
@ -127,8 +128,8 @@ public class OvsElement extends AdapterBase implements NetworkElement {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context)
|
||||
throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -136,7 +137,7 @@ public class OvsElement extends AdapterBase implements NetworkElement {
|
||||
public boolean canEnableIndividualServices() {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean verifyServicesCombination(List<String> services) {
|
||||
return true;
|
||||
|
||||
@ -54,14 +54,14 @@ import com.cloud.network.dao.LoadBalancerDao;
|
||||
import com.cloud.network.dao.NetworkDao;
|
||||
import com.cloud.network.dao.VirtualRouterProviderDao;
|
||||
import com.cloud.network.lb.LoadBalancingRule;
|
||||
import com.cloud.network.lb.LoadBalancingRulesManager;
|
||||
import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
|
||||
import com.cloud.network.lb.LoadBalancingRulesManager;
|
||||
import com.cloud.network.router.VirtualNetworkApplianceManager;
|
||||
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.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.RulesManager;
|
||||
import com.cloud.network.rules.StaticNat;
|
||||
@ -88,56 +88,72 @@ import com.cloud.vm.dao.DomainRouterDao;
|
||||
import com.cloud.vm.dao.UserVmDao;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
|
||||
@Local(value=NetworkElement.class)
|
||||
public class VirtualRouterElement extends AdapterBase implements VirtualRouterElementService, DhcpServiceProvider, UserDataServiceProvider, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider, LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer {
|
||||
@Local(value = NetworkElement.class)
|
||||
public class VirtualRouterElement extends AdapterBase implements VirtualRouterElementService, DhcpServiceProvider, UserDataServiceProvider, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider,
|
||||
LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer {
|
||||
private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class);
|
||||
|
||||
|
||||
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
|
||||
|
||||
@Inject NetworkDao _networksDao;
|
||||
@Inject NetworkManager _networkMgr;
|
||||
@Inject LoadBalancingRulesManager _lbMgr;
|
||||
@Inject NetworkOfferingDao _networkOfferingDao;
|
||||
@Inject VirtualNetworkApplianceManager _routerMgr;
|
||||
@Inject ConfigurationManager _configMgr;
|
||||
@Inject RulesManager _rulesMgr;
|
||||
@Inject UserVmManager _userVmMgr;
|
||||
@Inject UserVmDao _userVmDao;
|
||||
@Inject DomainRouterDao _routerDao;
|
||||
@Inject LoadBalancerDao _lbDao;
|
||||
@Inject HostDao _hostDao;
|
||||
@Inject AccountManager _accountMgr;
|
||||
@Inject ConfigurationDao _configDao;
|
||||
@Inject VirtualRouterProviderDao _vrProviderDao;
|
||||
|
||||
|
||||
@Inject
|
||||
NetworkDao _networksDao;
|
||||
@Inject
|
||||
NetworkManager _networkMgr;
|
||||
@Inject
|
||||
LoadBalancingRulesManager _lbMgr;
|
||||
@Inject
|
||||
NetworkOfferingDao _networkOfferingDao;
|
||||
@Inject
|
||||
VirtualNetworkApplianceManager _routerMgr;
|
||||
@Inject
|
||||
ConfigurationManager _configMgr;
|
||||
@Inject
|
||||
RulesManager _rulesMgr;
|
||||
@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) {
|
||||
Long physicalNetworkId = _networkMgr.getPhysicalNetworkId(network);
|
||||
if (physicalNetworkId == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Long physicalNetworkId = _networkMgr.getPhysicalNetworkId(network);
|
||||
if (physicalNetworkId == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_networkMgr.isProviderEnabledInPhysicalNetwork(physicalNetworkId, "VirtualRouter")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (service == null) {
|
||||
if (!_networkMgr.isProviderForNetwork(getProvider(), network.getId())) {
|
||||
s_logger.trace("Element " + getProvider().getName() + " is not a provider for the network " + network);
|
||||
return false;
|
||||
}
|
||||
if (!_networkMgr.isProviderForNetwork(getProvider(), network.getId())) {
|
||||
s_logger.trace("Element " + getProvider().getName() + " is not a provider for the network " + network);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!_networkMgr.isProviderSupportServiceInNetwork(network.getId(), service, getProvider())) {
|
||||
s_logger.trace("Element " + getProvider().getName() + " doesn't support service " + service.getName() + " in the network " + network);
|
||||
if (!_networkMgr.isProviderSupportServiceInNetwork(network.getId(), service, getProvider())) {
|
||||
s_logger.trace("Element " + getProvider().getName() + " doesn't support service " + service.getName() + " in the network " + network);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@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()) {
|
||||
return false;
|
||||
}
|
||||
@ -149,28 +165,28 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
|
||||
if (vm.getType() != VirtualMachine.Type.User) {
|
||||
public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
|
||||
InsufficientCapacityException, ResourceUnavailableException {
|
||||
if (vm.getType() != VirtualMachine.Type.User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!canHandle(network, null)) {
|
||||
return false;
|
||||
|
||||
if (!canHandle(network, null)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
|
||||
|
||||
NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
|
||||
if (offering.isSystemOnly()) {
|
||||
return false;
|
||||
}
|
||||
if (!_networkMgr.isProviderEnabledInPhysicalNetwork(_networkMgr.getPhysicalNetworkId(network), "VirtualRouter")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@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());
|
||||
if ((routers == null) || (routers.size() == 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());
|
||||
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());
|
||||
} else {
|
||||
return true;
|
||||
@ -196,6 +212,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* This function detects numbers like 12 ,32h ,42m .. etc,. 1) plain
|
||||
* 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;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyLBRules(Network network, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
|
||||
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());
|
||||
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());
|
||||
} else {
|
||||
return true;
|
||||
@ -323,14 +340,13 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@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());
|
||||
|
||||
|
||||
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()) {
|
||||
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;
|
||||
@ -341,26 +357,26 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean startVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException {
|
||||
if (canHandle(network, Service.Vpn)) {
|
||||
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
|
||||
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());
|
||||
return true;
|
||||
}
|
||||
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
|
||||
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());
|
||||
return true;
|
||||
}
|
||||
return _routerMgr.startRemoteAccessVpn(network, vpn, routers);
|
||||
} else {
|
||||
s_logger.debug("Element " + this.getName() + " doesn't handle createVpn command");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean stopVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException {
|
||||
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()) {
|
||||
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;
|
||||
@ -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());
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
return _routerMgr.associateIP(network, ipAddress, routers);
|
||||
} else {
|
||||
return false;
|
||||
@ -398,89 +414,124 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
public Provider getProvider() {
|
||||
return Provider.VirtualRouter;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Map<Service, Map<Capability, String>> getCapabilities() {
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
|
||||
private static String getHAProxyStickinessCapability() {
|
||||
LbStickinessMethod method;
|
||||
List <LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>(1);
|
||||
|
||||
method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is loadbalancer cookie based stickiness method.");
|
||||
List<LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>(1);
|
||||
|
||||
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("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("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);
|
||||
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);
|
||||
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(
|
||||
"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);
|
||||
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);
|
||||
|
||||
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("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("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);
|
||||
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(
|
||||
"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);
|
||||
|
||||
|
||||
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("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);
|
||||
|
||||
|
||||
Gson gson = new Gson();
|
||||
String capability = gson.toJson(methodList);
|
||||
return capability;
|
||||
}
|
||||
|
||||
private static Map<Service, Map<Capability, String>> setCapabilities() {
|
||||
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>();
|
||||
lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn,source");
|
||||
lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated");
|
||||
lbCapabilities.put(Capability.SupportedProtocols, "tcp, udp");
|
||||
|
||||
|
||||
lbCapabilities.put(Capability.SupportedStickinessMethods, getHAProxyStickinessCapability());
|
||||
|
||||
|
||||
capabilities.put(Service.Lb, lbCapabilities);
|
||||
|
||||
//Set capabilities for Firewall service
|
||||
|
||||
// Set capabilities for Firewall service
|
||||
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);
|
||||
|
||||
//Set capabilities for vpn
|
||||
|
||||
// Set capabilities for vpn
|
||||
Map<Capability, String> vpnCapabilities = new HashMap<Capability, String>();
|
||||
vpnCapabilities.put(Capability.SupportedVpnTypes, "pptp,l2tp,ipsec");
|
||||
capabilities.put(Service.Vpn, vpnCapabilities);
|
||||
|
||||
|
||||
Map<Capability, String> dnsCapabilities = new HashMap<Capability, String>();
|
||||
dnsCapabilities.put(Capability.AllowDnsSuffixModification, "true");
|
||||
capabilities.put(Service.Dns, dnsCapabilities);
|
||||
|
||||
|
||||
capabilities.put(Service.UserData, null);
|
||||
capabilities.put(Service.Dhcp, null);
|
||||
|
||||
|
||||
capabilities.put(Service.Gateway, null);
|
||||
|
||||
|
||||
Map<Capability, String> sourceNatCapabilities = new HashMap<Capability, String>();
|
||||
sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "per account");
|
||||
sourceNatCapabilities.put(Capability.RedundantRouter, "true");
|
||||
capabilities.put(Service.SourceNat, sourceNatCapabilities);
|
||||
|
||||
|
||||
capabilities.put(Service.StaticNat, null);
|
||||
capabilities.put(Service.PortForwarding, null);
|
||||
|
||||
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyStaticNats(Network config, List<? extends StaticNat> rules) throws ResourceUnavailableException {
|
||||
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());
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
return _routerMgr.applyStaticNats(config, rules, routers);
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
|
||||
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
|
||||
@ -517,9 +568,9 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@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);
|
||||
if (routers == null || routers.isEmpty()) {
|
||||
return true;
|
||||
@ -530,21 +581,21 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException{
|
||||
if (!canHandle(network, null)) {
|
||||
return false;
|
||||
}
|
||||
public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException {
|
||||
if (!canHandle(network, null)) {
|
||||
return false;
|
||||
}
|
||||
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
|
||||
if (routers == null || routers.isEmpty()) {
|
||||
s_logger.debug("Can't find virtual router element in network " + network.getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm;
|
||||
|
||||
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
|
||||
|
||||
return _routerMgr.savePasswordToRouter(network, nic, uservm, routers);
|
||||
}
|
||||
|
||||
@ -552,7 +603,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
public String getPropertiesFile() {
|
||||
return "virtualrouter_commands.properties";
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public VirtualRouterProvider configure(ConfigureVirtualRouterElementCmd cmd) {
|
||||
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());
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
element.setEnabled(cmd.getEnabled());
|
||||
_vrProviderDao.persist(element);
|
||||
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public VirtualRouterProvider addElement(Long nspId) {
|
||||
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());
|
||||
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());
|
||||
} else {
|
||||
return true;
|
||||
@ -597,7 +648,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isReady(PhysicalNetworkServiceProvider provider) {
|
||||
VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), VirtualRouterProviderType.VirtualRouter);
|
||||
@ -614,7 +665,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
if (element == null) {
|
||||
return true;
|
||||
}
|
||||
//Find domain routers
|
||||
// Find domain routers
|
||||
long elementId = element.getId();
|
||||
List<DomainRouterVO> routers = _routerDao.listByElementId(elementId);
|
||||
boolean result = true;
|
||||
@ -623,11 +674,11 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean canEnableIndividualServices() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public Long getIdByNspId(Long nspId) {
|
||||
VirtualRouterProviderVO vr = _vrProviderDao.findByNspIdAndType(nspId, VirtualRouterProviderType.VirtualRouter);
|
||||
@ -654,17 +705,17 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm;
|
||||
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
|
||||
|
||||
boolean publicNetwork = false;
|
||||
if (_networkMgr.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, getProvider())) {
|
||||
publicNetwork = true;
|
||||
}
|
||||
boolean isPodBased = (dest.getDataCenter().getNetworkType() == NetworkType.Basic || _networkMgr.isSecurityGroupSupportedInNetwork(network)) &&
|
||||
network.getTrafficType() == TrafficType.Guest;
|
||||
|
||||
network.getTrafficType() == TrafficType.Guest;
|
||||
|
||||
List<DomainRouterVO> routers;
|
||||
|
||||
|
||||
if (publicNetwork) {
|
||||
routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
|
||||
} else {
|
||||
@ -675,8 +726,9 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
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();
|
||||
if (isPodBased && _routerMgr.getDnsBasicZoneUpdate().equalsIgnoreCase("all")) {
|
||||
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)) {
|
||||
throw new ResourceUnavailableException("Can't find at least one router!", this.getClass(), 0);
|
||||
}
|
||||
|
||||
|
||||
List<VirtualRouter> rets = _routerMgr.applyDhcpEntry(network, nic, uservm, dest, context, routers);
|
||||
return (rets != null) && (!rets.isEmpty());
|
||||
}
|
||||
@ -702,17 +754,17 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>)vm;
|
||||
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
|
||||
|
||||
boolean publicNetwork = false;
|
||||
if (_networkMgr.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, getProvider())) {
|
||||
publicNetwork = true;
|
||||
}
|
||||
boolean isPodBased = (dest.getDataCenter().getNetworkType() == NetworkType.Basic || _networkMgr.isSecurityGroupSupportedInNetwork(network)) &&
|
||||
network.getTrafficType() == TrafficType.Guest;
|
||||
|
||||
network.getTrafficType() == TrafficType.Guest;
|
||||
|
||||
List<DomainRouterVO> routers;
|
||||
|
||||
|
||||
if (publicNetwork) {
|
||||
routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
|
||||
} else {
|
||||
@ -723,8 +775,9 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
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();
|
||||
if (isPodBased && _routerMgr.getDnsBasicZoneUpdate().equalsIgnoreCase("all")) {
|
||||
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)) {
|
||||
throw new ResourceUnavailableException("Can't find at least one router!", this.getClass(), 0);
|
||||
}
|
||||
|
||||
|
||||
List<VirtualRouter> rets = _routerMgr.applyUserData(network, nic, uservm, dest, context, routers);
|
||||
return (rets != null) && (!rets.isEmpty());
|
||||
}
|
||||
@ -746,7 +799,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
|
||||
Long id = cmd.getId();
|
||||
Long nspId = cmd.getNspId();
|
||||
Boolean enabled = cmd.getEnabled();
|
||||
|
||||
|
||||
SearchCriteriaService<VirtualRouterProviderVO, VirtualRouterProviderVO> sc = SearchCriteria2.create(VirtualRouterProviderVO.class);
|
||||
if (id != null) {
|
||||
sc.addAnd(sc.getEntity().getId(), Op.EQ, id);
|
||||
|
||||
@ -79,7 +79,7 @@ import com.cloud.vm.UserVmVO;
|
||||
import com.cloud.vm.dao.UserVmDao;
|
||||
|
||||
@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);
|
||||
String _name;
|
||||
|
||||
@ -97,7 +97,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
AccountManager _accountMgr;
|
||||
@Inject
|
||||
NetworkManager _networkMgr;
|
||||
@Inject
|
||||
@Inject
|
||||
UsageEventDao _usageEventDao;
|
||||
@Inject
|
||||
ConfigurationDao _configDao;
|
||||
@ -107,9 +107,9 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
PortForwardingRulesDao _pfRulesDao;
|
||||
@Inject
|
||||
UserVmDao _vmDao;
|
||||
|
||||
private boolean _elbEnabled=false;
|
||||
|
||||
|
||||
private boolean _elbEnabled = false;
|
||||
|
||||
@Override
|
||||
public boolean start() {
|
||||
return true;
|
||||
@ -124,7 +124,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
public String getName() {
|
||||
return _name;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
|
||||
_name = name;
|
||||
@ -132,73 +132,75 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
_elbEnabled = Boolean.parseBoolean(elbEnabledString);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException {
|
||||
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
|
||||
@Override
|
||||
@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);
|
||||
|
||||
|
||||
// Validate ip address
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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)) {
|
||||
throw new InvalidParameterValueException("Can specify icmpCode and icmpType for ICMP protocol only");
|
||||
}
|
||||
|
||||
|
||||
if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (portStart != null || portEnd != null)) {
|
||||
throw new InvalidParameterValueException("Can't specify start/end port when protocol is ICMP");
|
||||
}
|
||||
|
||||
|
||||
Long networkId = null;
|
||||
Long accountId = null;
|
||||
Long domainId = null;
|
||||
|
||||
|
||||
if (ipAddress != null) {
|
||||
networkId = ipAddress.getAssociatedWithNetworkId();
|
||||
accountId = ipAddress.getAllocatedToAccountId();
|
||||
domainId = ipAddress.getAllocatedInDomainId();
|
||||
networkId = ipAddress.getAssociatedWithNetworkId();
|
||||
accountId = ipAddress.getAllocatedToAccountId();
|
||||
domainId = ipAddress.getAllocatedInDomainId();
|
||||
}
|
||||
|
||||
|
||||
_networkMgr.checkIpForService(ipAddress, Service.Firewall);
|
||||
|
||||
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
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 = _firewallDao.persist(newRule);
|
||||
|
||||
if (type == FirewallRuleType.User)
|
||||
detectRulesConflict(newRule, ipAddress);
|
||||
|
||||
detectRulesConflict(newRule, ipAddress);
|
||||
|
||||
if (!_firewallDao.setStateToAdd(newRule)) {
|
||||
throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
|
||||
}
|
||||
UserContext.current().setEventDetails("Rule Id: " + newRule.getId());
|
||||
|
||||
|
||||
txn.commit();
|
||||
|
||||
return newRule;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<? extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd) {
|
||||
Long ipId = cmd.getIpAddressId();
|
||||
Long id = cmd.getId();
|
||||
|
||||
|
||||
Account caller = UserContext.current().getCaller();
|
||||
List<Long> permittedAccounts = new ArrayList<Long>();
|
||||
|
||||
@ -215,7 +217,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
Long domainId = domainIdRecursiveListProject.first();
|
||||
Boolean isRecursive = domainIdRecursiveListProject.second();
|
||||
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
|
||||
|
||||
|
||||
Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
|
||||
SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
|
||||
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
|
||||
@ -239,7 +241,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
|
||||
return _firewallDao.search(sc, filter);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
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";
|
||||
@ -251,21 +253,22 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
if (rule.getId() == newRule.getId()) {
|
||||
continue; // Skips my own rule.
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
boolean bothRulesFirewall = (rule.getPurpose() == newRule.getPurpose() && rule.getPurpose() == Purpose.Firewall);
|
||||
boolean duplicatedCidrs = false;
|
||||
if (bothRulesFirewall) {
|
||||
//Verify that the rules have different cidrs
|
||||
// Verify that the rules have different cidrs
|
||||
List<String> ruleCidrList = rule.getSourceCidrList();
|
||||
List<String> newRuleCidrList = newRule.getSourceCidrList();
|
||||
|
||||
|
||||
if (ruleCidrList == null || newRuleCidrList == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
Collection<String> similar = new HashSet<String>(ruleCidrList);
|
||||
similar.retainAll(newRuleCidrList);
|
||||
|
||||
@ -273,7 +276,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
duplicatedCidrs = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!oneOfRulesIsFirewall) {
|
||||
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());
|
||||
@ -284,57 +287,58 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
continue;
|
||||
} else if (!oneOfRulesIsFirewall && !(bothRulesFirewall && !duplicatedCidrs) && ((rule.getSourcePortStart().intValue() <= newRule.getSourcePortStart().intValue() && rule.getSourcePortEnd().intValue() >= newRule.getSourcePortStart().intValue())
|
||||
|| (rule.getSourcePortStart().intValue() <= newRule.getSourcePortEnd().intValue() && rule.getSourcePortEnd().intValue() >= newRule.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()))) {
|
||||
} else if (!oneOfRulesIsFirewall && !(bothRulesFirewall && !duplicatedCidrs)
|
||||
&& ((rule.getSourcePortStart().intValue() <= newRule.getSourcePortStart().intValue() && rule.getSourcePortEnd().intValue() >= newRule.getSourcePortStart().intValue())
|
||||
|| (rule.getSourcePortStart().intValue() <= newRule.getSourcePortEnd().intValue() && rule.getSourcePortEnd().intValue() >= newRule.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
|
||||
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()));
|
||||
|
||||
|
||||
if (!(allowPf || allowStaticNat || oneOfRulesIsFirewall)) {
|
||||
throw new NetworkRuleConflictException("The range specified, " + newRule.getSourcePortStart() + "-" + newRule.getSourcePortEnd() + ", conflicts with rule " + rule.getId()
|
||||
+ " which has " + rule.getSourcePortStart() + "-" + rule.getSourcePortEnd());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (s_logger.isDebugEnabled()) {
|
||||
s_logger.debug("No network rule conflicts detected for " + newRule + " against " + (rules.size() - 1) + " existing rules");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void validateFirewallRule(Account caller, IPAddressVO ipAddress, Integer portStart, Integer portEnd, String proto, Purpose purpose, FirewallRuleType type) {
|
||||
if (portStart != null && !NetUtils.isValidPort(portStart)) {
|
||||
throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart);
|
||||
}
|
||||
if (portEnd != null && !NetUtils.isValidPort(portEnd)) {
|
||||
throw new InvalidParameterValueException("Public port range is an invalid value: " + portEnd);
|
||||
}
|
||||
|
||||
// start port can't be bigger than end port
|
||||
if (portStart != null && portEnd != null && portStart > portEnd) {
|
||||
throw new InvalidParameterValueException("Start port can't be bigger than end port");
|
||||
}
|
||||
|
||||
if (ipAddress == null && type == FirewallRuleType.System) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (portStart != null && !NetUtils.isValidPort(portStart)) {
|
||||
throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart);
|
||||
}
|
||||
if (portEnd != null && !NetUtils.isValidPort(portEnd)) {
|
||||
throw new InvalidParameterValueException("Public port range is an invalid value: " + portEnd);
|
||||
}
|
||||
|
||||
// start port can't be bigger than end port
|
||||
if (portStart != null && portEnd != null && portStart > portEnd) {
|
||||
throw new InvalidParameterValueException("Start port can't be bigger than end port");
|
||||
}
|
||||
|
||||
if (ipAddress == null && type == FirewallRuleType.System) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate ip address
|
||||
_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");
|
||||
|
||||
}
|
||||
|
||||
|
||||
Network network = _networkMgr.getNetwork(networkId);
|
||||
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
|
||||
Map<Network.Capability, String> protocolCapabilities = null;
|
||||
|
||||
|
||||
if (purpose == Purpose.LoadBalancing) {
|
||||
if (!_elbEnabled) {
|
||||
protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.Lb);
|
||||
}
|
||||
} else if (purpose == Purpose.Firewall){
|
||||
} else if (purpose == Purpose.Firewall) {
|
||||
protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.Firewall);
|
||||
} else if (purpose == Purpose.PortForwarding) {
|
||||
protocolCapabilities = _networkMgr.getNetworkServiceCapabilities(network.getId(), Service.PortForwarding);
|
||||
}
|
||||
|
||||
if (protocolCapabilities != null) {
|
||||
String supportedProtocols = protocolCapabilities.get(Capability.SupportedProtocols).toLowerCase();
|
||||
if (!supportedProtocols.contains(proto.toLowerCase())) {
|
||||
throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId());
|
||||
} 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);
|
||||
}
|
||||
String supportedProtocols = protocolCapabilities.get(Capability.SupportedProtocols).toLowerCase();
|
||||
if (!supportedProtocols.contains(proto.toLowerCase())) {
|
||||
throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId());
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException {
|
||||
boolean success = true;
|
||||
@ -396,28 +399,27 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException {
|
||||
List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall);
|
||||
return applyFirewallRules(rules, false, caller);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyFirewallRules(List<FirewallRuleVO> rules, boolean continueOnError, Account caller) {
|
||||
|
||||
|
||||
if (rules.size() == 0) {
|
||||
s_logger.debug("There are no firewall rules to apply for ip id=" + rules);
|
||||
return true;
|
||||
}
|
||||
|
||||
for (FirewallRuleVO rule: rules){
|
||||
|
||||
for (FirewallRuleVO rule : rules) {
|
||||
// load cidrs if any
|
||||
rule.setSourceCidrList(_firewallCidrsDao.getSourceCidrs(rule.getId()));
|
||||
rule.setSourceCidrList(_firewallCidrsDao.getSourceCidrs(rule.getId()));
|
||||
}
|
||||
|
||||
if (caller != null) {
|
||||
@ -435,7 +437,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
|
||||
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) {
|
||||
throw new InvalidParameterValueException("Unable to find " + ruleId + " having purpose " + Purpose.Firewall);
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
|
||||
|
||||
revokeRule(rule, caller, userId, false);
|
||||
|
||||
boolean success = false;
|
||||
@ -465,15 +467,15 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
return success;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean revokeFirewallRule(long ruleId, boolean apply) {
|
||||
Account caller = UserContext.current().getCaller();
|
||||
long userId = UserContext.current().getCallerUserId();
|
||||
return revokeFirewallRule(ruleId, apply, caller, userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@Override
|
||||
@DB
|
||||
public void revokeRule(FirewallRuleVO rule, Account caller, long userId, boolean needUsageEvent) {
|
||||
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);
|
||||
_usageEventDao.persist(usageEvent);
|
||||
}
|
||||
|
||||
|
||||
txn.commit();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public FirewallRule getFirewallRule(long ruleId) {
|
||||
return _firewallDao.findById(ruleId);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException {
|
||||
List<FirewallRule> rules = new ArrayList<FirewallRule>();
|
||||
@ -520,7 +521,8 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@ -537,21 +539,22 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
|
||||
return rules.size() == 0;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
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
|
||||
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
|
||||
List<FirewallRuleVO> rules = _firewallDao.listByIpPurposeAndProtocolAndNotRevoked(ipAddrId, startPort, endPort, protocol, Purpose.Firewall);
|
||||
if (!rules.isEmpty()) {
|
||||
return rules.get(0);
|
||||
}
|
||||
|
||||
|
||||
List<String> oneCidr = new ArrayList<String>();
|
||||
oneCidr.add(NetUtils.ALL_CIDRS);
|
||||
return createFirewallRule(ipAddrId, caller, null, startPort, endPort, protocol, oneCidr, icmpCode, icmpType, relatedRuleId, FirewallRule.FirewallRuleType.User);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean revokeAllFirewallRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException {
|
||||
List<FirewallRule> rules = new ArrayList<FirewallRule>();
|
||||
@ -562,7 +565,8 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@ -579,22 +583,21 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
|
||||
return success && rules.size() == 0;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean revokeRelatedFirewallRule(long ruleId, boolean apply) {
|
||||
FirewallRule fwRule = _firewallDao.findByRelatedId(ruleId);
|
||||
|
||||
|
||||
if (fwRule == null) {
|
||||
s_logger.trace("No related firewall rule exists for rule id=" + ruleId + " so returning true here");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public boolean revokeFirewallRulesForVm(long vmId) {
|
||||
boolean success = true;
|
||||
@ -606,23 +609,22 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
List<PortForwardingRuleVO> pfRules = _pfRulesDao.listByVm(vmId);
|
||||
List<FirewallRuleVO> staticNatRules = _firewallDao.listStaticNatByVmId(vm.getId());
|
||||
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) {
|
||||
FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(pfRule.getId());
|
||||
if (relatedRule != null) {
|
||||
firewallRules.add(relatedRule);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for (FirewallRuleVO staticNatRule : staticNatRules) {
|
||||
FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(staticNatRule.getId());
|
||||
if (relatedRule != null) {
|
||||
firewallRules.add(relatedRule);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Set<Long> ipsToReprogram = new HashSet<Long>();
|
||||
|
||||
if (firewallRules.isEmpty()) {
|
||||
@ -642,7 +644,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
for (Long ipId : ipsToReprogram) {
|
||||
s_logger.debug("Applying firewall rules for ip address id=" + ipId + " as a part of vm expunge");
|
||||
try {
|
||||
success = success && applyFirewallRules(ipId,_accountMgr.getSystemAccount());
|
||||
success = success && applyFirewallRules(ipId, _accountMgr.getSystemAccount());
|
||||
} catch (ResourceUnavailableException ex) {
|
||||
s_logger.warn("Failed to apply port forwarding rules for ip id=" + ipId);
|
||||
success = false;
|
||||
@ -652,17 +654,18 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
|
||||
return success;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addSystemFirewallRules(IPAddressVO ip, Account acct) {
|
||||
List<FirewallRuleVO> systemRules = _firewallDao.listSystemRules();
|
||||
for (FirewallRuleVO rule : systemRules) {
|
||||
try {
|
||||
this.createFirewallRule(ip.getId(), acct, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(),
|
||||
rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), rule.getRelated(), FirewallRuleType.System);
|
||||
} catch (Exception e) {
|
||||
s_logger.debug("Failed to add system wide firewall rule, due to:" + e.toString());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean addSystemFirewallRules(IPAddressVO ip, Account acct) {
|
||||
List<FirewallRuleVO> systemRules = _firewallDao.listSystemRules();
|
||||
for (FirewallRuleVO rule : systemRules) {
|
||||
try {
|
||||
this.createFirewallRule(ip.getId(), acct, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(),
|
||||
rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), rule.getRelated(), FirewallRuleType.System);
|
||||
} catch (Exception e) {
|
||||
s_logger.debug("Failed to add system wide firewall rule, due to:" + e.toString());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -183,7 +183,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private boolean genericValidator(CreateLBStickinessPolicyCmd cmd) throws InvalidParameterValueException {
|
||||
LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId());
|
||||
/* Validation : check for valid Method name and params */
|
||||
@ -192,13 +192,13 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
boolean methodMatch = false;
|
||||
|
||||
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) {
|
||||
if (method.getMethodName().equalsIgnoreCase(cmd.getStickinessMethodName())) {
|
||||
if (method.getMethodName().equalsIgnoreCase(cmd.getStickinessMethodName())) {
|
||||
methodMatch = true;
|
||||
Map apiParamList = cmd.getparamList();
|
||||
List<LbStickinessMethodParam> methodParamList = method.getParamList();
|
||||
List<LbStickinessMethodParam> methodParamList = method.getParamList();
|
||||
Map<String, String> tempParamList = new HashMap<String, String>();
|
||||
|
||||
/*
|
||||
@ -246,15 +246,15 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
if (methodMatch == false) {
|
||||
throw new InvalidParameterValueException("Failed to match Stickiness method name for LB rule:" + cmd.getLbRuleId());
|
||||
}
|
||||
|
||||
|
||||
/* 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) {
|
||||
throw new InvalidParameterValueException("Failed to create Stickiness policy: Already policy attached " + cmd.getLbRuleId());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
@DB
|
||||
@ -265,20 +265,20 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
/* Validation : check corresponding load balancer rule exist */
|
||||
LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId());
|
||||
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);
|
||||
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 */
|
||||
if (!genericValidator(cmd)) {
|
||||
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());
|
||||
List<LbStickinessPolicy> policyList = new ArrayList<LbStickinessPolicy>();
|
||||
policyList.add(new LbStickinessPolicy(cmd.getStickinessMethodName(), lbpolicy.getParams()));
|
||||
@ -295,11 +295,11 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
_lbDao.persist(loadBalancer);
|
||||
return policy;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@DB
|
||||
@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 {
|
||||
applyLoadBalancerConfig(cmd.getLbRuleId());
|
||||
@ -310,19 +310,19 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@ActionEvent(eventType = EventTypes.EVENT_LB_STICKINESSPOLICY_DELETE, eventDescription = "revoking LB Stickiness policy ", async = true)
|
||||
public boolean deleteLBStickinessPolicy(long stickinessPolicyId) {
|
||||
UserContext caller = UserContext.current();
|
||||
LBStickinessPolicyVO stickinessPolicy = _lb2stickinesspoliciesDao.findById(stickinessPolicyId);
|
||||
|
||||
|
||||
if (stickinessPolicy == null) {
|
||||
throw new InvalidParameterException("Invalid Stickiness policy id value: " + stickinessPolicyId);
|
||||
}
|
||||
LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(stickinessPolicy.getLoadBalancerId()));
|
||||
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();
|
||||
_accountMgr.checkAccess(caller.getCaller(), null, true, loadBalancer);
|
||||
@ -335,7 +335,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
stickinessPolicy.setRevoke(true);
|
||||
_lb2stickinesspoliciesDao.persist(stickinessPolicy);
|
||||
s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", stickinesspolicyID " + stickinessPolicyId);
|
||||
|
||||
|
||||
if (!applyLoadBalancerConfig(loadBalancerId)) {
|
||||
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);
|
||||
@ -346,8 +346,8 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@DB
|
||||
@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) {
|
||||
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
|
||||
}
|
||||
|
||||
if(!success){
|
||||
throw new CloudRuntimeException("Failed to add load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
|
||||
|
||||
if (!success) {
|
||||
throw new CloudRuntimeException("Failed to add load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
|
||||
}
|
||||
|
||||
return success;
|
||||
@ -456,7 +456,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
_lb2VmMapDao.persist(map);
|
||||
s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + instanceId);
|
||||
}
|
||||
|
||||
|
||||
if (!applyLoadBalancerConfig(loadBalancerId)) {
|
||||
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);
|
||||
@ -465,9 +465,9 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
} catch (ResourceUnavailableException e) {
|
||||
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
|
||||
}
|
||||
if(!success){
|
||||
throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
|
||||
}
|
||||
if (!success) {
|
||||
throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
@ -521,9 +521,9 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
_accountMgr.checkAccess(caller, null, true, rule);
|
||||
|
||||
boolean result = deleteLoadBalancerRule(loadBalancerId, apply, caller, ctx.getCallerUserId());
|
||||
if(!result){
|
||||
throw new CloudRuntimeException("Unable to remove load balancer rule " + loadBalancerId);
|
||||
}
|
||||
if (!result) {
|
||||
throw new CloudRuntimeException("Unable to remove load balancer rule " + loadBalancerId);
|
||||
}
|
||||
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);
|
||||
_usageEventDao.persist(usageEvent);
|
||||
}
|
||||
|
||||
|
||||
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());
|
||||
if(network != null){
|
||||
if (network != null) {
|
||||
if (_networkMgr.networkIsConfiguredForExternalNetworking(network.getDataCenterId(), network.getId())) {
|
||||
_externalLBMgr.updateExternalLoadBalancerNetworkUsageStats(loadBalancerId);
|
||||
}
|
||||
@ -590,22 +590,21 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
} else {
|
||||
_firewallDao.remove(lb.getId());
|
||||
}
|
||||
|
||||
|
||||
_elbMgr.handleDeleteLoadBalancerRule(lb, callerUserId, caller);
|
||||
|
||||
|
||||
if (success) {
|
||||
s_logger.debug("Load balancer with id " + lb.getId() + " is removed successfully");
|
||||
}
|
||||
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@Override
|
||||
@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());
|
||||
|
||||
|
||||
int defPortStart = lb.getDefaultPortStart();
|
||||
int defPortEnd = lb.getDefaultPortEnd();
|
||||
|
||||
@ -618,50 +617,50 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
if ((lb.getAlgorithm() == null) || !NetUtils.isValidAlgorithm(lb.getAlgorithm())) {
|
||||
throw new InvalidParameterValueException("Invalid algorithm: " + lb.getAlgorithm());
|
||||
}
|
||||
|
||||
|
||||
Long ipAddrId = lb.getSourceIpAddressId();
|
||||
IPAddressVO ipAddressVo = null;
|
||||
if (ipAddrId != null) {
|
||||
ipAddressVo = _ipAddressDao.findById(ipAddrId);
|
||||
|
||||
ipAddressVo = _ipAddressDao.findById(ipAddrId);
|
||||
|
||||
// Validate ip address
|
||||
if (ipAddressVo == null) {
|
||||
throw new InvalidParameterValueException("Unable to create load balance rule; ip id=" + ipAddrId + " doesn't exist in the system");
|
||||
} else if (ipAddressVo.isOneToOneNat()) {
|
||||
throw new NetworkRuleConflictException("Can't do load balance on ip address: " + ipAddressVo.getAddress());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
_networkMgr.checkIpForService(ipAddressVo, Service.Lb);
|
||||
}
|
||||
|
||||
|
||||
LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb, lbOwner, lb.getNetworkId());
|
||||
if (result == null){
|
||||
IpAddress ip = null;
|
||||
Network guestNetwork = _networkMgr.getNetwork(lb.getNetworkId());
|
||||
NetworkOffering off = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
|
||||
if (off.getElasticLb() && ipAddressVo == null) {
|
||||
ip = _networkMgr.assignElasticIp(lb.getNetworkId(), lbOwner, true, false);
|
||||
lb.setSourceIpAddressId(ip.getId());
|
||||
}
|
||||
try {
|
||||
if (result == null) {
|
||||
IpAddress ip = null;
|
||||
Network guestNetwork = _networkMgr.getNetwork(lb.getNetworkId());
|
||||
NetworkOffering off = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
|
||||
if (off.getElasticLb() && ipAddressVo == null) {
|
||||
ip = _networkMgr.assignElasticIp(lb.getNetworkId(), lbOwner, true, false);
|
||||
lb.setSourceIpAddressId(ip.getId());
|
||||
}
|
||||
try {
|
||||
result = createLoadBalancer(lb, openFirewall);
|
||||
} catch (Exception ex) {
|
||||
s_logger.warn("Failed to create load balancer due to ", ex);
|
||||
} finally {
|
||||
if (result == null && ip != null) {
|
||||
s_logger.debug("Releasing elastic IP address " + ip + " as corresponding lb rule failed to create");
|
||||
_networkMgr.handleElasticIpRelease(ip);
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
s_logger.warn("Failed to create load balancer due to ", ex);
|
||||
} finally {
|
||||
if (result == null && ip != null) {
|
||||
s_logger.debug("Releasing elastic IP address " + ip + " as corresponding lb rule failed to create");
|
||||
_networkMgr.handleElasticIpRelease(ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result == null){
|
||||
throw new CloudRuntimeException("Failed to create load balancer rule: "+lb.getName());
|
||||
}
|
||||
|
||||
|
||||
if (result == null) {
|
||||
throw new CloudRuntimeException("Failed to create load balancer rule: " + lb.getName());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@DB
|
||||
public LoadBalancer createLoadBalancer(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException {
|
||||
UserContext caller = UserContext.current();
|
||||
@ -669,7 +668,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
int defPortStart = lb.getDefaultPortStart();
|
||||
int srcPortEnd = lb.getSourcePortEnd();
|
||||
long sourceIpId = lb.getSourceIpAddressId();
|
||||
|
||||
|
||||
IPAddressVO ipAddr = _ipAddressDao.findById(sourceIpId);
|
||||
Long networkId = ipAddr.getSourceNetworkId();
|
||||
// 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);
|
||||
} else if (ipAddr.isOneToOneNat()) {
|
||||
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);
|
||||
|
||||
|
||||
networkId = ipAddr.getAssociatedWithNetworkId();
|
||||
networkId = ipAddr.getAssociatedWithNetworkId();
|
||||
if (networkId == null) {
|
||||
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();
|
||||
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());
|
||||
|
||||
newRule = _lbDao.persist(newRule);
|
||||
|
||||
|
||||
if (openFirewall) {
|
||||
_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);
|
||||
_usageEventDao.persist(usageEvent);
|
||||
txn.commit();
|
||||
|
||||
|
||||
return newRule;
|
||||
} catch (Exception e) {
|
||||
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);
|
||||
} finally {
|
||||
if (!success && newRule != null) {
|
||||
|
||||
txn.start();
|
||||
|
||||
txn.start();
|
||||
_firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
|
||||
_lbDao.remove(newRule.getId());
|
||||
|
||||
|
||||
txn.commit();
|
||||
}
|
||||
}
|
||||
@ -743,8 +741,8 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
|
||||
@Override
|
||||
public boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException {
|
||||
LoadBalancerVO lb = _lbDao.findById(lbRuleId);
|
||||
//get all rules in transition state
|
||||
LoadBalancerVO lb = _lbDao.findById(lbRuleId);
|
||||
// get all rules in transition state
|
||||
List<LoadBalancerVO> lbs = _lbDao.listInTransitionStateByNetworkId(lb.getNetworkId());
|
||||
return applyLoadBalancerRules(lbs, true);
|
||||
}
|
||||
@ -768,7 +766,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
List<LbDestination> dstList = getExistingDestinations(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);
|
||||
}
|
||||
|
||||
@ -779,12 +777,12 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
|
||||
if (updateRulesInDB) {
|
||||
for (LoadBalancerVO lb : lbs) {
|
||||
boolean checkForReleaseElasticIp = false;
|
||||
txn.start();
|
||||
if (lb.getState() == FirewallRule.State.Revoke) {
|
||||
_lbDao.remove(lb.getId());
|
||||
s_logger.debug("LB " + lb.getId() + " is successfully removed");
|
||||
checkForReleaseElasticIp = true;
|
||||
boolean checkForReleaseElasticIp = false;
|
||||
txn.start();
|
||||
if (lb.getState() == FirewallRule.State.Revoke) {
|
||||
_lbDao.remove(lb.getId());
|
||||
s_logger.debug("LB " + lb.getId() + " is successfully removed");
|
||||
checkForReleaseElasticIp = true;
|
||||
} else if (lb.getState() == FirewallRule.State.Add) {
|
||||
lb.setState(FirewallRule.State.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()) {
|
||||
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");
|
||||
}
|
||||
|
||||
// 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);
|
||||
if (!stickinesspolicies.isEmpty()){
|
||||
_lb2stickinesspoliciesDao.remove(lb.getId(), true);
|
||||
if (!stickinesspolicies.isEmpty()) {
|
||||
_lb2stickinesspoliciesDao.remove(lb.getId(), true);
|
||||
s_logger.debug("Load balancer rule id " + lb.getId() + " is removed stickiness policies");
|
||||
}
|
||||
|
||||
txn.commit();
|
||||
|
||||
|
||||
if (checkForReleaseElasticIp) {
|
||||
boolean success = true;
|
||||
long count = _firewallDao.countRulesByIpId(lb.getSourceIpAddressId());
|
||||
if (count == 0) {
|
||||
try {
|
||||
success = handleElasticLBIpRelease(lb);
|
||||
} catch (Exception ex) {
|
||||
s_logger.warn("Failed to release elastic ip as a part of lb rule " + lb + " deletion due to exception ", ex);
|
||||
success = false;
|
||||
} finally {
|
||||
if (!success) {
|
||||
s_logger.warn("Failed to release elastic ip as a part of lb rule " + lb + " deletion");
|
||||
}
|
||||
}
|
||||
}
|
||||
boolean success = true;
|
||||
long count = _firewallDao.countRulesByIpId(lb.getSourceIpAddressId());
|
||||
if (count == 0) {
|
||||
try {
|
||||
success = handleElasticLBIpRelease(lb);
|
||||
} catch (Exception ex) {
|
||||
s_logger.warn("Failed to release elastic ip as a part of lb rule " + lb + " deletion due to exception ", ex);
|
||||
success = false;
|
||||
} finally {
|
||||
if (!success) {
|
||||
s_logger.warn("Failed to release elastic ip as a part of lb rule " + lb + " deletion");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected boolean handleElasticLBIpRelease(LoadBalancerVO lb) {
|
||||
IpAddress ip = _ipAddressDao.findById(lb.getSourceIpAddressId());
|
||||
boolean success = true;
|
||||
if (ip.getElastic()) {
|
||||
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())) {
|
||||
s_logger.warn("Unable to release elastic ip address id=" + lb.getSourceIpAddressId() + " as a part of delete lb rule");
|
||||
success = false;
|
||||
} else {
|
||||
s_logger.warn("Successfully released elastic ip address id=" + lb.getSourceIpAddressId() + " as a part of delete lb rule");
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
protected boolean handleElasticLBIpRelease(LoadBalancerVO lb) {
|
||||
IpAddress ip = _ipAddressDao.findById(lb.getSourceIpAddressId());
|
||||
boolean success = true;
|
||||
if (ip.getElastic()) {
|
||||
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())) {
|
||||
s_logger.warn("Unable to release elastic ip address id=" + lb.getSourceIpAddressId() + " as a part of delete lb rule");
|
||||
success = false;
|
||||
} else {
|
||||
s_logger.warn("Successfully released elastic ip address id=" + lb.getSourceIpAddressId() + " as a part of delete lb rule");
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeAllLoadBalanacersForIp(long ipId, Account caller, long callerUserId) {
|
||||
@ -886,19 +884,19 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<LbStickinessPolicy> getStickinessPolicies(long lbId) {
|
||||
List<LbStickinessPolicy> stickinessPolicies = new ArrayList<LbStickinessPolicy>();
|
||||
List<LBStickinessPolicyVO> sDbpolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(lbId);
|
||||
|
||||
|
||||
for (LBStickinessPolicyVO sDbPolicy : sDbpolicies) {
|
||||
LbStickinessPolicy sPolicy = new LbStickinessPolicy(sDbPolicy.getMethodName(), sDbPolicy.getParams(), sDbPolicy.isRevoke());
|
||||
stickinessPolicies.add(sPolicy);
|
||||
}
|
||||
return stickinessPolicies;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<LbDestination> getExistingDestinations(long lbId) {
|
||||
List<LbDestination> dstList = new ArrayList<LbDestination>();
|
||||
@ -927,7 +925,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public boolean stop() {
|
||||
return true;
|
||||
}
|
||||
@ -946,12 +944,12 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
String description = cmd.getDescription();
|
||||
String algorithm = cmd.getAlgorithm();
|
||||
LoadBalancerVO lb = _lbDao.findById(lbRuleId);
|
||||
|
||||
|
||||
if (lb == null) {
|
||||
throw new InvalidParameterValueException("Unable to find lb rule by id=" + lbRuleId);
|
||||
}
|
||||
|
||||
//check permissions
|
||||
|
||||
// check permissions
|
||||
_accountMgr.checkAccess(caller, null, true, lb);
|
||||
|
||||
if (name != null) {
|
||||
@ -980,10 +978,10 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
}
|
||||
}
|
||||
|
||||
if(!success){
|
||||
throw new CloudRuntimeException("Failed to update load balancer rule: "+lbRuleId);
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
throw new CloudRuntimeException("Failed to update load balancer rule: " + lbRuleId);
|
||||
}
|
||||
|
||||
return lb;
|
||||
}
|
||||
|
||||
@ -1037,14 +1035,17 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
|
||||
return loadBalancerInstances;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<LbStickinessMethod> getStickinessMethods(long networkid)
|
||||
public List<LbStickinessMethod> getStickinessMethods(long networkid)
|
||||
{
|
||||
String capability = getLBStickinessCapability(networkid);
|
||||
if (capability == null) return null;
|
||||
if (capability == null)
|
||||
return null;
|
||||
Gson gson = new Gson();
|
||||
java.lang.reflect.Type listType = new TypeToken<List<LbStickinessMethod>>() {}.getType();
|
||||
List<LbStickinessMethod> result = gson.fromJson(capability,listType);
|
||||
java.lang.reflect.Type listType = new TypeToken<List<LbStickinessMethod>>() {
|
||||
}.getType();
|
||||
List<LbStickinessMethod> result = gson.fromJson(capability, listType);
|
||||
return result;
|
||||
}
|
||||
|
||||
@ -1056,14 +1057,14 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
if (loadBalancer == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
_accountMgr.checkAccess(caller, null, true, loadBalancer);
|
||||
|
||||
|
||||
List<LBStickinessPolicyVO> sDbpolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(cmd.getLbRuleId());
|
||||
|
||||
|
||||
return sDbpolicies;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<LoadBalancerVO> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) {
|
||||
Long ipId = cmd.getPublicIpId();
|
||||
@ -1072,7 +1073,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
String name = cmd.getLoadBalancerRuleName();
|
||||
String keyword = cmd.getKeyword();
|
||||
Long instanceId = cmd.getVirtualMachineId();
|
||||
|
||||
|
||||
Account caller = UserContext.current().getCaller();
|
||||
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());
|
||||
Long domainId = domainIdRecursiveListProject.first();
|
||||
Boolean isRecursive = domainIdRecursiveListProject.second();
|
||||
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
|
||||
|
||||
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
|
||||
|
||||
Filter searchFilter = new Filter(LoadBalancerVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
|
||||
SearchBuilder<LoadBalancerVO> sb = _lbDao.createSearchBuilder();
|
||||
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
|
||||
|
||||
|
||||
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
|
||||
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
|
||||
sb.and("sourceIpAddress", sb.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
|
||||
@ -1104,7 +1105,7 @@ public class LoadBalancingRulesManagerImpl<Type> implements LoadBalancingRulesMa
|
||||
|
||||
SearchCriteria<LoadBalancerVO> sc = sb.create();
|
||||
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
|
||||
|
||||
|
||||
if (keyword != null) {
|
||||
SearchCriteria<LoadBalancerVO> ssc = _lbDao.createSearchCriteria();
|
||||
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
|
||||
|
||||
@ -28,28 +28,30 @@ import com.cloud.network.rules.FirewallRule.FirewallRuleType;
|
||||
import com.cloud.network.rules.FirewallRule.Purpose;
|
||||
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;
|
||||
* 1. one to one nat ip forwarding
|
||||
* 2. port forwarding
|
||||
* 3. load balancing
|
||||
*
|
||||
* 1. one to one nat ip forwarding
|
||||
* 2. port forwarding
|
||||
* 3. load balancing
|
||||
*
|
||||
* 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
|
||||
* 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.
|
||||
*
|
||||
* @param newRule the new rule created.
|
||||
* @param ipAddress ip address that back up the new rule.
|
||||
* @param newRule
|
||||
* the new rule created.
|
||||
* @param ipAddress
|
||||
* ip address that back up the new rule.
|
||||
* @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);
|
||||
|
||||
|
||||
boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException;
|
||||
|
||||
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);
|
||||
|
||||
boolean revokeFirewallRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException;
|
||||
|
||||
|
||||
/**
|
||||
* Revokes a firewall rule
|
||||
* @param ruleId the id of the rule to revoke.
|
||||
* @param caller TODO
|
||||
* @param userId TODO
|
||||
* Revokes a firewall rule
|
||||
*
|
||||
* @param ruleId
|
||||
* the id of the rule to revoke.
|
||||
* @param caller
|
||||
* TODO
|
||||
* @param userId
|
||||
* TODO
|
||||
* @return
|
||||
*/
|
||||
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;
|
||||
|
||||
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 revokeFirewallRulesForVm(long vmId);
|
||||
|
||||
|
||||
boolean addSystemFirewallRules(IPAddressVO ip, Account acct);
|
||||
|
||||
}
|
||||
|
||||
@ -26,54 +26,56 @@ import com.cloud.network.IpAddress;
|
||||
import com.cloud.user.Account;
|
||||
import com.cloud.uservm.UserVm;
|
||||
|
||||
|
||||
/**
|
||||
* Rules Manager manages the network rules created for different networks.
|
||||
*/
|
||||
public interface RulesManager extends RulesService {
|
||||
|
||||
|
||||
boolean applyPortForwardingRules(long ipAddressId, boolean continueOnError, Account caller);
|
||||
|
||||
|
||||
boolean applyStaticNatRules(long sourceIpId, boolean continueOnError, Account caller);
|
||||
|
||||
|
||||
boolean applyPortForwardingRulesForNetwork(long networkId, boolean continueOnError, Account caller);
|
||||
|
||||
|
||||
boolean applyStaticNatRulesForNetwork(long networkId, boolean continueOnError, Account caller);
|
||||
|
||||
|
||||
void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller);
|
||||
|
||||
void checkRuleAndUserVm(FirewallRule rule, UserVm userVm, Account caller);
|
||||
|
||||
|
||||
boolean revokeAllPFAndStaticNatRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException;
|
||||
|
||||
|
||||
boolean revokeAllPFStaticNatRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException;
|
||||
|
||||
|
||||
List<? extends FirewallRule> listFirewallRulesByIp(long ipAddressId);
|
||||
|
||||
|
||||
/**
|
||||
* Returns a list of port forwarding rules that are ready for application
|
||||
* to the network elements for this ip.
|
||||
*
|
||||
* @param ip
|
||||
* @return List of PortForwardingRule
|
||||
*/
|
||||
List<? extends PortForwardingRule> listPortForwardingRulesForApplication(long ipId);
|
||||
|
||||
|
||||
List<? extends PortForwardingRule> gatherPortForwardingRulesForApplication(List<? extends IpAddress> addrs);
|
||||
|
||||
boolean revokePortForwardingRulesForVm(long vmId);
|
||||
|
||||
boolean revokeStaticNatRulesForVm(long vmId);
|
||||
|
||||
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);
|
||||
|
||||
List<PortForwardingRuleVO> listByNetworkId(long networkId);
|
||||
boolean revokePortForwardingRulesForVm(long vmId);
|
||||
|
||||
boolean revokeStaticNatRulesForVm(long vmId);
|
||||
|
||||
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);
|
||||
|
||||
List<PortForwardingRuleVO> listByNetworkId(long networkId);
|
||||
|
||||
boolean applyStaticNatForIp(long sourceIpId, boolean continueOnError, Account caller, boolean forRevoke);
|
||||
|
||||
|
||||
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;
|
||||
|
||||
}
|
||||
|
||||
@ -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)
|
||||
public PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException {
|
||||
UserContext ctx = UserContext.current();
|
||||
@ -164,30 +165,30 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
Long ipAddrId = rule.getSourceIpAddressId();
|
||||
|
||||
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
|
||||
|
||||
|
||||
// Validate ip address
|
||||
if (ipAddress == null) {
|
||||
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system");
|
||||
} else if (ipAddress.isOneToOneNat()) {
|
||||
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);
|
||||
|
||||
|
||||
Long networkId = ipAddress.getAssociatedWithNetworkId();
|
||||
Long accountId = ipAddress.getAllocatedToAccountId();
|
||||
Long domainId = ipAddress.getAllocatedInDomainId();
|
||||
|
||||
|
||||
// start port can't be bigger than end port
|
||||
if (rule.getDestinationPortStart() > rule.getDestinationPortEnd()) {
|
||||
throw new InvalidParameterValueException("Start port can't be bigger than end port");
|
||||
}
|
||||
|
||||
|
||||
// check that the port ranges are of equal size
|
||||
if ((rule.getDestinationPortEnd() - rule.getDestinationPortStart()) != (rule.getSourcePortEnd() - rule.getSourcePortStart())) {
|
||||
throw new InvalidParameterValueException("Source port and destination port ranges should be of equal sizes.");
|
||||
}
|
||||
|
||||
|
||||
// validate user VM exists
|
||||
UserVm vm = _vmDao.findById(vmId);
|
||||
if (vm == null) {
|
||||
@ -195,7 +196,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
} else {
|
||||
checkRuleAndUserVm(rule, vm, caller);
|
||||
}
|
||||
|
||||
|
||||
_networkMgr.checkIpForService(ipAddress, Service.PortForwarding);
|
||||
|
||||
// Verify that vm has nic in the network
|
||||
@ -209,12 +210,12 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
|
||||
PortForwardingRuleVO newRule = new PortForwardingRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), dstIp, rule.getDestinationPortStart(),
|
||||
rule.getDestinationPortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, vmId);
|
||||
newRule = _portForwardingDao.persist(newRule);
|
||||
|
||||
//create firewallRule for 0.0.0.0/0 cidr
|
||||
|
||||
// create firewallRule for 0.0.0.0/0 cidr
|
||||
if (openFirewall) {
|
||||
_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();
|
||||
return newRule;
|
||||
} catch (Exception e) {
|
||||
|
||||
|
||||
|
||||
if (newRule != null) {
|
||||
|
||||
|
||||
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);
|
||||
_portForwardingDao.remove(newRule.getId());
|
||||
|
||||
|
||||
txn.commit();
|
||||
}
|
||||
|
||||
|
||||
if (e instanceof NetworkRuleConflictException) {
|
||||
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)
|
||||
public StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException {
|
||||
Account caller = UserContext.current().getCaller();
|
||||
@ -257,44 +258,42 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
Long ipAddrId = rule.getSourceIpAddressId();
|
||||
|
||||
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
|
||||
|
||||
|
||||
// Validate ip address
|
||||
if (ipAddress == null) {
|
||||
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) {
|
||||
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);
|
||||
|
||||
|
||||
Long networkId = ipAddress.getAssociatedWithNetworkId();
|
||||
Long accountId = ipAddress.getAllocatedToAccountId();
|
||||
Long domainId = ipAddress.getAllocatedInDomainId();
|
||||
|
||||
_networkMgr.checkIpForService(ipAddress, Service.StaticNat);
|
||||
|
||||
|
||||
Network network = _networkMgr.getNetwork(networkId);
|
||||
NetworkOffering off = _configMgr.getNetworkOffering(network.getNetworkOfferingId());
|
||||
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);
|
||||
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
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);
|
||||
|
||||
newRule = _firewallDao.persist(newRule);
|
||||
|
||||
//create firewallRule for 0.0.0.0/0 cidr
|
||||
|
||||
// create firewallRule for 0.0.0.0/0 cidr
|
||||
if (openFirewall) {
|
||||
_firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId());
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
_firewallMgr.detectRulesConflict(newRule, ipAddress);
|
||||
@ -310,15 +309,15 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
|
||||
return staticNatRule;
|
||||
} catch (Exception e) {
|
||||
|
||||
|
||||
if (newRule != null) {
|
||||
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);
|
||||
_portForwardingDao.remove(newRule.getId());
|
||||
_portForwardingDao.remove(newRule.getId());
|
||||
txn.commit();
|
||||
}
|
||||
|
||||
|
||||
if (e instanceof NetworkRuleConflictException) {
|
||||
throw (NetworkRuleConflictException) e;
|
||||
}
|
||||
@ -329,7 +328,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
@Override
|
||||
public boolean enableStaticNat(long ipId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException {
|
||||
UserContext ctx = UserContext.current();
|
||||
Account caller = ctx.getCaller();
|
||||
Account caller = ctx.getCaller();
|
||||
|
||||
// Verify input parameters
|
||||
UserVmVO vm = _vmDao.findById(vmId);
|
||||
@ -364,14 +363,14 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
|
||||
// Verify ip address parameter
|
||||
isIpReadyForStaticNat(vmId, ipAddress, caller, ctx.getCallerUserId());
|
||||
|
||||
|
||||
_networkMgr.checkIpForService(ipAddress, Service.StaticNat);
|
||||
|
||||
ipAddress.setOneToOneNat(true);
|
||||
ipAddress.setAssociatedWithVmId(vmId);
|
||||
|
||||
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");
|
||||
if (applyStaticNatForIp(ipId, false, caller, false)) {
|
||||
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 {
|
||||
if (ipAddress.isSourceNat()) {
|
||||
protected void isIpReadyForStaticNat(long vmId, IPAddressVO ipAddress, Account caller, long callerUserId) throws NetworkRuleConflictException, ResourceUnavailableException {
|
||||
if (ipAddress.isSourceNat()) {
|
||||
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()) {
|
||||
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);
|
||||
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");
|
||||
@ -406,33 +405,33 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
} 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");
|
||||
}
|
||||
|
||||
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
|
||||
@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);
|
||||
|
||||
if(!revokePortForwardingRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)){
|
||||
throw new CloudRuntimeException("Failed to delete port forwarding rule");
|
||||
if (!revokePortForwardingRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)) {
|
||||
throw new CloudRuntimeException("Failed to delete port forwarding rule");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -482,8 +481,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
|
||||
_accountMgr.checkAccess(caller, null, true, rule);
|
||||
|
||||
if(!revokeStaticNatRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)){
|
||||
throw new CloudRuntimeException("Failed to revoke forwarding rule");
|
||||
if (!revokeStaticNatRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)) {
|
||||
throw new CloudRuntimeException("Failed to revoke forwarding rule");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -537,7 +536,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean revokeStaticNatRulesForVm(long vmId) {
|
||||
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());
|
||||
Long domainId = domainIdRecursiveListProject.first();
|
||||
Boolean isRecursive = domainIdRecursiveListProject.second();
|
||||
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
|
||||
|
||||
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
|
||||
|
||||
Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
|
||||
SearchBuilder<PortForwardingRuleVO> sb = _portForwardingDao.createSearchBuilder();
|
||||
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
|
||||
|
||||
|
||||
sb.and("id", sb.entity().getId(), Op.EQ);
|
||||
sb.and("ip", sb.entity().getSourceIpAddressId(), 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);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<String> getSourceCidrs(long ruleId){
|
||||
public List<String> getSourceCidrs(long ruleId) {
|
||||
return _firewallCidrsDao.getSourceCidrs(ruleId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean applyPortForwardingRules(long ipId, boolean continueOnError, Account caller) {
|
||||
List<PortForwardingRuleVO> rules = _portForwardingDao.listForApplication(ipId);
|
||||
|
||||
|
||||
if (rules.size() == 0) {
|
||||
s_logger.debug("There are no firwall rules to apply for ip id=" + ipId);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
if (caller != null) {
|
||||
_accountMgr.checkAccess(caller, null, true, rules.toArray(new PortForwardingRuleVO[rules.size()]));
|
||||
@ -739,7 +737,6 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyStaticNatsForNetwork(long networkId, boolean continueOnError, Account caller) {
|
||||
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);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
if (caller != null) {
|
||||
_accountMgr.checkAccess(caller, null, true, ips.toArray(new IPAddressVO[ips.size()]));
|
||||
}
|
||||
|
||||
|
||||
List<StaticNat> staticNats = new ArrayList<StaticNat>();
|
||||
for (IPAddressVO ip : ips) {
|
||||
// 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);
|
||||
staticNats.add(staticNat);
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
if (!_networkMgr.applyStaticNats(staticNats, continueOnError)) {
|
||||
return false;
|
||||
@ -774,7 +771,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
|
||||
@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) {
|
||||
Account caller = UserContext.current().getCaller();
|
||||
Account caller = UserContext.current().getCaller();
|
||||
List<Long> permittedAccounts = new ArrayList<Long>();
|
||||
|
||||
if (ipId != null) {
|
||||
@ -790,16 +787,15 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
domainId = domainIdRecursiveListProject.first();
|
||||
isRecursive = domainIdRecursiveListProject.second();
|
||||
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
|
||||
|
||||
|
||||
Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, start, size);
|
||||
SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
|
||||
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
|
||||
|
||||
|
||||
sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
|
||||
sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
|
||||
sb.and("id", sb.entity().getId(), Op.EQ);
|
||||
|
||||
|
||||
if (vmId != null) {
|
||||
SearchBuilder<IPAddressVO> ipSearch = _ipAddressDao.createSearchBuilder();
|
||||
ipSearch.and("associatedWithVmId", ipSearch.entity().getAssociatedWithVmId(), Op.EQ);
|
||||
@ -809,7 +805,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
SearchCriteria<FirewallRuleVO> sc = sb.create();
|
||||
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
|
||||
sc.setParameters("purpose", Purpose.StaticNat);
|
||||
|
||||
|
||||
if (id != null) {
|
||||
sc.setParameters("id", id);
|
||||
}
|
||||
@ -828,8 +824,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
@Override
|
||||
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "applying port forwarding rule", async = true)
|
||||
public boolean applyPortForwardingRules(long ipId, Account caller) throws ResourceUnavailableException {
|
||||
if(!applyPortForwardingRules(ipId, false, caller)){
|
||||
throw new CloudRuntimeException("Failed to apply port forwarding rule");
|
||||
if (!applyPortForwardingRules(ipId, false, caller)) {
|
||||
throw new CloudRuntimeException("Failed to apply port forwarding rule");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -837,8 +833,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
@Override
|
||||
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "applying static nat rule", async = true)
|
||||
public boolean applyStaticNatRules(long ipId, Account caller) throws ResourceUnavailableException {
|
||||
if(!applyStaticNatRules(ipId, false, caller)){
|
||||
throw new CloudRuntimeException("Failed to apply static nat rule");
|
||||
if (!applyStaticNatRules(ipId, false, caller)) {
|
||||
throw new CloudRuntimeException("Failed to apply static nat rule");
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
for (FirewallRuleVO rule : staticNatRules) {
|
||||
// Mark all static nat rules as Revoke, but don't revoke them yet
|
||||
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);
|
||||
|
||||
// revoke all port forwarding rules
|
||||
success = success && applyPortForwardingRules(ipId, true, caller);
|
||||
|
||||
// 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.
|
||||
rules.addAll(_portForwardingDao.listByIpAndNotRevoked(ipId));
|
||||
@ -969,10 +964,10 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
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] = _firewallDao.persist(rules[i]);
|
||||
|
||||
|
||||
if (openFirewall) {
|
||||
_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) {
|
||||
return _portForwardingDao.listByNetwork(networkId);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException{
|
||||
UserContext ctx = UserContext.current();
|
||||
Account caller = ctx.getCaller();
|
||||
IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
|
||||
public boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException {
|
||||
UserContext ctx = UserContext.current();
|
||||
Account caller = ctx.getCaller();
|
||||
IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
|
||||
checkIpAndUserVm(ipAddress, null, caller);
|
||||
|
||||
|
||||
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();
|
||||
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 {
|
||||
boolean success = true;
|
||||
|
||||
@ -1062,8 +1059,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
if (!ipAddress.isOneToOneNat()) {
|
||||
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 {
|
||||
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)) {
|
||||
@ -1079,22 +1076,22 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
s_logger.warn("Unable to revoke all static nat rules for ip " + ipAddress);
|
||||
success = false;
|
||||
}
|
||||
|
||||
|
||||
if (success) {
|
||||
boolean isIpElastic = ipAddress.getElastic();
|
||||
|
||||
boolean isIpElastic = ipAddress.getElastic();
|
||||
|
||||
ipAddress.setOneToOneNat(false);
|
||||
ipAddress.setAssociatedWithVmId(null);
|
||||
if (isIpElastic && !releaseIpIfElastic) {
|
||||
ipAddress.setElastic(false);
|
||||
ipAddress.setElastic(false);
|
||||
}
|
||||
_ipAddressDao.update(ipAddress.getId(), ipAddress);
|
||||
|
||||
if (isIpElastic && releaseIpIfElastic && !_networkMgr.handleElasticIpRelease(ipAddress)) {
|
||||
s_logger.warn("Failed to release elastic ip address " + ipAddress);
|
||||
success = false;
|
||||
if (isIpElastic && releaseIpIfElastic && !_networkMgr.handleElasticIpRelease(ipAddress)) {
|
||||
s_logger.warn("Failed to release elastic ip address " + ipAddress);
|
||||
success = false;
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
} else {
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean applyStaticNatForIp(long sourceIpId, boolean continueOnError, Account caller, boolean forRevoke) {
|
||||
|
||||
|
||||
List<StaticNat> staticNats = new ArrayList<StaticNat>();
|
||||
IpAddress sourceIp = _ipAddressDao.findById(sourceIpId);
|
||||
|
||||
|
||||
if (!sourceIp.isOneToOneNat()) {
|
||||
s_logger.debug("Source ip id=" + sourceIpId + " is not one to one nat");
|
||||
return true;
|
||||
@ -1141,30 +1138,30 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
if (networkId == null) {
|
||||
throw new CloudRuntimeException("Ip address is not associated with any network");
|
||||
}
|
||||
|
||||
|
||||
UserVmVO vm = _vmDao.findById(sourceIp.getAssociatedWithVmId());
|
||||
Network network = _networkMgr.getNetwork(networkId);
|
||||
if (network == null) {
|
||||
throw new CloudRuntimeException("Unable to find ip address to map to in vm id=" + vm.getId());
|
||||
}
|
||||
|
||||
|
||||
if (caller != null) {
|
||||
_accountMgr.checkAccess(caller, null, true, sourceIp);
|
||||
}
|
||||
|
||||
//create new static nat rule
|
||||
// create new static nat rule
|
||||
// Get nic IP4 address
|
||||
|
||||
|
||||
String dstIp;
|
||||
if (forRevoke) {
|
||||
dstIp = _networkMgr.getIpInNetworkIncludingRemoved(sourceIp.getAssociatedWithVmId(), networkId);
|
||||
} else {
|
||||
dstIp = _networkMgr.getIpInNetwork(sourceIp.getAssociatedWithVmId(), networkId);
|
||||
}
|
||||
|
||||
|
||||
StaticNatImpl staticNat = new StaticNatImpl(sourceIp.getAllocatedToAccountId(), sourceIp.getAllocatedInDomainId(), networkId, sourceIpId, dstIp, forRevoke);
|
||||
staticNats.add(staticNat);
|
||||
|
||||
|
||||
try {
|
||||
if (!_networkMgr.applyStaticNats(staticNats, continueOnError)) {
|
||||
return false;
|
||||
@ -1176,52 +1173,51 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void enableElasticIpAndStaticNatForVm(UserVm vm, boolean getNewIp) throws InsufficientAddressCapacityException{
|
||||
boolean success = true;
|
||||
|
||||
//enable static nat if eIp capability is supported
|
||||
List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
|
||||
for (Nic nic : nics) {
|
||||
Network guestNetwork = _networkMgr.getNetwork(nic.getNetworkId());
|
||||
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
|
||||
if (offering.getElasticIp()) {
|
||||
|
||||
//check if there is already static nat enabled
|
||||
if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) {
|
||||
s_logger.debug("Vm " + vm + " already has elastic ip associated with it in guest network " + guestNetwork);
|
||||
continue;
|
||||
}
|
||||
|
||||
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);
|
||||
if (ip == null) {
|
||||
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);
|
||||
|
||||
try {
|
||||
success = enableStaticNat(ip.getId(), vm.getId());
|
||||
} 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);
|
||||
success = false;
|
||||
} 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);
|
||||
success = false;
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
s_logger.warn("Failed to enable static nat on elastic ip " + ip + " for the vm " + vm + ", releasing the ip...");
|
||||
_networkMgr.handleElasticIpRelease(ip);
|
||||
throw new CloudRuntimeException("Failed to enable static nat on elastic ip for the vm " + vm);
|
||||
} else {
|
||||
s_logger.warn("Succesfully enabled static nat on elastic ip " + ip + " for the vm " + vm);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enableElasticIpAndStaticNatForVm(UserVm vm, boolean getNewIp) throws InsufficientAddressCapacityException {
|
||||
boolean success = true;
|
||||
|
||||
// enable static nat if eIp capability is supported
|
||||
List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
|
||||
for (Nic nic : nics) {
|
||||
Network guestNetwork = _networkMgr.getNetwork(nic.getNetworkId());
|
||||
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
|
||||
if (offering.getElasticIp()) {
|
||||
|
||||
// check if there is already static nat enabled
|
||||
if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) {
|
||||
s_logger.debug("Vm " + vm + " already has elastic ip associated with it in guest network " + guestNetwork);
|
||||
continue;
|
||||
}
|
||||
|
||||
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);
|
||||
if (ip == null) {
|
||||
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);
|
||||
|
||||
try {
|
||||
success = enableStaticNat(ip.getId(), vm.getId());
|
||||
} 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);
|
||||
success = false;
|
||||
} 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);
|
||||
success = false;
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
s_logger.warn("Failed to enable static nat on elastic ip " + ip + " for the vm " + vm + ", releasing the ip...");
|
||||
_networkMgr.handleElasticIpRelease(ip);
|
||||
throw new CloudRuntimeException("Failed to enable static nat on elastic ip for the vm " + vm);
|
||||
} else {
|
||||
s_logger.warn("Succesfully enabled static nat on elastic ip " + ip + " for the vm " + vm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -36,93 +36,93 @@ import com.cloud.offering.NetworkOffering;
|
||||
import com.cloud.utils.db.GenericDao;
|
||||
|
||||
@Entity
|
||||
@Table(name="network_offerings")
|
||||
@Table(name = "network_offerings")
|
||||
public class NetworkOfferingVO implements NetworkOffering, Identity {
|
||||
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
@Column(name="id")
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
long id;
|
||||
|
||||
@Column(name="name")
|
||||
|
||||
@Column(name = "name")
|
||||
String name;
|
||||
|
||||
@Column(name="unique_name")
|
||||
|
||||
@Column(name = "unique_name")
|
||||
private String uniqueName;
|
||||
|
||||
@Column(name="display_text")
|
||||
|
||||
@Column(name = "display_text")
|
||||
String displayText;
|
||||
|
||||
@Column(name="nw_rate")
|
||||
|
||||
@Column(name = "nw_rate")
|
||||
Integer rateMbps;
|
||||
|
||||
@Column(name="mc_rate")
|
||||
|
||||
@Column(name = "mc_rate")
|
||||
Integer multicastRateMbps;
|
||||
|
||||
@Column(name="traffic_type")
|
||||
@Enumerated(value=EnumType.STRING)
|
||||
|
||||
@Column(name = "traffic_type")
|
||||
@Enumerated(value = EnumType.STRING)
|
||||
TrafficType trafficType;
|
||||
|
||||
@Column(name="specify_vlan")
|
||||
|
||||
@Column(name = "specify_vlan")
|
||||
boolean specifyVlan;
|
||||
|
||||
@Column(name="system_only")
|
||||
|
||||
@Column(name = "system_only")
|
||||
boolean systemOnly;
|
||||
|
||||
@Column(name="service_offering_id")
|
||||
|
||||
@Column(name = "service_offering_id")
|
||||
Long serviceOfferingId;
|
||||
|
||||
@Column(name="tags", length=4096)
|
||||
|
||||
@Column(name = "tags", length = 4096)
|
||||
String tags;
|
||||
|
||||
@Column(name="default")
|
||||
|
||||
@Column(name = "default")
|
||||
boolean isDefault;
|
||||
|
||||
@Column(name="availability")
|
||||
@Enumerated(value=EnumType.STRING)
|
||||
|
||||
@Column(name = "availability")
|
||||
@Enumerated(value = EnumType.STRING)
|
||||
Availability availability;
|
||||
|
||||
@Column(name="state")
|
||||
@Enumerated(value=EnumType.STRING)
|
||||
|
||||
@Column(name = "state")
|
||||
@Enumerated(value = EnumType.STRING)
|
||||
State state = State.Disabled;
|
||||
|
||||
@Column(name=GenericDao.REMOVED_COLUMN)
|
||||
|
||||
@Column(name = GenericDao.REMOVED_COLUMN)
|
||||
Date removed;
|
||||
|
||||
@Column(name=GenericDao.CREATED_COLUMN)
|
||||
|
||||
@Column(name = GenericDao.CREATED_COLUMN)
|
||||
Date created;
|
||||
|
||||
@Column(name="guest_type")
|
||||
@Enumerated(value=EnumType.STRING)
|
||||
@Column(name = "guest_type")
|
||||
@Enumerated(value = EnumType.STRING)
|
||||
Network.GuestType guestType;
|
||||
|
||||
@Column(name="dedicated_lb_service")
|
||||
|
||||
@Column(name = "dedicated_lb_service")
|
||||
boolean dedicatedLB;
|
||||
|
||||
@Column(name="shared_source_nat_service")
|
||||
|
||||
@Column(name = "shared_source_nat_service")
|
||||
boolean sharedSourceNat;
|
||||
|
||||
@Column(name="specify_ip_ranges")
|
||||
|
||||
@Column(name = "specify_ip_ranges")
|
||||
boolean specifyIpRanges = false;
|
||||
|
||||
@Column(name="sort_key")
|
||||
|
||||
@Column(name = "sort_key")
|
||||
int sortKey;
|
||||
|
||||
@Column(name="uuid")
|
||||
@Column(name = "uuid")
|
||||
String uuid;
|
||||
|
||||
@Column(name="redundant_router_service")
|
||||
|
||||
@Column(name = "redundant_router_service")
|
||||
boolean redundantRouter;
|
||||
|
||||
@Column(name="conserve_mode")
|
||||
@Column(name = "conserve_mode")
|
||||
boolean conserveMode;
|
||||
|
||||
@Column(name="elastic_ip_service")
|
||||
|
||||
@Column(name = "elastic_ip_service")
|
||||
boolean elasticIp;
|
||||
|
||||
@Column(name="elastic_lb_service")
|
||||
|
||||
@Column(name = "elastic_lb_service")
|
||||
boolean elasticLb;
|
||||
|
||||
|
||||
@Override
|
||||
public String getDisplayText() {
|
||||
return displayText;
|
||||
@ -132,7 +132,7 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public TrafficType getTrafficType() {
|
||||
return trafficType;
|
||||
@ -152,25 +152,25 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
|
||||
public Integer getRateMbps() {
|
||||
return rateMbps;
|
||||
}
|
||||
|
||||
|
||||
public Date getCreated() {
|
||||
return created;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isSystemOnly() {
|
||||
return systemOnly;
|
||||
}
|
||||
|
||||
|
||||
public Date getRemoved() {
|
||||
return removed;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
@ -186,17 +186,17 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
|
||||
public void setMulticastRateMbps(Integer multicastRateMbps) {
|
||||
this.multicastRateMbps = multicastRateMbps;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isDefault() {
|
||||
return isDefault;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean getSpecifyVlan() {
|
||||
return specifyVlan;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Availability getAvailability() {
|
||||
return availability;
|
||||
@ -205,22 +205,22 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
|
||||
public void setAvailability(Availability availability) {
|
||||
this.availability = availability;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getUniqueName() {
|
||||
return uniqueName;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void setState(State state) {
|
||||
this.state = state;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public State getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Network.GuestType getGuestType() {
|
||||
return guestType;
|
||||
@ -239,7 +239,7 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
|
||||
public boolean getDedicatedLB() {
|
||||
return dedicatedLB;
|
||||
}
|
||||
|
||||
|
||||
public void setDedicatedLb(boolean dedicatedLB) {
|
||||
this.dedicatedLB = dedicatedLB;
|
||||
}
|
||||
@ -248,7 +248,7 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
|
||||
public boolean getSharedSourceNat() {
|
||||
return sharedSourceNat;
|
||||
}
|
||||
|
||||
|
||||
public void setSharedSourceNat(boolean 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,
|
||||
Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb, boolean specifyIpRanges) {
|
||||
this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges);
|
||||
Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb,
|
||||
boolean specifyIpRanges) {
|
||||
this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges);
|
||||
this.dedicatedLB = dedicatedLb;
|
||||
this.sharedSourceNat = sharedSourceNat;
|
||||
this.redundantRouter = redundantRouter;
|
||||
this.elasticIp = elasticIp;
|
||||
this.elasticLb = elasticLb;
|
||||
}
|
||||
|
||||
|
||||
public NetworkOfferingVO() {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Network Offering for all system vms.
|
||||
*
|
||||
* @param name
|
||||
* @param trafficType
|
||||
* @param specifyIpRanges TODO
|
||||
* @param specifyIpRanges
|
||||
* TODO
|
||||
*/
|
||||
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.state = State.Enabled;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder buf = new StringBuilder("[Network Offering [");
|
||||
return buf.append(id).append("-").append(trafficType).append("-").append(name).append("]").toString();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getUuid() {
|
||||
return this.uuid;
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
|
||||
public void setUuid(String uuid) {
|
||||
this.uuid = uuid;
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
public void setSortKey(int key) {
|
||||
sortKey = key;
|
||||
sortKey = key;
|
||||
}
|
||||
|
||||
|
||||
public int getSortKey() {
|
||||
return sortKey;
|
||||
return sortKey;
|
||||
}
|
||||
|
||||
|
||||
public void setUniqueName(String uniqueName) {
|
||||
this.uniqueName = uniqueName;
|
||||
this.uniqueName = uniqueName;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -343,17 +346,18 @@ public class NetworkOfferingVO implements NetworkOffering, Identity {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getElasticIp() {
|
||||
return elasticIp;
|
||||
}
|
||||
public boolean getElasticIp() {
|
||||
return elasticIp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getElasticLb() {
|
||||
return elasticLb;
|
||||
}
|
||||
|
||||
public boolean getElasticLb() {
|
||||
return elasticLb;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getSpecifyIpRanges() {
|
||||
return specifyIpRanges;
|
||||
}
|
||||
return specifyIpRanges;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -33,32 +33,35 @@ import com.cloud.utils.db.GenericDao;
|
||||
/**
|
||||
* NetworkOfferingDao deals with searches and operations done on the
|
||||
* network_offering table.
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface NetworkOfferingDao extends GenericDao<NetworkOfferingVO, Long> {
|
||||
/**
|
||||
* Returns the network offering that matches the name.
|
||||
* @param uniqueName name
|
||||
*
|
||||
* @param uniqueName
|
||||
* name
|
||||
* @return NetworkOfferingVO
|
||||
*/
|
||||
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.
|
||||
* 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
|
||||
*/
|
||||
NetworkOfferingVO persistDefaultNetworkOffering(NetworkOfferingVO offering);
|
||||
|
||||
|
||||
List<NetworkOfferingVO> listSystemNetworkOfferings();
|
||||
|
||||
|
||||
List<NetworkOfferingVO> listByAvailability(Availability availability, boolean isSystem);
|
||||
|
||||
|
||||
List<Long> getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering);
|
||||
|
||||
|
||||
List<NetworkOfferingVO> listByTrafficTypeGuestTypeAndState(NetworkOffering.State state, TrafficType trafficType, Network.GuestType type);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -21,7 +21,6 @@
|
||||
*/
|
||||
package com.cloud.offerings.dao;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
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.Transaction;
|
||||
|
||||
@Local(value=NetworkOfferingDao.class) @DB(txn=false)
|
||||
@Local(value = NetworkOfferingDao.class)
|
||||
@DB(txn = false)
|
||||
public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Long> implements NetworkOfferingDao {
|
||||
final SearchBuilder<NetworkOfferingVO> NameSearch;
|
||||
final SearchBuilder<NetworkOfferingVO> SystemOfferingSearch;
|
||||
final SearchBuilder<NetworkOfferingVO> AvailabilitySearch;
|
||||
final SearchBuilder<NetworkOfferingVO> AllFieldsSearch;
|
||||
private final GenericSearchBuilder<NetworkOfferingVO, Long> UpgradeSearch;
|
||||
|
||||
|
||||
protected NetworkOfferingDaoImpl() {
|
||||
super();
|
||||
|
||||
|
||||
NameSearch = createSearchBuilder();
|
||||
NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ);
|
||||
NameSearch.and("uniqueName", NameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ);
|
||||
NameSearch.done();
|
||||
|
||||
|
||||
SystemOfferingSearch = createSearchBuilder();
|
||||
SystemOfferingSearch.and("system", SystemOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
|
||||
SystemOfferingSearch.done();
|
||||
|
||||
|
||||
AvailabilitySearch = createSearchBuilder();
|
||||
AvailabilitySearch.and("availability", AvailabilitySearch.entity().getAvailability(), SearchCriteria.Op.EQ);
|
||||
AvailabilitySearch.and("isSystem", AvailabilitySearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
|
||||
AvailabilitySearch.done();
|
||||
|
||||
|
||||
AllFieldsSearch = createSearchBuilder();
|
||||
AllFieldsSearch.and("trafficType", AllFieldsSearch.entity().getTrafficType(), 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.done();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public NetworkOfferingVO findByUniqueName(String uniqueName) {
|
||||
SearchCriteria<NetworkOfferingVO> sc = NameSearch.create();
|
||||
|
||||
|
||||
sc.setParameters("uniqueName", uniqueName);
|
||||
|
||||
|
||||
return findOneBy(sc);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public NetworkOfferingVO persistDefaultNetworkOffering(NetworkOfferingVO offering) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<NetworkOfferingVO> listSystemNetworkOfferings() {
|
||||
SearchCriteria<NetworkOfferingVO> sc = SystemOfferingSearch.create();
|
||||
sc.setParameters("system", true);
|
||||
return this.listIncludingRemovedBy(sc, null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<NetworkOfferingVO> listByAvailability(Availability availability, boolean isSystem) {
|
||||
SearchCriteria<NetworkOfferingVO> sc = AvailabilitySearch.create();
|
||||
@ -122,11 +122,12 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
|
||||
sc.setParameters("isSystem", isSystem);
|
||||
return listBy(sc, null);
|
||||
}
|
||||
|
||||
@Override @DB
|
||||
public boolean remove(Long networkOfferingId){
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
@Override
|
||||
@DB
|
||||
public boolean remove(Long networkOfferingId) {
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
NetworkOfferingVO offering = findById(networkOfferingId);
|
||||
offering.setUniqueName(null);
|
||||
update(networkOfferingId, offering);
|
||||
@ -134,27 +135,27 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
|
||||
txn.commit();
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<Long> getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering) {
|
||||
SearchCriteria<Long> sc = UpgradeSearch.create();
|
||||
//exclude original offering
|
||||
// exclude original offering
|
||||
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);
|
||||
|
||||
//Type of the network should be the same
|
||||
|
||||
// Type of the network should be the same
|
||||
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("state", SearchCriteria.Op.EQ, NetworkOffering.State.Enabled);
|
||||
|
||||
|
||||
return customSearch(sc, null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<NetworkOfferingVO> listByTrafficTypeGuestTypeAndState(NetworkOffering.State state, TrafficType trafficType, Network.GuestType type) {
|
||||
SearchCriteria<NetworkOfferingVO> sc = AllFieldsSearch.create();
|
||||
@ -163,4 +164,5 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
|
||||
sc.setParameters("state", state);
|
||||
return listBy(sc, null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -79,10 +79,10 @@ import com.cloud.vm.dao.VMInstanceDao;
|
||||
|
||||
import edu.emory.mathcs.backport.java.util.Arrays;
|
||||
|
||||
@Local(value = { ResourceLimitService.class})
|
||||
public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
public static final Logger s_logger = Logger.getLogger(ResourceLimitManagerImpl.class);
|
||||
|
||||
@Local(value = { ResourceLimitService.class })
|
||||
public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
|
||||
public static final Logger s_logger = Logger.getLogger(ResourceLimitManagerImpl.class);
|
||||
|
||||
private String _name;
|
||||
@Inject
|
||||
private DomainDao _domainDao;
|
||||
@ -116,14 +116,13 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
private ProjectDao _projectDao;
|
||||
@Inject
|
||||
private ProjectAccountDao _projectAccountDao;
|
||||
|
||||
|
||||
|
||||
protected SearchBuilder<ResourceCountVO> ResourceCountSearch;
|
||||
ScheduledExecutorService _rcExecutor;
|
||||
long _resourceCountCheckInterval=0;
|
||||
Map<ResourceType, Long> accountResourceLimitMap = new EnumMap<ResourceType, Long>(ResourceType.class);
|
||||
Map<ResourceType, Long> projectResourceLimitMap = new EnumMap<ResourceType, Long>(ResourceType.class);
|
||||
|
||||
long _resourceCountCheckInterval = 0;
|
||||
Map<ResourceType, Long> accountResourceLimitMap = new EnumMap<ResourceType, Long>(ResourceType.class);
|
||||
Map<ResourceType, Long> projectResourceLimitMap = new EnumMap<ResourceType, Long>(ResourceType.class);
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return _name;
|
||||
@ -131,8 +130,8 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
|
||||
@Override
|
||||
public boolean start() {
|
||||
if (_resourceCountCheckInterval > 0){
|
||||
_rcExecutor.scheduleAtFixedRate(new ResourceCountCheckTask(), _resourceCountCheckInterval, _resourceCountCheckInterval, TimeUnit.SECONDS);
|
||||
if (_resourceCountCheckInterval > 0) {
|
||||
_rcExecutor.scheduleAtFixedRate(new ResourceCountCheckTask(), _resourceCountCheckInterval, _resourceCountCheckInterval, TimeUnit.SECONDS);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -141,11 +140,11 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
public boolean stop() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
|
||||
_name = name;
|
||||
|
||||
|
||||
ResourceCountSearch = _resourceCountDao.createSearchBuilder();
|
||||
ResourceCountSearch.and("id", ResourceCountSearch.entity().getId(), SearchCriteria.Op.IN);
|
||||
ResourceCountSearch.and("accountId", ResourceCountSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
|
||||
@ -153,28 +152,28 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
ResourceCountSearch.done();
|
||||
|
||||
_resourceCountCheckInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ResourceCountCheckInterval.key()), 0);
|
||||
if (_resourceCountCheckInterval > 0){
|
||||
if (_resourceCountCheckInterval > 0) {
|
||||
_rcExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ResourceCountChecker"));
|
||||
}
|
||||
|
||||
|
||||
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.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.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.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSnapshots.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.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVolumes.key())));
|
||||
|
||||
accountResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVolumes.key())));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
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) {
|
||||
s_logger.trace("Not incrementing resource count for system accounts, returning");
|
||||
return;
|
||||
@ -182,46 +181,46 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
long numToIncrement = (delta.length == 0) ? 1 : delta[0].longValue();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
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) {
|
||||
s_logger.trace("Not decrementing resource count for system accounts, returning");
|
||||
return;
|
||||
}
|
||||
long numToDecrement = (delta.length == 0) ? 1 : delta[0].longValue();
|
||||
|
||||
|
||||
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,
|
||||
"Failed to decrement resource count of type " + type + " for account id=" + accountId + "; use updateResourceCount API to recalculate/fix the problem");
|
||||
_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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
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);
|
||||
|
||||
// Check if limit is configured for account
|
||||
if (limit != null) {
|
||||
max = limit.getMax().longValue();
|
||||
} else {
|
||||
// If the account has an no limit set, then return global default account limits
|
||||
Long value = null;
|
||||
// If the account has an no limit set, then return global default account limits
|
||||
Long value = null;
|
||||
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
|
||||
value = projectResourceLimitMap.get(type);
|
||||
value = projectResourceLimitMap.get(type);
|
||||
} else {
|
||||
value = accountResourceLimitMap.get(type);
|
||||
}
|
||||
if (value != null){
|
||||
return value;
|
||||
}
|
||||
value = accountResourceLimitMap.get(type);
|
||||
}
|
||||
if (value != null) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return max;
|
||||
@ -230,9 +229,9 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
@Override
|
||||
public long findCorrectResourceLimitForDomain(Domain domain, ResourceType type) {
|
||||
long max = Resource.RESOURCE_UNLIMITED;
|
||||
|
||||
//no limits on ROOT domain
|
||||
if(domain.getId() == Domain.ROOT_DOMAIN){
|
||||
|
||||
// no limits on ROOT domain
|
||||
if (domain.getId() == Domain.ROOT_DOMAIN) {
|
||||
return Resource.RESOURCE_UNLIMITED;
|
||||
}
|
||||
// Check account
|
||||
@ -244,8 +243,8 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
// check domain hierarchy
|
||||
Long domainId = domain.getParent();
|
||||
while ((domainId != null) && (limit == null)) {
|
||||
|
||||
if(domainId == Domain.ROOT_DOMAIN){
|
||||
|
||||
if (domainId == Domain.ROOT_DOMAIN) {
|
||||
return Resource.RESOURCE_UNLIMITED;
|
||||
}
|
||||
limit = _resourceLimitDao.findByOwnerIdAndType(domainId, ResourceOwnerType.Domain, type);
|
||||
@ -261,8 +260,9 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
return max;
|
||||
}
|
||||
|
||||
@Override @DB
|
||||
public void checkResourceLimit(Account account, ResourceType type, long... count) throws ResourceAllocationException{
|
||||
@Override
|
||||
@DB
|
||||
public void checkResourceLimit(Account account, ResourceType type, long... count) throws ResourceAllocationException {
|
||||
long numResources = ((count.length == 0) ? 1 : count[0]);
|
||||
Project project = null;
|
||||
|
||||
@ -270,15 +270,15 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
if (_accountMgr.isAdmin(account.getType())) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
|
||||
project = _projectDao.findByProjectAccountId(account.getId());
|
||||
}
|
||||
|
||||
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
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);
|
||||
SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
|
||||
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;
|
||||
if (accountLimit != Resource.RESOURCE_UNLIMITED && potentialCount > accountLimit) {
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
@ -307,8 +307,8 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
|
||||
while (domainId != null) {
|
||||
DomainVO domain = _domainDao.findById(domainId);
|
||||
//no limit check if it is ROOT domain
|
||||
if(domainId != Domain.ROOT_DOMAIN){
|
||||
// no limit check if it is ROOT domain
|
||||
if (domainId != Domain.ROOT_DOMAIN) {
|
||||
ResourceLimitVO domainLimit = _resourceLimitDao.findByOwnerIdAndType(domainId, ResourceOwnerType.Domain, type);
|
||||
if (domainLimit != null && domainLimit.getMax().longValue() != Resource.RESOURCE_UNLIMITED) {
|
||||
long domainCount = _resourceCountDao.getResourceCount(domainId, ResourceOwnerType.Domain, type);
|
||||
@ -323,151 +323,151 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
txn.commit();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<ResourceLimitVO> searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal) {
|
||||
Account caller = UserContext.current().getCaller();
|
||||
List<ResourceLimitVO> limits = new ArrayList<ResourceLimitVO>();
|
||||
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.");
|
||||
}
|
||||
}
|
||||
Account caller = UserContext.current().getCaller();
|
||||
List<ResourceLimitVO> limits = new ArrayList<ResourceLimitVO>();
|
||||
boolean isAccount = true;
|
||||
|
||||
//If id is passed in, get the record and return it if permission check has passed
|
||||
if (id != null) {
|
||||
ResourceLimitVO vo = _resourceLimitDao.findById(id);
|
||||
if (vo.getAccountId() != null) {
|
||||
_accountMgr.checkAccess(caller, null, true, _accountDao.findById(vo.getAccountId()));
|
||||
limits.add(vo);
|
||||
} else if (vo.getDomainId() != null) {
|
||||
_accountMgr.checkAccess(caller, _domainDao.findById(vo.getDomainId()));
|
||||
limits.add(vo);
|
||||
}
|
||||
|
||||
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);
|
||||
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;
|
||||
}
|
||||
|
||||
SearchCriteria<ResourceLimitVO> sc = sb.create();
|
||||
Filter filter = new Filter(ResourceLimitVO.class, "id", true, startIndex, pageSizeVal);
|
||||
|
||||
if (accountId != null) {
|
||||
sc.setParameters("accountId", accountId);
|
||||
}
|
||||
|
||||
if (domainId != null) {
|
||||
sc.setParameters("domainId", domainId);
|
||||
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;
|
||||
_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 (id != null) {
|
||||
ResourceLimitVO vo = _resourceLimitDao.findById(id);
|
||||
if (vo.getAccountId() != null) {
|
||||
_accountMgr.checkAccess(caller, null, true, _accountDao.findById(vo.getAccountId()));
|
||||
limits.add(vo);
|
||||
} else if (vo.getDomainId() != null) {
|
||||
_accountMgr.checkAccess(caller, _domainDao.findById(vo.getDomainId()));
|
||||
limits.add(vo);
|
||||
}
|
||||
|
||||
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();
|
||||
Filter filter = new Filter(ResourceLimitVO.class, "id", true, startIndex, pageSizeVal);
|
||||
|
||||
if (accountId != null) {
|
||||
sc.setParameters("accountId", accountId);
|
||||
}
|
||||
|
||||
if (domainId != null) {
|
||||
sc.setParameters("domainId", domainId);
|
||||
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
|
||||
public ResourceLimitVO updateResourceLimit(Long accountId, Long domainId, Integer typeId, Long max) {
|
||||
Account caller = UserContext.current().getCaller();
|
||||
@ -490,27 +490,27 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
throw new InvalidParameterValueException("Please specify valid resource type");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
ResourceOwnerType ownerType = null;
|
||||
Long ownerId = null;
|
||||
|
||||
|
||||
if (accountId != null) {
|
||||
Account account = _entityMgr.findById(Account.class, accountId);
|
||||
if (account.getType() == Account.ACCOUNT_ID_SYSTEM) {
|
||||
throw new InvalidParameterValueException("Can't update system account");
|
||||
}
|
||||
|
||||
|
||||
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
|
||||
_accountMgr.checkAccess(caller, AccessType.ModifyProject, true, account);
|
||||
_accountMgr.checkAccess(caller, AccessType.ModifyProject, true, account);
|
||||
} else {
|
||||
_accountMgr.checkAccess(caller, null, true, account);
|
||||
}
|
||||
|
||||
|
||||
ownerType = ResourceOwnerType.Account;
|
||||
ownerId = accountId;
|
||||
} else if (domainId != null) {
|
||||
Domain domain = _entityMgr.findById(Domain.class, domainId);
|
||||
|
||||
|
||||
_accountMgr.checkAccess(caller, domain);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
|
||||
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...
|
||||
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;
|
||||
ownerId = domainId;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (ownerId == null) {
|
||||
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
|
||||
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();
|
||||
long count=0;
|
||||
long count = 0;
|
||||
List<ResourceCountVO> counts = new ArrayList<ResourceCountVO>();
|
||||
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.");
|
||||
}
|
||||
_accountMgr.checkAccess(callerAccount, domain);
|
||||
|
||||
|
||||
if (resourceType != null) {
|
||||
resourceTypes.add(resourceType);
|
||||
} else {
|
||||
@ -588,39 +587,39 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
count = recalculateAccountResourceCount(accountId, type);
|
||||
counts.add(new ResourceCountVO(type, count, accountId, ResourceOwnerType.Account));
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
if (type.supportsOwner(ResourceOwnerType.Domain)) {
|
||||
count = recalculateDomainResourceCount(domainId, type);
|
||||
counts.add(new ResourceCountVO(type, count, domainId, ResourceOwnerType.Domain));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return counts;
|
||||
}
|
||||
|
||||
|
||||
@DB
|
||||
protected boolean updateResourceCountForAccount(long accountId, ResourceType type, boolean increment, long delta) {
|
||||
boolean result = true;
|
||||
try {
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
|
||||
Set<Long> rowsToLock = _resourceCountDao.listAllRowsToUpdate(accountId, ResourceOwnerType.Account, type);
|
||||
|
||||
//Lock rows first
|
||||
|
||||
// Lock rows first
|
||||
SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
|
||||
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) {
|
||||
if (!_resourceCountDao.updateById(rowToUpdate.getId(), increment, delta)) {
|
||||
s_logger.trace("Unable to update resource count for the row " + rowToUpdate);
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
txn.commit();
|
||||
} catch (Exception ex) {
|
||||
s_logger.error("Failed to update resource count for account id=" + accountId);
|
||||
@ -628,16 +627,16 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@DB
|
||||
protected long recalculateDomainResourceCount(long domainId, ResourceType type) {
|
||||
long newCount=0;
|
||||
long newCount = 0;
|
||||
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
|
||||
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);
|
||||
SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
|
||||
sc.setParameters("id", rowIdsToLock.toArray());
|
||||
@ -649,18 +648,18 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
List<DomainVO> domainChildren = _domainDao.findImmediateChildrenForParent(domainId);
|
||||
// for each child domain update the resource count
|
||||
if (type.supportsOwner(ResourceOwnerType.Domain)) {
|
||||
|
||||
//calculate project count here
|
||||
|
||||
// calculate project count here
|
||||
if (type == ResourceType.project) {
|
||||
newCount = newCount + _projectDao.countProjectsForDomain(domainId);
|
||||
}
|
||||
|
||||
|
||||
for (DomainVO domainChild : domainChildren) {
|
||||
long domainCount = recalculateDomainResourceCount(domainChild.getId(), type);
|
||||
newCount = newCount + domainCount; // add the child domain count to parent domain count
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (type.supportsOwner(ResourceOwnerType.Account)) {
|
||||
List<AccountVO> accounts = _accountDao.findActiveAccountsForDomain(domainId);
|
||||
for (AccountVO account : accounts) {
|
||||
@ -671,26 +670,26 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
_resourceCountDao.setResourceCount(domainId, ResourceOwnerType.Domain, type, newCount);
|
||||
|
||||
if (oldCount != newCount) {
|
||||
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." );
|
||||
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.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new CloudRuntimeException("Failed to update resource count for domain with Id " + domainId);
|
||||
} finally {
|
||||
txn.commit();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new CloudRuntimeException("Failed to update resource count for domain with Id " + domainId);
|
||||
} finally {
|
||||
txn.commit();
|
||||
}
|
||||
|
||||
return newCount;
|
||||
return newCount;
|
||||
}
|
||||
|
||||
|
||||
@DB
|
||||
protected long recalculateAccountResourceCount(long accountId, ResourceType type) {
|
||||
Long newCount=null;
|
||||
Long newCount = null;
|
||||
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
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
|
||||
SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
|
||||
sc.setParameters("accountId", accountId);
|
||||
@ -704,7 +703,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
} else if (type == Resource.ResourceType.volume) {
|
||||
newCount = _volumeDao.countAllocatedVolumesForAccount(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) {
|
||||
newCount = _snapshotDao.countSnapshotsForAccount(accountId);
|
||||
} else if (type == Resource.ResourceType.public_ip) {
|
||||
@ -712,29 +711,29 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
} else if (type == Resource.ResourceType.template) {
|
||||
newCount = _vmTemplateDao.countTemplatesForAccount(accountId);
|
||||
} else if (type == Resource.ResourceType.project) {
|
||||
newCount = _projectAccountDao.countByAccountIdAndRole(accountId, Role.Admin);
|
||||
newCount = _projectAccountDao.countByAccountIdAndRole(accountId, Role.Admin);
|
||||
} else {
|
||||
throw new InvalidParameterValueException("Unsupported resource type " + type);
|
||||
}
|
||||
_resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue());
|
||||
|
||||
if (oldCount != newCount) {
|
||||
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." );
|
||||
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.");
|
||||
}
|
||||
txn.commit();
|
||||
|
||||
|
||||
return (newCount == null) ? 0 : newCount.longValue();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public long getResourceCount(Account account, ResourceType type) {
|
||||
return _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type);
|
||||
}
|
||||
|
||||
|
||||
protected class ResourceCountCheckTask implements Runnable {
|
||||
public ResourceCountCheckTask() {
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -744,7 +743,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{
|
||||
|
||||
// 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
|
||||
for (Domain domain : domains ) {
|
||||
for (Domain domain : domains) {
|
||||
for (ResourceType type : ResourceCount.ResourceType.values()) {
|
||||
if (type.supportsOwner(ResourceOwnerType.Domain)) {
|
||||
recalculateDomainResourceCount(domain.getId(), type);
|
||||
|
||||
@ -25,11 +25,13 @@ import com.cloud.exception.InternalErrorException;
|
||||
* This is the Server that is run right before the Management Server.
|
||||
*/
|
||||
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
|
||||
* @return
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public void persistDefaultValues() throws InternalErrorException;
|
||||
|
||||
}
|
||||
|
||||
@ -108,7 +108,7 @@ import com.cloud.uuididentity.dao.IdentityDao;
|
||||
|
||||
public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
public static final Logger s_logger = Logger.getLogger(ConfigurationServerImpl.class.getName());
|
||||
|
||||
|
||||
private final ConfigurationDao _configDao;
|
||||
private final DataCenterDao _zoneDao;
|
||||
private final HostPodDao _podDao;
|
||||
@ -124,7 +124,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
private final ResourceCountDao _resourceCountDao;
|
||||
private final NetworkOfferingServiceMapDao _ntwkOfferingServiceMapDao;
|
||||
private final IdentityDao _identityDao;
|
||||
|
||||
|
||||
public ConfigurationServerImpl() {
|
||||
ComponentLocator locator = ComponentLocator.getLocator(Name);
|
||||
_configDao = locator.getDao(ConfigurationDao.class);
|
||||
@ -143,21 +143,22 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
_identityDao = locator.getDao(IdentityDao.class);
|
||||
}
|
||||
|
||||
@Override @DB
|
||||
@Override
|
||||
@DB
|
||||
public void persistDefaultValues() throws InternalErrorException {
|
||||
|
||||
|
||||
// Create system user and admin user
|
||||
saveUser();
|
||||
|
||||
|
||||
// Get init
|
||||
String init = _configDao.getValue("init");
|
||||
|
||||
|
||||
// Get domain suffix - needed for network creation
|
||||
_domainSuffix = _configDao.getValue("guest.domain.suffix");
|
||||
|
||||
|
||||
if (init == null || init.equals("false")) {
|
||||
s_logger.debug("ConfigurationServer is saving default values to the database.");
|
||||
|
||||
|
||||
// Save default Configuration Table values
|
||||
List<String> categories = Config.getCategories();
|
||||
for (String category : categories) {
|
||||
@ -165,16 +166,16 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
if (!_configDao.isPremium() && category.equals("Premium")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
List<Config> configs = Config.getConfigs(category);
|
||||
for (Config c : configs) {
|
||||
String name = c.key();
|
||||
|
||||
//if the config value already present in the db, don't insert it again
|
||||
if (_configDao.findByName(name) != null) {
|
||||
|
||||
// if the config value already present in the db, don't insert it again
|
||||
if (_configDao.findByName(name) != null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
String instance = "DEFAULT";
|
||||
String component = c.getComponent();
|
||||
String value = c.getDefaultValue();
|
||||
@ -184,7 +185,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
_configDao.persist(configVO);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
_configDao.update(Config.UseSecondaryStorageVm.key(), Config.UseSecondaryStorageVm.getCategory(), "true");
|
||||
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.");
|
||||
|
||||
_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
|
||||
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);
|
||||
// Save default disk offerings
|
||||
createdefaultDiskOffering(null, "Small", "Small Disk, 5 GB", 5, null);
|
||||
createdefaultDiskOffering(null, "Medium", "Medium Disk, 20 GB", 20, null);
|
||||
createdefaultDiskOffering(null, "Large", "Large Disk, 100 GB", 100, null);
|
||||
|
||||
|
||||
// Save the mount parent to the configuration table
|
||||
String mountParent = getMountParent();
|
||||
if (mountParent != null) {
|
||||
@ -220,32 +220,31 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
|
||||
// generate a single sign-on key
|
||||
updateSSOKey();
|
||||
|
||||
//Create default network offerings
|
||||
|
||||
// Create default network offerings
|
||||
createDefaultNetworkOfferings();
|
||||
|
||||
//Create default networks
|
||||
|
||||
// Create default networks
|
||||
createDefaultNetworks();
|
||||
|
||||
//Create userIpAddress ranges
|
||||
|
||||
|
||||
//Update existing vlans with networkId
|
||||
|
||||
// Create userIpAddress ranges
|
||||
|
||||
// Update existing vlans with networkId
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
|
||||
|
||||
List<VlanVO> vlans = _vlanDao.listAll();
|
||||
if (vlans != null && !vlans.isEmpty()) {
|
||||
for (VlanVO vlan : vlans) {
|
||||
if (vlan.getNetworkId().longValue() == 0) {
|
||||
updateVlanWithNetworkId(vlan);
|
||||
}
|
||||
|
||||
//Create vlan user_ip_address range
|
||||
|
||||
// Create vlan user_ip_address range
|
||||
String ipPange = vlan.getIpRange();
|
||||
String[] range = ipPange.split("-");
|
||||
String startIp = range[0];
|
||||
String endIp = range[1];
|
||||
|
||||
|
||||
txn.start();
|
||||
IPRangeConfig config = new IPRangeConfig();
|
||||
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();
|
||||
|
||||
|
||||
// keystore for SSL/TLS connection
|
||||
updateSSLKeystore();
|
||||
|
||||
@ -269,14 +268,13 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
|
||||
// Update the cloud identifier
|
||||
updateCloudIdentifier();
|
||||
|
||||
|
||||
updateUuids();
|
||||
|
||||
|
||||
|
||||
// Set init to true
|
||||
_configDao.update("init", "Hidden", "true");
|
||||
}
|
||||
|
||||
|
||||
private void updateUuids() {
|
||||
_identityDao.initializeDefaultUuid("disk_offering");
|
||||
_identityDao.initializeDefaultUuid("network_offerings");
|
||||
@ -297,15 +295,15 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
_identityDao.initializeDefaultUuid("networks");
|
||||
_identityDao.initializeDefaultUuid("user_ip_address");
|
||||
}
|
||||
|
||||
|
||||
private String getMountParent() {
|
||||
return getEnvironmentProperty("mount.parent");
|
||||
}
|
||||
|
||||
|
||||
private String getEnvironmentProperty(String name) {
|
||||
try {
|
||||
final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
|
||||
|
||||
|
||||
if (propsFile == null) {
|
||||
return null;
|
||||
} else {
|
||||
@ -319,8 +317,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@DB
|
||||
protected void saveUser() {
|
||||
// insert system account
|
||||
@ -339,21 +336,21 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
}
|
||||
|
||||
|
||||
// insert admin user
|
||||
long id = 2;
|
||||
String username = "admin";
|
||||
String firstname = "admin";
|
||||
String lastname = "cloud";
|
||||
String password = "password";
|
||||
|
||||
|
||||
MessageDigest md5 = null;
|
||||
try {
|
||||
md5 = MessageDigest.getInstance("MD5");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
md5.reset();
|
||||
BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));
|
||||
String pwStr = pwInt.toString(16);
|
||||
@ -376,7 +373,6 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
// now insert the user
|
||||
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " +
|
||||
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())";
|
||||
|
||||
|
||||
txn = Transaction.currentTxn();
|
||||
try {
|
||||
@ -384,8 +380,6 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
try {
|
||||
String tableName = "security_group";
|
||||
@ -396,19 +390,19 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
tableName = "network_group";
|
||||
} catch (Exception ex) {
|
||||
// if network_groups table exists, create the default security group there
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
insertSql = "SELECT * FROM " + tableName + " where account_id=2 and name='default'";
|
||||
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
|
||||
ResultSet rs = stmt.executeQuery();
|
||||
if (!rs.next()) {
|
||||
//save default security group
|
||||
// save default security group
|
||||
if (tableName.equals("security_group")) {
|
||||
insertSql = "INSERT INTO " + tableName +" (name, description, account_id, domain_id) " +
|
||||
"VALUES ('default', 'Default Security Group', 2, 1)";
|
||||
insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id) " +
|
||||
"VALUES ('default', 'Default Security Group', 2, 1)";
|
||||
} else {
|
||||
insertSql = "INSERT INTO " + tableName +" (name, description, account_id, domain_id, account_name) " +
|
||||
"VALUES ('default', 'Default Security Group', 2, 1, 'admin')";
|
||||
insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id, account_name) " +
|
||||
"VALUES ('default', 'Default Security Group', 2, 1, 'admin')";
|
||||
}
|
||||
|
||||
txn = Transaction.currentTxn();
|
||||
@ -430,7 +424,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
String currentCloudIdentifier = _configDao.getValue("cloud.identifier");
|
||||
if (currentCloudIdentifier == null || currentCloudIdentifier.isEmpty()) {
|
||||
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 {
|
||||
ou = InetAddress.getLocalHost().getCanonicalHostName();
|
||||
String[] group = ou.split("\\.");
|
||||
String[] group = ou.split("\\.");
|
||||
|
||||
// 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) {
|
||||
ou = "cloud.com";
|
||||
} else {
|
||||
@ -477,7 +471,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
|
||||
String o = ou;
|
||||
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.add("-genkey");
|
||||
script.add("-keystore", keystorePath);
|
||||
@ -498,7 +492,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
}
|
||||
|
||||
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 */
|
||||
String confPath = confFile.getParent();
|
||||
String keystorePath = confPath + "/cloud.keystore";
|
||||
@ -508,13 +502,13 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
s_logger.info("SSL keystore located at " + keystorePath);
|
||||
try {
|
||||
if (!dbExisted) {
|
||||
if (!keystoreFile.exists()) {
|
||||
if (!keystoreFile.exists()) {
|
||||
generateDefaultKeystore(keystorePath);
|
||||
s_logger.info("Generated SSL keystore.");
|
||||
}
|
||||
String base64Keystore = getBase64Keystore(keystorePath);
|
||||
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.");
|
||||
} else if (keystoreFile.exists()) { // and dbExisted
|
||||
// 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
|
||||
|
||||
String userid = System.getProperty("user.name");
|
||||
if (!userid.startsWith("cloud")){
|
||||
if (!userid.startsWith("cloud")) {
|
||||
return;
|
||||
}
|
||||
String already = _configDao.getValue("ssh.privatekey");
|
||||
@ -567,13 +561,13 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
}
|
||||
|
||||
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 (s_logger.isInfoEnabled()) {
|
||||
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");
|
||||
|
||||
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);
|
||||
} catch (EOFException 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");
|
||||
}
|
||||
String privateKey = new String(arr1).trim();
|
||||
byte[] arr2 = new byte[4094]; // configuration table column value size
|
||||
try {
|
||||
new DataInputStream(new FileInputStream(pubkeyfile)).readFully(arr2);
|
||||
} catch (EOFException e) {
|
||||
} catch (EOFException 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");
|
||||
}
|
||||
String publicKey = new String(arr2).trim();
|
||||
String publicKey = new String(arr2).trim();
|
||||
|
||||
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) " +
|
||||
"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();
|
||||
try {
|
||||
@ -608,7 +602,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
s_logger.debug("Private key inserted into database");
|
||||
}
|
||||
} 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");
|
||||
}
|
||||
|
||||
@ -619,10 +613,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
s_logger.debug("Public key inserted into database");
|
||||
}
|
||||
} 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");
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
s_logger.info("Keypairs already in database");
|
||||
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");
|
||||
injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath());
|
||||
}
|
||||
|
||||
|
||||
private void writeKeyToDisk(String key, String keyPath) {
|
||||
Script.runSimpleBashScript("mkdir -p ~/.ssh");
|
||||
File keyfile = new File( keyPath);
|
||||
File keyfile = new File(keyPath);
|
||||
if (!keyfile.exists()) {
|
||||
try {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (keyfile.exists()) {
|
||||
try {
|
||||
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 prvKey = _configDao.getValue("ssh.privatekey");
|
||||
writeKeyToDisk(prvKey, homeDir + "/.ssh/id_rsa");
|
||||
@ -673,20 +667,20 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
}
|
||||
|
||||
protected void injectSshKeysIntoSystemVmIsoPatch(String publicKeyPath, String privKeyPath) {
|
||||
String injectScript = "scripts/vm/systemvm/injectkeys.sh";
|
||||
String scriptPath = Script.findScript("" , injectScript);
|
||||
String injectScript = "scripts/vm/systemvm/injectkeys.sh";
|
||||
String scriptPath = Script.findScript("", injectScript);
|
||||
String systemVmIsoPath = Script.findScript("", "vms/systemvm.iso");
|
||||
if ( scriptPath == null ) {
|
||||
if (scriptPath == null) {
|
||||
throw new CloudRuntimeException("Unable to find key inject script " + injectScript);
|
||||
}
|
||||
if (systemVmIsoPath == null) {
|
||||
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(privKeyPath);
|
||||
command.add(systemVmIsoPath);
|
||||
|
||||
|
||||
final String result = command.execute();
|
||||
if (result != null) {
|
||||
s_logger.warn("Failed to inject generated public key into systemvm iso " + result);
|
||||
@ -697,14 +691,14 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
@DB
|
||||
protected void generateSecStorageVmCopyPassword() {
|
||||
String already = _configDao.getValue("secstorage.copy.password");
|
||||
|
||||
|
||||
if (already == null) {
|
||||
|
||||
|
||||
s_logger.info("Need to store secondary storage vm copy password in the database");
|
||||
String password = PasswordGenerator.generateRandomPassword(12);
|
||||
|
||||
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();
|
||||
try {
|
||||
@ -712,9 +706,9 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
stmt1.executeUpdate();
|
||||
s_logger.debug("secondary storage vm copy password inserted into database");
|
||||
} 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 cidrAddress = cidrPair[0];
|
||||
int cidrSize = Integer.parseInt(cidrPair[1]);
|
||||
|
||||
|
||||
if (startIp != null) {
|
||||
if (endIp == null) {
|
||||
endIp = NetUtils.getIpRangeEndIpFromCidr(cidrAddress, cidrSize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Create the new pod in the database
|
||||
String ipRange;
|
||||
if (startIp != null) {
|
||||
@ -755,17 +749,17 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
} else {
|
||||
ipRange = "";
|
||||
}
|
||||
|
||||
|
||||
HostPodVO pod = new HostPodVO(podName, zoneId, gateway, cidrAddress, cidrSize, ipRange);
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
try {
|
||||
txn.start();
|
||||
|
||||
|
||||
if (_podDao.persist(pod) == null) {
|
||||
txn.rollback();
|
||||
throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support.");
|
||||
}
|
||||
|
||||
|
||||
if (startIp != null) {
|
||||
_zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp);
|
||||
}
|
||||
@ -775,7 +769,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
if (nums > 16 || nums <= 0) {
|
||||
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);
|
||||
if (linkLocalIpRanges == null) {
|
||||
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();
|
||||
|
||||
} catch(Exception e) {
|
||||
} catch (Exception e) {
|
||||
txn.rollback();
|
||||
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.");
|
||||
}
|
||||
|
||||
|
||||
return pod;
|
||||
}
|
||||
|
||||
@ -799,7 +793,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
diskSize = diskSize * 1024 * 1024 * 1024;
|
||||
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 = _diskOfferingDao.persistDeafultDiskOffering(newDiskOffering);
|
||||
return newDiskOffering;
|
||||
@ -823,10 +817,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
t.delete(t.length() - 1, t.length());
|
||||
tags = t.toString();
|
||||
}
|
||||
|
||||
|
||||
return tags;
|
||||
}
|
||||
|
||||
|
||||
@DB
|
||||
protected void createDefaultNetworkOfferings() {
|
||||
|
||||
@ -838,21 +832,21 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering);
|
||||
NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage, true);
|
||||
storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering);
|
||||
|
||||
//populate providers
|
||||
|
||||
// populate providers
|
||||
Map<Network.Service, Network.Provider> defaultSharedNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
|
||||
defaultSharedNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
|
||||
defaultSharedNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);
|
||||
defaultSharedNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter);
|
||||
|
||||
|
||||
Map<Network.Service, Network.Provider> defaultIsolatedNetworkOfferingProviders = defaultSharedNetworkOfferingProviders;
|
||||
|
||||
|
||||
Map<Network.Service, Network.Provider> defaultSharedSGNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
|
||||
defaultSharedSGNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
|
||||
defaultSharedSGNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);
|
||||
defaultSharedSGNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter);
|
||||
defaultSharedSGNetworkOfferingProviders.put(Service.SecurityGroup, Provider.SecurityGroupProvider);
|
||||
|
||||
|
||||
Map<Network.Service, Network.Provider> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
|
||||
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dhcp, 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.PortForwarding, Provider.VirtualRouter);
|
||||
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, Provider.VirtualRouter);
|
||||
|
||||
|
||||
Map<Network.Service, Network.Provider> netscalerServiceProviders = new HashMap<Network.Service, Network.Provider>();
|
||||
netscalerServiceProviders.put(Service.Dhcp, 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.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 first network offering has to be enabled, in Advance zone - the second one
|
||||
// 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
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
//Offering #1
|
||||
|
||||
// Offering #1
|
||||
NetworkOfferingVO deafultSharedSGNetworkOffering = new NetworkOfferingVO(
|
||||
NetworkOffering.DefaultSharedNetworkOfferingWithSGService,
|
||||
"Offering for Shared Security group enabled networks",
|
||||
TrafficType.Guest,
|
||||
false, true, null, null, true, Availability.Optional,
|
||||
NetworkOffering.DefaultSharedNetworkOfferingWithSGService,
|
||||
"Offering for Shared Security group enabled networks",
|
||||
TrafficType.Guest,
|
||||
false, true, null, null, true, Availability.Optional,
|
||||
null, Network.GuestType.Shared, true, true);
|
||||
|
||||
|
||||
deafultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled);
|
||||
deafultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(deafultSharedSGNetworkOffering);
|
||||
|
||||
|
||||
for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) {
|
||||
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(deafultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service));
|
||||
_ntwkOfferingServiceMapDao.persist(offService);
|
||||
s_logger.trace("Added service for the network offering: " + offService);
|
||||
}
|
||||
|
||||
//Offering #2
|
||||
|
||||
// Offering #2
|
||||
NetworkOfferingVO defaultSharedNetworkOffering = new NetworkOfferingVO(
|
||||
NetworkOffering.DefaultSharedNetworkOffering,
|
||||
"Offering for Shared networks",
|
||||
TrafficType.Guest,
|
||||
false, true, null, null, true, Availability.Optional,
|
||||
NetworkOffering.DefaultSharedNetworkOffering,
|
||||
"Offering for Shared networks",
|
||||
TrafficType.Guest,
|
||||
false, true, null, null, true, Availability.Optional,
|
||||
null, Network.GuestType.Shared, true, true);
|
||||
|
||||
|
||||
defaultSharedNetworkOffering.setState(NetworkOffering.State.Enabled);
|
||||
defaultSharedNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedNetworkOffering);
|
||||
|
||||
|
||||
for (Service service : defaultSharedNetworkOfferingProviders.keySet()) {
|
||||
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedNetworkOffering.getId(), service, defaultSharedNetworkOfferingProviders.get(service));
|
||||
_ntwkOfferingServiceMapDao.persist(offService);
|
||||
s_logger.trace("Added service for the network offering: " + offService);
|
||||
}
|
||||
|
||||
//Offering #3
|
||||
|
||||
// Offering #3
|
||||
NetworkOfferingVO defaultIsolatedSourceNatEnabledNetworkOffering = new NetworkOfferingVO(
|
||||
NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService,
|
||||
"Offering for Isolated networks with Source Nat service enabled",
|
||||
TrafficType.Guest,
|
||||
false, false, null, null, true, Availability.Required,
|
||||
NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService,
|
||||
"Offering for Isolated networks with Source Nat service enabled",
|
||||
TrafficType.Guest,
|
||||
false, false, null, null, true, Availability.Required,
|
||||
null, Network.GuestType.Isolated, true, false);
|
||||
|
||||
|
||||
defaultIsolatedSourceNatEnabledNetworkOffering.setState(NetworkOffering.State.Enabled);
|
||||
defaultIsolatedSourceNatEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedSourceNatEnabledNetworkOffering);
|
||||
|
||||
|
||||
|
||||
for (Service service : defaultIsolatedSourceNatEnabledNetworkOfferingProviders.keySet()) {
|
||||
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service));
|
||||
_ntwkOfferingServiceMapDao.persist(offService);
|
||||
s_logger.trace("Added service for the network offering: " + offService);
|
||||
}
|
||||
|
||||
//Offering #4
|
||||
|
||||
// Offering #4
|
||||
NetworkOfferingVO defaultIsolatedEnabledNetworkOffering = new NetworkOfferingVO(
|
||||
NetworkOffering.DefaultIsolatedNetworkOffering,
|
||||
"Offering for Isolated networks with no Source Nat service",
|
||||
TrafficType.Guest,
|
||||
false, true, null, null, true, Availability.Optional,
|
||||
NetworkOffering.DefaultIsolatedNetworkOffering,
|
||||
"Offering for Isolated networks with no Source Nat service",
|
||||
TrafficType.Guest,
|
||||
false, true, null, null, true, Availability.Optional,
|
||||
null, Network.GuestType.Isolated, true, true);
|
||||
|
||||
|
||||
defaultIsolatedEnabledNetworkOffering.setState(NetworkOffering.State.Enabled);
|
||||
defaultIsolatedEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedEnabledNetworkOffering);
|
||||
|
||||
|
||||
for (Service service : defaultIsolatedNetworkOfferingProviders.keySet()) {
|
||||
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedEnabledNetworkOffering.getId(), service, defaultIsolatedNetworkOfferingProviders.get(service));
|
||||
_ntwkOfferingServiceMapDao.persist(offService);
|
||||
s_logger.trace("Added service for the network offering: " + offService);
|
||||
}
|
||||
|
||||
//Offering #5
|
||||
|
||||
// Offering #5
|
||||
NetworkOfferingVO defaultNetscalerNetworkOffering = new NetworkOfferingVO(
|
||||
NetworkOffering.DefaultSharedEIPandELBNetworkOffering,
|
||||
"Offering for Shared networks with Elastic IP and Elastic LB capabilities",
|
||||
TrafficType.Guest,
|
||||
false, true, null, null, true, Availability.Optional,
|
||||
NetworkOffering.DefaultSharedEIPandELBNetworkOffering,
|
||||
"Offering for Shared networks with Elastic IP and Elastic LB capabilities",
|
||||
TrafficType.Guest,
|
||||
false, true, null, null, true, Availability.Optional,
|
||||
null, Network.GuestType.Shared, true, false, false, false, true, true, true);
|
||||
|
||||
|
||||
defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled);
|
||||
defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering);
|
||||
|
||||
|
||||
for (Service service : netscalerServiceProviders.keySet()) {
|
||||
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultNetscalerNetworkOffering.getId(), service, netscalerServiceProviders.get(service));
|
||||
_ntwkOfferingServiceMapDao.persist(offService);
|
||||
s_logger.trace("Added service for the network offering: " + offService);
|
||||
}
|
||||
|
||||
|
||||
txn.commit();
|
||||
}
|
||||
|
||||
|
||||
private void createDefaultNetworks() {
|
||||
List<DataCenterVO> zones = _dataCenterDao.listAll();
|
||||
long id = 1;
|
||||
|
||||
|
||||
HashMap<TrafficType, String> guruNames = new HashMap<TrafficType, String>();
|
||||
guruNames.put(TrafficType.Public, PublicNetworkGuru.class.getSimpleName());
|
||||
guruNames.put(TrafficType.Management, PodBasedNetworkGuru.class.getSimpleName());
|
||||
guruNames.put(TrafficType.Control, ControlNetworkGuru.class.getSimpleName());
|
||||
guruNames.put(TrafficType.Storage, StorageNetworkGuru.class.getSimpleName());
|
||||
guruNames.put(TrafficType.Guest, DirectPodBasedNetworkGuru.class.getSimpleName());
|
||||
|
||||
|
||||
for (DataCenterVO zone : zones) {
|
||||
long zoneId = zone.getId();
|
||||
long accountId = 1L;
|
||||
Long domainId = zone.getDomainId();
|
||||
|
||||
|
||||
if (domainId == null) {
|
||||
domainId = 1L;
|
||||
}
|
||||
//Create default networks - system only
|
||||
// Create default networks - system only
|
||||
List<NetworkOfferingVO> ntwkOff = _networkOfferingDao.listSystemNetworkOfferings();
|
||||
|
||||
|
||||
for (NetworkOfferingVO offering : ntwkOff) {
|
||||
if (offering.isSystemOnly()) {
|
||||
long related = id;
|
||||
long networkOfferingId = offering.getId();
|
||||
Mode mode = Mode.Static;
|
||||
String networkDomain = null;
|
||||
|
||||
|
||||
BroadcastDomainType broadcastDomainType = null;
|
||||
TrafficType trafficType= offering.getTrafficType();
|
||||
|
||||
TrafficType trafficType = offering.getTrafficType();
|
||||
|
||||
boolean specifyIpRanges = false;
|
||||
|
||||
if (trafficType == TrafficType.Management) {
|
||||
@ -1010,15 +1003,16 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
broadcastDomainType = BroadcastDomainType.LinkLocal;
|
||||
} else if (offering.getTrafficType() == TrafficType.Public) {
|
||||
if ((zone.getNetworkType() == NetworkType.Advanced && !zone.isSecurityGroupEnabled()) || zone.getNetworkType() == NetworkType.Basic) {
|
||||
specifyIpRanges = true;
|
||||
specifyIpRanges = true;
|
||||
broadcastDomainType = BroadcastDomainType.Vlan;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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.setDns1(zone.getDns1());
|
||||
network.setDns2(zone.getDns2());
|
||||
@ -1026,50 +1020,48 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
_networkDao.persist(network, false, getServicesAndProvidersForNetwork(networkOfferingId));
|
||||
id++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void updateVlanWithNetworkId(VlanVO vlan) {
|
||||
long zoneId = vlan.getDataCenterId();
|
||||
long networkId = 0L;
|
||||
DataCenterVO zone = _zoneDao.findById(zoneId);
|
||||
|
||||
|
||||
if (zone.getNetworkType() == NetworkType.Advanced) {
|
||||
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Public);
|
||||
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Public);
|
||||
} else {
|
||||
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Guest);
|
||||
}
|
||||
|
||||
|
||||
vlan.setNetworkId(networkId);
|
||||
_vlanDao.update(vlan.getId(), vlan);
|
||||
}
|
||||
|
||||
|
||||
private long getSystemNetworkIdByZoneAndTrafficType(long zoneId, TrafficType trafficType) {
|
||||
//find system public network offering
|
||||
// find system public network offering
|
||||
Long networkOfferingId = null;
|
||||
List<NetworkOfferingVO> offerings = _networkOfferingDao.listSystemNetworkOfferings();
|
||||
for (NetworkOfferingVO offering: offerings) {
|
||||
for (NetworkOfferingVO offering : offerings) {
|
||||
if (offering.getTrafficType() == trafficType) {
|
||||
networkOfferingId = offering.getId();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (networkOfferingId == null) {
|
||||
throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType);
|
||||
}
|
||||
|
||||
|
||||
List<NetworkVO> networks = _networkDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId);
|
||||
if (networks == null || networks.isEmpty()) {
|
||||
throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId);
|
||||
}
|
||||
return networks.get(0).getId();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@DB
|
||||
public void updateResourceCount() {
|
||||
ResourceType[] resourceTypes = Resource.ResourceType.values();
|
||||
@ -1077,10 +1069,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
List<DomainVO> domains = _domainDao.listAllIncludingRemoved();
|
||||
List<ResourceCountVO> domainResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Domain);
|
||||
List<ResourceCountVO> accountResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Account);
|
||||
|
||||
|
||||
List<ResourceType> accountSupportedResourceTypes = new ArrayList<ResourceType>();
|
||||
List<ResourceType> domainSupportedResourceTypes = new ArrayList<ResourceType>();
|
||||
|
||||
|
||||
for (ResourceType resourceType : resourceTypes) {
|
||||
if (resourceType.supportsOwner(ResourceOwnerType.Account)) {
|
||||
accountSupportedResourceTypes.add(resourceType);
|
||||
@ -1089,15 +1081,14 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
domainSupportedResourceTypes.add(resourceType);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
int accountExpectedCount = accountSupportedResourceTypes.size();
|
||||
int domainExpectedCount = domainSupportedResourceTypes.size();
|
||||
|
||||
|
||||
if ((domainResourceCount.size() < domainExpectedCount * domains.size())) {
|
||||
s_logger.debug("resource_count table has records missing for some domains...going to insert them");
|
||||
for (DomainVO domain : domains) {
|
||||
//Lock domain
|
||||
// Lock domain
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
_domainDao.lockRow(domain.getId(), true);
|
||||
@ -1119,11 +1110,11 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
txn.commit();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ((accountResourceCount.size() < accountExpectedCount * accounts.size())) {
|
||||
s_logger.debug("resource_count table has records missing for some accounts...going to insert them");
|
||||
for (AccountVO account : accounts) {
|
||||
//lock account
|
||||
// lock account
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
_accountDao.lockRow(account.getId(), true);
|
||||
@ -1132,7 +1123,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
for (ResourceCountVO accountCount : accountCounts) {
|
||||
accountCountStr.add(accountCount.getType().toString());
|
||||
}
|
||||
|
||||
|
||||
if (accountCountStr.size() < accountExpectedCount) {
|
||||
for (ResourceType resourceType : accountSupportedResourceTypes) {
|
||||
if (!accountCountStr.contains(resourceType.toString())) {
|
||||
@ -1142,23 +1133,23 @@ public class ConfigurationServerImpl implements ConfigurationServer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
txn.commit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Map<String, String> getServicesAndProvidersForNetwork(long networkOfferingId) {
|
||||
Map<String, String> svcProviders = new HashMap<String, String>();
|
||||
List<NetworkOfferingServiceMapVO> servicesMap = _ntwkOfferingServiceMapDao.listByNetworkOfferingId(networkOfferingId);
|
||||
|
||||
|
||||
for (NetworkOfferingServiceMapVO serviceMap : servicesMap) {
|
||||
if (svcProviders.containsKey(serviceMap.getService())) {
|
||||
continue;
|
||||
}
|
||||
svcProviders.put(serviceMap.getService(), serviceMap.getProvider());
|
||||
}
|
||||
svcProviders.put(serviceMap.getService(), serviceMap.getProvider());
|
||||
}
|
||||
|
||||
|
||||
return svcProviders;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -23,11 +23,11 @@ import java.util.Set;
|
||||
import com.cloud.domain.Domain;
|
||||
import com.cloud.domain.DomainVO;
|
||||
|
||||
public interface DomainManager extends DomainService{
|
||||
public interface DomainManager extends DomainService {
|
||||
Set<Long> getDomainChildrenIds(String parentDomainPath);
|
||||
|
||||
Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain);
|
||||
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
DomainVO findDomainByPath(String domainPath);
|
||||
|
||||
|
||||
Set<Long> getDomainParentIds(long domainId);
|
||||
|
||||
|
||||
boolean removeDomain(long domainId);
|
||||
|
||||
|
||||
List<? extends Domain> findInactiveDomains();
|
||||
|
||||
boolean deleteDomain(DomainVO domain, Boolean cleanup);
|
||||
|
||||
@ -57,9 +57,9 @@ import com.cloud.utils.exception.CloudRuntimeException;
|
||||
import com.cloud.utils.net.NetUtils;
|
||||
|
||||
@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);
|
||||
|
||||
|
||||
private String _name;
|
||||
@Inject
|
||||
private DomainDao _domainDao;
|
||||
@ -71,14 +71,14 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
|
||||
private AccountDao _accountDao;
|
||||
@Inject
|
||||
private DiskOfferingDao _diskOfferingDao;
|
||||
@Inject
|
||||
@Inject
|
||||
private ServiceOfferingDao _offeringsDao;
|
||||
|
||||
|
||||
@Override
|
||||
public Domain getDomain(long domainId) {
|
||||
return _domainDao.findById(domainId);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return _name;
|
||||
@ -93,34 +93,34 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
|
||||
public boolean stop() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
|
||||
_name = name;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Set<Long> getDomainChildrenIds(String parentDomainPath) {
|
||||
Set<Long> childDomains = new HashSet<Long>();
|
||||
SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
|
||||
sc.addAnd("path", SearchCriteria.Op.LIKE, parentDomainPath + "%");
|
||||
|
||||
|
||||
List<DomainVO> domains = _domainDao.search(sc, null);
|
||||
|
||||
|
||||
for (DomainVO domain : domains) {
|
||||
childDomains.add(domain.getId());
|
||||
}
|
||||
|
||||
|
||||
return childDomains;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isChildDomain(Long parentId, Long childId) {
|
||||
return _domainDao.isChildDomain(parentId, childId);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_CREATE, eventDescription = "creating Domain")
|
||||
public Domain createDomain(String name, Long parentId, String networkDomain) {
|
||||
@ -134,27 +134,26 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
|
||||
if (parentDomain == null) {
|
||||
throw new InvalidParameterValueException("Unable to create domain " + name + ", parent domain " + parentId + " not found.");
|
||||
}
|
||||
|
||||
|
||||
if (parentDomain.getState().equals(Domain.State.Inactive)) {
|
||||
throw new CloudRuntimeException("The domain cannot be created as the parent domain " + parentDomain.getName() + " is being deleted");
|
||||
}
|
||||
|
||||
|
||||
_accountMgr.checkAccess(caller, parentDomain);
|
||||
|
||||
|
||||
return createDomain(name, parentId, caller.getId(), networkDomain);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@DB
|
||||
public Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain) {
|
||||
//Verify network domain
|
||||
// Verify network domain
|
||||
if (networkDomain != null) {
|
||||
if (!NetUtils.verifyDomainName(networkDomain)) {
|
||||
throw new InvalidParameterValueException(
|
||||
"Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
|
||||
+ "and the hyphen ('-'); can't start or end with \"-\"");
|
||||
+ "and the hyphen ('-'); can't start or end with \"-\"");
|
||||
}
|
||||
}
|
||||
|
||||
@ -162,64 +161,63 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
|
||||
sc.addAnd("name", SearchCriteria.Op.EQ, name);
|
||||
sc.addAnd("parent", SearchCriteria.Op.EQ, parentId);
|
||||
List<DomainVO> domains = _domainDao.search(sc, null);
|
||||
|
||||
|
||||
if (!domains.isEmpty()) {
|
||||
throw new InvalidParameterValueException("Domain with name " + name + " already exists for the parent id=" + parentId);
|
||||
}
|
||||
|
||||
Transaction txn = Transaction.currentTxn();
|
||||
txn.start();
|
||||
|
||||
|
||||
DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain));
|
||||
_resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain);
|
||||
|
||||
|
||||
txn.commit();
|
||||
|
||||
|
||||
return domain;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public DomainVO findDomainByPath(String domainPath) {
|
||||
return _domainDao.findDomainByPath(domainPath);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Set<Long> getDomainParentIds(long domainId) {
|
||||
return _domainDao.getDomainParentIds(domainId);
|
||||
return _domainDao.getDomainParentIds(domainId);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean removeDomain(long domainId) {
|
||||
return _domainDao.remove(domainId);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<? extends Domain> findInactiveDomains() {
|
||||
return _domainDao.findInactiveDomains();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_DELETE, eventDescription = "deleting Domain", async = true)
|
||||
public boolean deleteDomain(long domainId, Boolean cleanup) {
|
||||
Account caller = UserContext.current().getCaller();
|
||||
|
||||
|
||||
DomainVO domain = _domainDao.findById(domainId);
|
||||
|
||||
|
||||
if (domain == null) {
|
||||
throw new InvalidParameterValueException("Failed to delete domain " + domainId + ", domain not found");
|
||||
} else if (domainId == DomainVO.ROOT_DOMAIN) {
|
||||
throw new PermissionDeniedException("Can't delete ROOT domain");
|
||||
}
|
||||
|
||||
|
||||
_accountMgr.checkAccess(caller, domain);
|
||||
|
||||
return deleteDomain(domain, cleanup);
|
||||
|
||||
return deleteDomain(domain, cleanup);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
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");
|
||||
domain.setState(Domain.State.Inactive);
|
||||
_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() + ").");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
} else {
|
||||
List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domain.getId());
|
||||
if (accountsForCleanup.isEmpty()) {
|
||||
if (!_domainDao.remove(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");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
s_logger.warn("Can't delete the domain yet because it has " + accountsForCleanup.size() + "accounts that need a cleanup");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
cleanupDomainOfferings(domain.getId());
|
||||
return true;
|
||||
} catch (Exception ex) {
|
||||
@ -252,7 +250,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void cleanupDomainOfferings(Long domainId) {
|
||||
// delete the service and disk offerings associated with this domain
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
//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;
|
||||
List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domainId);
|
||||
if (accountsForCleanup.isEmpty()) {
|
||||
@ -318,14 +316,14 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
|
||||
|
||||
return success && deleteDomainSuccess;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<DomainVO> searchForDomains(ListDomainsCmd cmd){
|
||||
public List<DomainVO> searchForDomains(ListDomainsCmd cmd) {
|
||||
Account caller = UserContext.current().getCaller();
|
||||
Long domainId = cmd.getId();
|
||||
boolean listAll = cmd.listAll();
|
||||
boolean isRecursive = false;
|
||||
|
||||
|
||||
if (domainId != null) {
|
||||
Domain domain = getDomain(domainId);
|
||||
if (domain == null) {
|
||||
@ -333,10 +331,10 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
|
||||
}
|
||||
_accountMgr.checkAccess(caller, domain);
|
||||
} else {
|
||||
domainId = caller.getDomainId();
|
||||
if (listAll) {
|
||||
isRecursive = true;
|
||||
}
|
||||
domainId = caller.getDomainId();
|
||||
if (listAll) {
|
||||
isRecursive = true;
|
||||
}
|
||||
}
|
||||
|
||||
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 (isRecursive) {
|
||||
sc.setParameters("path", getDomain(domainId).getPath() + "%");
|
||||
} else {
|
||||
sc.setParameters("id", domainId);
|
||||
}
|
||||
if (isRecursive) {
|
||||
sc.setParameters("path", getDomain(domainId).getPath() + "%");
|
||||
} else {
|
||||
sc.setParameters("id", domainId);
|
||||
}
|
||||
}
|
||||
|
||||
//return only Active domains to the API
|
||||
|
||||
// return only Active domains to the API
|
||||
sc.setParameters("state", Domain.State.Active);
|
||||
|
||||
return _domainDao.search(sc, searchFilter);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<DomainVO> searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException {
|
||||
public List<DomainVO> searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException {
|
||||
Long domainId = cmd.getId();
|
||||
String domainName = cmd.getDomainName();
|
||||
Boolean isRecursive = cmd.isRecursive();
|
||||
Object keyword = cmd.getKeyword();
|
||||
boolean listAll = cmd.listAll();
|
||||
String path = null;
|
||||
|
||||
|
||||
Account caller = UserContext.current().getCaller();
|
||||
if (domainId != null) {
|
||||
_accountMgr.checkAccess(caller, getDomain(domainId));
|
||||
_accountMgr.checkAccess(caller, getDomain(domainId));
|
||||
} else {
|
||||
domainId = caller.getDomainId();
|
||||
}
|
||||
@ -408,7 +406,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{
|
||||
|
||||
return domainList;
|
||||
}
|
||||
|
||||
|
||||
private List<DomainVO> searchForDomainChildren(Filter searchFilter, Long domainId, String domainName, Object keyword, String path, boolean listActiveOnly) {
|
||||
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.LIKE, path + "%");
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -17,7 +17,6 @@
|
||||
*/
|
||||
package com.cloud.upgrade;
|
||||
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
@ -37,32 +36,39 @@ import com.cloud.utils.db.Transaction;
|
||||
import com.cloud.utils.exception.CloudRuntimeException;
|
||||
|
||||
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
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
DbTestUtils.executeScript("PreviousDatabaseSchema/clean-db.sql", false, true);
|
||||
DbTestUtils.executeScript("PreviousDatabaseSchema/clean-db.sql", false,
|
||||
true);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@After
|
||||
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");
|
||||
DbTestUtils.executeScript("PreviousDatabaseSchema/2.2.14/cloud_usage_2214.sql", false, true);
|
||||
DbTestUtils.executeScript("PreviousDatabaseSchema/2.2.14/advance_zone_2.2.14.sql", false, true);
|
||||
|
||||
DatabaseUpgradeChecker checker = ComponentLocator.inject(DatabaseUpgradeChecker.class);
|
||||
|
||||
DbTestUtils.executeScript(
|
||||
"PreviousDatabaseSchema/2.2.14/cloud_usage_2214.sql", false,
|
||||
true);
|
||||
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");
|
||||
|
||||
|
||||
Connection conn = Transaction.getStandaloneConnection();
|
||||
|
||||
|
||||
try {
|
||||
checkPhysicalNetworks(conn);
|
||||
checkPhysicalNetworks(conn);
|
||||
checkNetworkOfferings(conn);
|
||||
checkNetworks(conn);
|
||||
} finally {
|
||||
@ -71,125 +77,128 @@ public class Test2214To30DBUpgrade extends TestCase {
|
||||
} catch (SQLException e) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
protected void checkPhysicalNetworks(Connection conn) throws SQLException {
|
||||
protected void checkPhysicalNetworks(Connection conn) throws SQLException {
|
||||
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();
|
||||
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();
|
||||
pstmt.close();
|
||||
|
||||
|
||||
pstmt = conn.prepareStatement("SELECT COUNT(*) FROM physical_network");
|
||||
rs = pstmt.executeQuery();
|
||||
assert rs.next() : "No physical networks setup.";
|
||||
rs.close();
|
||||
pstmt.close();
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
protected void checkNetworkOfferings(Connection conn) throws SQLException {
|
||||
//1) verify that all fields are present
|
||||
List<String> fields = new ArrayList<String>();
|
||||
fields.add("id");
|
||||
fields.add("name");
|
||||
fields.add("unique_name");
|
||||
fields.add("display_text");
|
||||
fields.add("nw_rate");
|
||||
fields.add("mc_rate");
|
||||
fields.add("traffic_type");
|
||||
fields.add("specify_vlan");
|
||||
fields.add("system_only");
|
||||
fields.add("service_offering_id");
|
||||
fields.add("tags");
|
||||
fields.add("default");
|
||||
fields.add("availability");
|
||||
fields.add("state");
|
||||
fields.add("removed");
|
||||
fields.add("created");
|
||||
fields.add("guest_type");
|
||||
fields.add("dedicated_lb_service");
|
||||
fields.add("shared_source_nat_service");
|
||||
fields.add("specify_ip_ranges");
|
||||
fields.add("sort_key");
|
||||
fields.add("uuid");
|
||||
fields.add("redundant_router_service");
|
||||
fields.add("conserve_mode");
|
||||
fields.add("elastic_ip_service");
|
||||
fields.add("elastic_lb_service");
|
||||
|
||||
PreparedStatement pstmt;
|
||||
// 1) verify that all fields are present
|
||||
List<String> fields = new ArrayList<String>();
|
||||
fields.add("id");
|
||||
fields.add("name");
|
||||
fields.add("unique_name");
|
||||
fields.add("display_text");
|
||||
fields.add("nw_rate");
|
||||
fields.add("mc_rate");
|
||||
fields.add("traffic_type");
|
||||
fields.add("specify_vlan");
|
||||
fields.add("system_only");
|
||||
fields.add("service_offering_id");
|
||||
fields.add("tags");
|
||||
fields.add("default");
|
||||
fields.add("availability");
|
||||
fields.add("state");
|
||||
fields.add("removed");
|
||||
fields.add("created");
|
||||
fields.add("guest_type");
|
||||
fields.add("dedicated_lb_service");
|
||||
fields.add("shared_source_nat_service");
|
||||
fields.add("specify_ip_ranges");
|
||||
fields.add("sort_key");
|
||||
fields.add("uuid");
|
||||
fields.add("redundant_router_service");
|
||||
fields.add("conserve_mode");
|
||||
fields.add("elastic_ip_service");
|
||||
fields.add("elastic_lb_service");
|
||||
|
||||
PreparedStatement pstmt;
|
||||
for (String field : fields) {
|
||||
pstmt = conn.prepareStatement("SHOW COLUMNS FROM network_offerings LIKE ?");
|
||||
pstmt.setString(1, field);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
if (!rs.next()) {
|
||||
throw new CloudRuntimeException("Field " + field + " is missing in upgraded network_offerings table");
|
||||
}
|
||||
rs.close();
|
||||
pstmt.close();
|
||||
|
||||
pstmt = conn
|
||||
.prepareStatement("SHOW COLUMNS FROM network_offerings LIKE ?");
|
||||
pstmt.setString(1, field);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
if (!rs.next()) {
|
||||
throw new CloudRuntimeException("Field " + field
|
||||
+ " is missing in upgraded network_offerings table");
|
||||
}
|
||||
rs.close();
|
||||
pstmt.close();
|
||||
|
||||
}
|
||||
|
||||
//2) compare default network offerings
|
||||
|
||||
// 2) compare default network offerings
|
||||
}
|
||||
|
||||
|
||||
protected void checkNetworks(Connection conn) throws SQLException {
|
||||
|
||||
//1) verify that all fields are present
|
||||
List<String> fields = new ArrayList<String>();
|
||||
fields.add("id");
|
||||
fields.add("name");
|
||||
fields.add("mode");
|
||||
fields.add("broadcast_domain_type");
|
||||
fields.add("traffic_type");
|
||||
fields.add("display_text");
|
||||
fields.add("broadcast_uri");
|
||||
fields.add("gateway");
|
||||
fields.add("cidr");
|
||||
fields.add("network_offering_id");
|
||||
fields.add("physical_network_id");
|
||||
fields.add("data_center_id");
|
||||
fields.add("related");
|
||||
fields.add("guru_name");
|
||||
fields.add("state");
|
||||
fields.add("dns1");
|
||||
fields.add("domain_id");
|
||||
fields.add("account_id");
|
||||
fields.add("set_fields");
|
||||
fields.add("guru_data");
|
||||
fields.add("dns2");
|
||||
fields.add("network_domain");
|
||||
fields.add("created");
|
||||
fields.add("removed");
|
||||
fields.add("reservation_id");
|
||||
fields.add("uuid");
|
||||
fields.add("guest_type");
|
||||
fields.add("restart_required");
|
||||
fields.add("specify_ip_ranges");
|
||||
fields.add("acl_type");
|
||||
fields.add("specified_cidr");
|
||||
|
||||
PreparedStatement pstmt;
|
||||
|
||||
// 1) verify that all fields are present
|
||||
List<String> fields = new ArrayList<String>();
|
||||
fields.add("id");
|
||||
fields.add("name");
|
||||
|
||||
fields.add("mode");
|
||||
fields.add("broadcast_domain_type");
|
||||
fields.add("traffic_type");
|
||||
fields.add("display_text");
|
||||
fields.add("broadcast_uri");
|
||||
fields.add("gateway");
|
||||
fields.add("cidr");
|
||||
fields.add("network_offering_id");
|
||||
fields.add("physical_network_id");
|
||||
fields.add("data_center_id");
|
||||
fields.add("related");
|
||||
fields.add("guru_name");
|
||||
fields.add("state");
|
||||
fields.add("dns1");
|
||||
fields.add("domain_id");
|
||||
fields.add("account_id");
|
||||
fields.add("set_fields");
|
||||
fields.add("guru_data");
|
||||
fields.add("dns2");
|
||||
fields.add("network_domain");
|
||||
fields.add("created");
|
||||
fields.add("removed");
|
||||
fields.add("reservation_id");
|
||||
fields.add("uuid");
|
||||
fields.add("guest_type");
|
||||
fields.add("restart_required");
|
||||
fields.add("specify_ip_ranges");
|
||||
fields.add("acl_type");
|
||||
fields.add("specified_cidr");
|
||||
|
||||
PreparedStatement pstmt;
|
||||
for (String field : fields) {
|
||||
pstmt = conn.prepareStatement("SHOW COLUMNS FROM networks LIKE ?");
|
||||
pstmt.setString(1, field);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
if (!rs.next()) {
|
||||
throw new CloudRuntimeException("Field " + field + " is missing in upgraded networks table");
|
||||
}
|
||||
rs.close();
|
||||
pstmt.close();
|
||||
|
||||
pstmt = conn.prepareStatement("SHOW COLUMNS FROM networks LIKE ?");
|
||||
pstmt.setString(1, field);
|
||||
ResultSet rs = pstmt.executeQuery();
|
||||
if (!rs.next()) {
|
||||
throw new CloudRuntimeException("Field " + field
|
||||
+ " is missing in upgraded networks table");
|
||||
}
|
||||
rs.close();
|
||||
pstmt.close();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user