diff --git a/api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java b/api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java index 063b3559434..a558b077690 100644 --- a/api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java +++ b/api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java @@ -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 . * - */ -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"); + } + } +} diff --git a/api/src/com/cloud/api/commands/CreateVMGroupCmd.java b/api/src/com/cloud/api/commands/CreateVMGroupCmd.java index a760612f7cc..6a07f73b88a 100644 --- a/api/src/com/cloud/api/commands/CreateVMGroupCmd.java +++ b/api/src/com/cloud/api/commands/CreateVMGroupCmd.java @@ -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); diff --git a/api/src/com/cloud/configuration/ConfigurationService.java b/api/src/com/cloud/configuration/ConfigurationService.java index f80e13e4e2c..452923f7f48 100644 --- a/api/src/com/cloud/configuration/ConfigurationService.java +++ b/api/src/com/cloud/configuration/ConfigurationService.java @@ -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 diff --git a/api/src/com/cloud/configuration/ResourceLimit.java b/api/src/com/cloud/configuration/ResourceLimit.java index 8c8b59d91cc..6b36eab4e1f 100644 --- a/api/src/com/cloud/configuration/ResourceLimit.java +++ b/api/src/com/cloud/configuration/ResourceLimit.java @@ -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); + } diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 89833212cb6..d66c4eae61d 100755 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -84,7 +84,7 @@ public interface NetworkService { Integer getNetworkRate(long networkId, Long vmId); Network getSystemNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); - + Map> getNetworkOfferingServiceProvidersMap(long networkOfferingId); PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRange, Long domainId, List 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 listTrafficTypes(Long physicalNetworkId); PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); - + Network getExclusiveGuestNetwork(long zoneId); - + List> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd); + } diff --git a/api/src/com/cloud/network/firewall/FirewallService.java b/api/src/com/cloud/network/firewall/FirewallService.java index 6ce885a1f04..86d1181de4e 100644 --- a/api/src/com/cloud/network/firewall/FirewallService.java +++ b/api/src/com/cloud/network/firewall/FirewallService.java @@ -10,18 +10,22 @@ import com.cloud.user.Account; public interface FirewallService { FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException; + List 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); + } diff --git a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java index 65c61f85ad8..c2906fd2089 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java @@ -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 vmIds); boolean removeFromLoadBalancer(long lbRuleId, List 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 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 searchForLBStickinessPolicies(ListLBStickinessPoliciesCmd cmd); - - + List listByNetworkId(long networkId); - + LoadBalancer findById(long LoadBalancer); } diff --git a/api/src/com/cloud/network/rules/RulesService.java b/api/src/com/cloud/network/rules/RulesService.java index 1588d7d633e..55439632be3 100644 --- a/api/src/com/cloud/network/rules/RulesService.java +++ b/api/src/com/cloud/network/rules/RulesService.java @@ -26,50 +26,61 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; public interface RulesService { - List searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll); + List 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 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 getSourceCidrs(long ruleId); - boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException; - + boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException; + } diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 7d6fed2e18e..2ee8cfa1c2d 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -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(); } diff --git a/api/src/com/cloud/user/DomainService.java b/api/src/com/cloud/user/DomainService.java index 6b4f83f832f..31decd5d6ab 100644 --- a/api/src/com/cloud/user/DomainService.java +++ b/api/src/com/cloud/user/DomainService.java @@ -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 searchForDomains(ListDomainsCmd cmd) - throws PermissionDeniedException; + List searchForDomains(ListDomainsCmd cmd) + throws PermissionDeniedException; + + List searchForDomainChildren(ListDomainChildrenCmd cmd) + throws PermissionDeniedException; - List searchForDomainChildren(ListDomainChildrenCmd cmd) - throws PermissionDeniedException; } diff --git a/api/src/com/cloud/user/ResourceLimitService.java b/api/src/com/cloud/user/ResourceLimitService.java index 542e3f0300b..2f9e5340361 100644 --- a/api/src/com/cloud/user/ResourceLimitService.java +++ b/api/src/com/cloud/user/ResourceLimitService.java @@ -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 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 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 diff --git a/core/src/com/cloud/configuration/ResourceLimitVO.java b/core/src/com/cloud/configuration/ResourceLimitVO.java index 0900aa4ef04..33aeb5d6994 100644 --- a/core/src/com/cloud/configuration/ResourceLimitVO.java +++ b/core/src/com/cloud/configuration/ResourceLimitVO.java @@ -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; + } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index d0079df516b..498668ef4a6 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -276,18 +276,19 @@ public class ApiResponseHelper implements ResponseGenerator { Long ipLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.public_ip, account.getId()); String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); Long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId()); - + Long ips = ipLimit - ipTotal; - //check how many free ips are left, and if it's less than max allowed number of ips from account - use this value + // check how many free ips are left, and if it's less than max allowed number of ips from account - use this +// value Long ipsLeft = ApiDBUtils.countFreePublicIps(); boolean unlimited = true; if (ips.longValue() > ipsLeft.longValue()) { - ips = ipsLeft; - unlimited = false; + ips = ipsLeft; + unlimited = false; } - + String ipAvail = ((accountIsAdmin || ipLimit == -1) && unlimited) ? "Unlimited" : String.valueOf(ips); - + accountResponse.setIpLimit(ipLimitDisplay); accountResponse.setIpTotal(ipTotal); accountResponse.setIpAvailable(ipAvail); @@ -319,7 +320,7 @@ public class ApiResponseHelper implements ResponseGenerator { // Get stopped and running VMs int vmStopped = 0; int vmRunning = 0; - + List permittedAccounts = new ArrayList(); permittedAccounts.add(account.getId()); @@ -353,8 +354,7 @@ public class ApiResponseHelper implements ResponseGenerator { accountResponse.setDetails(ApiDBUtils.getAccountDetails(account.getId())); return accountResponse; } - - + @Override public UserResponse createUserResponse(UserAccount user) { UserResponse userResponse = new UserResponse(); @@ -418,7 +418,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ResourceLimitResponse createResourceLimitResponse(ResourceLimit limit) { ResourceLimitResponse resourceLimitResponse = new ResourceLimitResponse(); - if (limit.getResourceOwnerType() == ResourceOwnerType.Domain) { + if (limit.getResourceOwnerType() == ResourceOwnerType.Domain) { populateDomain(resourceLimitResponse, limit.getOwnerId()); } else if (limit.getResourceOwnerType() == ResourceOwnerType.Account) { Account accountTemp = ApiDBUtils.findAccountById(limit.getOwnerId()); @@ -496,7 +496,7 @@ public class ApiResponseHelper implements ResponseGenerator { public SnapshotResponse createSnapshotResponse(Snapshot snapshot) { SnapshotResponse snapshotResponse = new SnapshotResponse(); snapshotResponse.setId(snapshot.getId()); - + populateOwner(snapshotResponse, snapshot); VolumeVO volume = findVolumeById(snapshot.getVolumeId()); @@ -528,7 +528,6 @@ public class ApiResponseHelper implements ResponseGenerator { return policyResponse; } - @Override public HostResponse createHostResponse(Host host) { @@ -556,17 +555,17 @@ public class ApiResponseHelper implements ResponseGenerator { hostResponse.setIpAddress(host.getPrivateIpAddress()); hostResponse.setVersion(host.getVersion()); hostResponse.setCreated(host.getCreated()); - - if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) - || details.contains(HostDetails.stats) || details.contains(HostDetails.events) ){ - + + if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) + || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) { + GuestOSCategoryVO guestOSCategory = ApiDBUtils.getHostGuestOSCategory(host.getId()); if (guestOSCategory != null) { hostResponse.setOsCategoryId(guestOSCategory.getId()); hostResponse.setOsCategoryName(guestOSCategory.getName()); } hostResponse.setZoneName(ApiDBUtils.findZoneById(host.getDataCenterId()).getName()); - + if (host.getPodId() != null) { HostPodVO pod = ApiDBUtils.findPodById(host.getPodId()); if (pod != null) { @@ -581,26 +580,26 @@ public class ApiResponseHelper implements ResponseGenerator { } } - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - if (host.getType() == Host.Type.Routing) { + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + if (host.getType() == Host.Type.Routing) { - if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)){ - //set allocated capacities - Long mem = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(),Capacity.CAPACITY_TYPE_MEMORY); - Long cpu = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(),Capacity.CAPACITY_TYPE_CPU); - - hostResponse.setMemoryAllocated(mem); + if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) { + // set allocated capacities + Long mem = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_MEMORY); + Long cpu = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_CPU); + + hostResponse.setMemoryAllocated(mem); hostResponse.setMemoryTotal(host.getTotalMemory()); hostResponse.setHostTags(ApiDBUtils.getHostTags(host.getId())); hostResponse.setHypervisorVersion(host.getHypervisorVersion()); - + String cpuAlloc = decimalFormat.format(((float) cpu / (float) (host.getCpus() * host.getSpeed())) * 100f) + "%"; hostResponse.setCpuAllocated(cpuAlloc); String cpuWithOverprovisioning = new Float(host.getCpus() * host.getSpeed() * ApiDBUtils.getCpuOverprovisioningFactor()).toString(); hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning); } - - if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)){ + + if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) { // set CPU/RAM/Network stats String cpuUsed = null; HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId()); @@ -608,24 +607,24 @@ public class ApiResponseHelper implements ResponseGenerator { float cpuUtil = (float) hostStats.getCpuUtilization(); cpuUsed = decimalFormat.format(cpuUtil) + "%"; hostResponse.setCpuUsed(cpuUsed); - hostResponse.setMemoryUsed( (new Double(hostStats.getUsedMemory())).longValue()); + hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue()); hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue()); hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue()); - + } } - - }else if (host.getType() == Host.Type.SecondaryStorage){ - StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); - if (secStorageStats != null){ - hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes()); - hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed()); - } + + } else if (host.getType() == Host.Type.SecondaryStorage) { + StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); + if (secStorageStats != null) { + hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes()); + hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed()); + } } hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host)); - - if (details.contains(HostDetails.all) || details.contains(HostDetails.events)){ + + if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) { Set possibleEvents = host.getStatus().getPossibleEvents(); if ((possibleEvents != null) && !possibleEvents.isEmpty()) { String events = ""; @@ -692,9 +691,9 @@ public class ApiResponseHelper implements ResponseGenerator { populateAccount(vlanResponse, owner.getId()); populateDomain(vlanResponse, owner.getDomainId()); } - + vlanResponse.setPhysicalNetworkId(vlan.getPhysicalNetworkId()); - + vlanResponse.setObjectName("vlan"); return vlanResponse; } @@ -809,34 +808,34 @@ public class ApiResponseHelper implements ResponseGenerator { podResponse.setEndIp(((ipRange.length > 1) && (ipRange[1] != null)) ? ipRange[1] : ""); podResponse.setGateway(pod.getGateway()); podResponse.setAllocationState(pod.getAllocationState().toString()); - if (showCapacities != null && showCapacities){ - List capacities = ApiDBUtils.getCapacityByClusterPodZone(null,pod.getId(),null); - Set capacityResponses = new HashSet(); - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - for (SummedCapacity capacity : capacities){ - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU){ - capacityResponse.setCapacityTotal(new Long((long)(capacity.getTotalCapacity()*cpuOverprovisioningFactor))); - }else if(capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED){ - List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, pod.getId() ,null); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); - }else{ - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - } - if (capacityResponse.getCapacityTotal() != 0) { - capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); - } else { - capacityResponse.setPercentUsed(s_percentFormat.format(0L)); - } - capacityResponses.add(capacityResponse); - } - // Do it for stats as well. - capacityResponses.addAll(getStatsCapacityresponse(null, null, pod.getId(), pod.getDataCenterId())); - podResponse.setCapacitites(new ArrayList(capacityResponses)); + if (showCapacities != null && showCapacities) { + List capacities = ApiDBUtils.getCapacityByClusterPodZone(null, pod.getId(), null); + Set capacityResponses = new HashSet(); + float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); + + for (SummedCapacity capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { + capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); + } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { + List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, pod.getId(), null); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); + } else { + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + } + if (capacityResponse.getCapacityTotal() != 0) { + capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); + } else { + capacityResponse.setPercentUsed(s_percentFormat.format(0L)); + } + capacityResponses.add(capacityResponse); + } + // Do it for stats as well. + capacityResponses.addAll(getStatsCapacityresponse(null, null, pod.getId(), pod.getDataCenterId())); + podResponse.setCapacitites(new ArrayList(capacityResponses)); } podResponse.setObjectName("pod"); return podResponse; @@ -862,48 +861,48 @@ public class ApiResponseHelper implements ResponseGenerator { // FIXME zoneResponse.setVlan(dataCenter.get.getVnet()); } - if (showCapacities != null && showCapacities){ - List capacities = ApiDBUtils.getCapacityByClusterPodZone(dataCenter.getId(),null,null); - Set capacityResponses = new HashSet(); - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - for (SummedCapacity capacity : capacities){ - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU){ - capacityResponse.setCapacityTotal(new Long((long)(capacity.getTotalCapacity()*cpuOverprovisioningFactor))); - }else if(capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED){ - List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(dataCenter.getId(), null ,null); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); - }else{ - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - } - if (capacityResponse.getCapacityTotal() != 0) { - capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); - } else { - capacityResponse.setPercentUsed(s_percentFormat.format(0L)); - } - capacityResponses.add(capacityResponse); - } - // Do it for stats as well. - capacityResponses.addAll(getStatsCapacityresponse(null, null, null, dataCenter.getId())); - - zoneResponse.setCapacitites(new ArrayList(capacityResponses)); + if (showCapacities != null && showCapacities) { + List capacities = ApiDBUtils.getCapacityByClusterPodZone(dataCenter.getId(), null, null); + Set capacityResponses = new HashSet(); + float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); + + for (SummedCapacity capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { + capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); + } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { + List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(dataCenter.getId(), null, null); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); + } else { + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + } + if (capacityResponse.getCapacityTotal() != 0) { + capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); + } else { + capacityResponse.setPercentUsed(s_percentFormat.format(0L)); + } + capacityResponses.add(capacityResponse); + } + // Do it for stats as well. + capacityResponses.addAll(getStatsCapacityresponse(null, null, null, dataCenter.getId())); + + zoneResponse.setCapacitites(new ArrayList(capacityResponses)); } - - //set network domain info + + // set network domain info zoneResponse.setDomain(dataCenter.getDomain()); - - //set domain info + + // set domain info Long domainId = dataCenter.getDomainId(); if (domainId != null) { - Domain domain = ApiDBUtils.findDomainById(domainId); - zoneResponse.setDomainId(domain.getId()); - zoneResponse.setDomainName(domain.getName()); + Domain domain = ApiDBUtils.findDomainById(domainId); + zoneResponse.setDomainId(domain.getId()); + zoneResponse.setDomainName(domain.getName()); } - + zoneResponse.setType(dataCenter.getNetworkType().toString()); zoneResponse.setAllocationState(dataCenter.getAllocationState().toString()); zoneResponse.setZoneToken(dataCenter.getZoneToken()); @@ -912,30 +911,30 @@ public class ApiResponseHelper implements ResponseGenerator { return zoneResponse; } - private List getStatsCapacityresponse(Long poolId, Long clusterId, Long podId, Long zoneId){ - List capacities = new ArrayList(); - capacities.add(ApiDBUtils.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId)); - if(clusterId == null && podId == null){ - capacities.add(ApiDBUtils.getSecondaryStorageUsedStats(poolId, zoneId)); - } - - List capacityResponses = new ArrayList(); - for (CapacityVO capacity : capacities){ - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - if (capacityResponse.getCapacityTotal() != 0) { + private List getStatsCapacityresponse(Long poolId, Long clusterId, Long podId, Long zoneId) { + List capacities = new ArrayList(); + capacities.add(ApiDBUtils.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId)); + if (clusterId == null && podId == null) { + capacities.add(ApiDBUtils.getSecondaryStorageUsedStats(poolId, zoneId)); + } + + List capacityResponses = new ArrayList(); + for (CapacityVO capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + if (capacityResponse.getCapacityTotal() != 0) { capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); } else { capacityResponse.setPercentUsed(s_percentFormat.format(0L)); } - capacityResponses.add(capacityResponse); - } - - return capacityResponses; + capacityResponses.add(capacityResponse); + } + + return capacityResponses; } - + @Override public VolumeResponse createVolumeResponse(Volume volume) { VolumeResponse volResponse = new VolumeResponse(); @@ -956,18 +955,18 @@ public class ApiResponseHelper implements ResponseGenerator { Long instanceId = volume.getInstanceId(); if (instanceId != null && volume.getState() != Volume.State.Destroy) { VMInstanceVO vm = ApiDBUtils.findVMInstanceById(instanceId); - if(vm != null){ - volResponse.setVirtualMachineId(vm.getId()); - volResponse.setVirtualMachineName(vm.getHostName()); - UserVm userVm = ApiDBUtils.findUserVmById(vm.getId()); - if (userVm != null) { - volResponse.setVirtualMachineDisplayName(userVm.getDisplayName()); - volResponse.setVirtualMachineState(vm.getState().toString()); - } else { - s_logger.error("User Vm with Id: "+instanceId+" does not exist for volume "+volume.getId()); - } + if (vm != null) { + volResponse.setVirtualMachineId(vm.getId()); + volResponse.setVirtualMachineName(vm.getHostName()); + UserVm userVm = ApiDBUtils.findUserVmById(vm.getId()); + if (userVm != null) { + volResponse.setVirtualMachineDisplayName(userVm.getDisplayName()); + volResponse.setVirtualMachineState(vm.getState().toString()); + } else { + s_logger.error("User Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); + } } else { - s_logger.error("Vm with Id: "+instanceId+" does not exist for volume "+volume.getId()); + s_logger.error("Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); } } @@ -1019,13 +1018,13 @@ public class ApiResponseHelper implements ResponseGenerator { // if (volume.getSourceType() != null) { // volResponse.setSourceType(volume.getSourceType().toString()); // } - - //return hypervisor for ROOT and Resource domain only + + // return hypervisor for ROOT and Resource domain only Account caller = UserContext.current().getCaller(); if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { volResponse.setHypervisor(ApiDBUtils.getVolumeHyperType(volume.getId()).toString()); } - + volResponse.setAttached(volume.getAttached()); volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); @@ -1041,7 +1040,7 @@ public class ApiResponseHelper implements ResponseGenerator { groupResponse.setId(group.getId()); groupResponse.setName(group.getName()); groupResponse.setCreated(group.getCreated()); - + populateOwner(groupResponse, group); groupResponse.setObjectName("instancegroup"); @@ -1073,14 +1072,14 @@ public class ApiResponseHelper implements ResponseGenerator { } StorageStats stats = ApiDBUtils.getStoragePoolStatistics(pool.getId()); - long allocatedSize = ApiDBUtils.getStorageCapacitybyPool(pool.getId(),Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED); + long allocatedSize = ApiDBUtils.getStorageCapacitybyPool(pool.getId(), Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED); poolResponse.setDiskSizeTotal(pool.getCapacityBytes()); poolResponse.setDiskSizeAllocated(allocatedSize); - + if (stats != null) { Long used = stats.getByteUsed(); - poolResponse.setDiskSizeUsed(used); - } + poolResponse.setDiskSizeUsed(used); + } if (pool.getClusterId() != null) { ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId()); @@ -1109,35 +1108,35 @@ public class ApiResponseHelper implements ResponseGenerator { } DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); clusterResponse.setZoneName(zone.getName()); - if (showCapacities != null && showCapacities){ - List capacities = ApiDBUtils.getCapacityByClusterPodZone(null,null,cluster.getId()); - Set capacityResponses = new HashSet(); - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - for (SummedCapacity capacity : capacities){ - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - - if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU){ - capacityResponse.setCapacityTotal(new Long((long)(capacity.getTotalCapacity()*cpuOverprovisioningFactor))); - }else if(capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED){ - List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, null, cluster.getId()); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); - }else{ - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - } - if (capacityResponse.getCapacityTotal() != 0) { - capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); - } else { - capacityResponse.setPercentUsed(s_percentFormat.format(0L)); - } - capacityResponses.add(capacityResponse); - } - // Do it for stats as well. - capacityResponses.addAll(getStatsCapacityresponse(null, cluster.getId(), pod.getId(), pod.getDataCenterId())); - clusterResponse.setCapacitites(new ArrayList(capacityResponses)); + if (showCapacities != null && showCapacities) { + List capacities = ApiDBUtils.getCapacityByClusterPodZone(null, null, cluster.getId()); + Set capacityResponses = new HashSet(); + float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); + + for (SummedCapacity capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + + if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { + capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); + } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { + List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, null, cluster.getId()); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); + } else { + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + } + if (capacityResponse.getCapacityTotal() != 0) { + capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); + } else { + capacityResponse.setPercentUsed(s_percentFormat.format(0L)); + } + capacityResponses.add(capacityResponse); + } + // Do it for stats as well. + capacityResponses.addAll(getStatsCapacityresponse(null, cluster.getId(), pod.getId(), pod.getDataCenterId())); + clusterResponse.setCapacitites(new ArrayList(capacityResponses)); } clusterResponse.setObjectName("cluster"); return clusterResponse; @@ -1208,19 +1207,18 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("ipforwardingrule"); return response; } - - + @Override - public List createUserVmResponse(String objectName, EnumSet details, UserVm...userVms) { + public List createUserVmResponse(String objectName, EnumSet details, UserVm... userVms) { Account caller = UserContext.current().getCaller(); Map dataCenters = new HashMap(); Map hosts = new HashMap(); Map templates = new HashMap(); Map serviceOfferings = new HashMap(); Map networks = new HashMap(); - + List vmResponses = new ArrayList(); - + for (UserVm userVm : userVms) { UserVmResponse userVmResponse = new UserVmResponse(); Account acct = ApiDBUtils.findAccountById(Long.valueOf(userVm.getAccountId())); @@ -1234,8 +1232,6 @@ public class ApiResponseHelper implements ResponseGenerator { userVmResponse.setName(userVm.getHostName()); userVmResponse.setCreated(userVm.getCreated()); - - userVmResponse.setHaEnable(userVm.isHaEnabled()); if (userVm.getDisplayName() != null) { @@ -1246,13 +1242,13 @@ public class ApiResponseHelper implements ResponseGenerator { userVmResponse.setPassword(userVm.getPassword()); } - if (details.contains(VMDetails.all) || details.contains(VMDetails.group)){ + if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) { InstanceGroupVO group = ApiDBUtils.findInstanceGroupForVM(userVm.getId()); if (group != null) { userVmResponse.setGroup(group.getName()); userVmResponse.setGroupId(group.getId()); } - + } // Data Center Info @@ -1261,193 +1257,191 @@ public class ApiResponseHelper implements ResponseGenerator { zone = ApiDBUtils.findZoneById(userVm.getDataCenterIdToDeployIn()); dataCenters.put(zone.getId(), zone); } - + userVmResponse.setZoneId(zone.getId()); userVmResponse.setZoneName(zone.getName()); - // if user is an admin, display host id if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) { Host host = hosts.get(userVm.getHostId()); - + if (host == null) { host = ApiDBUtils.findHostById(userVm.getHostId()); hosts.put(host.getId(), host); } - + userVmResponse.setHostId(host.getId()); userVmResponse.setHostName(host.getName()); } - + if (userVm.getState() != null) { - if (userVm.getHostId() != null) { - Host host = hosts.get(userVm.getHostId()); - + if (userVm.getHostId() != null) { + Host host = hosts.get(userVm.getHostId()); + if (host == null) { host = ApiDBUtils.findHostById(userVm.getHostId()); hosts.put(host.getId(), host); } if (host.getStatus() != com.cloud.host.Status.Up) { - userVmResponse.setState(VirtualMachine.State.Unknown.toString()); + userVmResponse.setState(VirtualMachine.State.Unknown.toString()); } else { - userVmResponse.setState(userVm.getState().toString()); + userVmResponse.setState(userVm.getState().toString()); } - } else { - userVmResponse.setState(userVm.getState().toString()); - } + } else { + userVmResponse.setState(userVm.getState().toString()); + } } if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - if (userVm.getHypervisorType() != null){ + if (userVm.getHypervisorType() != null) { userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)){ - // Template Info - VMTemplateVO template = templates.get(userVm.getTemplateId()); - if (template == null) { - template = ApiDBUtils.findTemplateById(userVm.getTemplateId()); - if (template != null) { - templates.put(template.getId(), template); - } - } - - if (template != null) { - userVmResponse.setTemplateId(userVm.getTemplateId()); - userVmResponse.setTemplateName(template.getName()); - userVmResponse.setTemplateDisplayText(template.getDisplayText()); - userVmResponse.setPasswordEnabled(template.getEnablePassword()); - } else { - userVmResponse.setTemplateId(-1L); - userVmResponse.setTemplateName("ISO Boot"); - userVmResponse.setTemplateDisplayText("ISO Boot"); - userVmResponse.setPasswordEnabled(false); - } } + if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) { + // Template Info + VMTemplateVO template = templates.get(userVm.getTemplateId()); + if (template == null) { + template = ApiDBUtils.findTemplateById(userVm.getTemplateId()); + if (template != null) { + templates.put(template.getId(), template); + } + } - if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)){ - // ISO Info - VMTemplateVO iso = templates.get(userVm.getIsoId()); - if (iso == null) { - iso = ApiDBUtils.findTemplateById(userVm.getIsoId()); - if (iso != null) { - templates.put(iso.getId(), iso); - } - } - - if (iso != null) { - userVmResponse.setIsoId(iso.getId()); - userVmResponse.setIsoName(iso.getName()); - } + if (template != null) { + userVmResponse.setTemplateId(userVm.getTemplateId()); + userVmResponse.setTemplateName(template.getName()); + userVmResponse.setTemplateDisplayText(template.getDisplayText()); + userVmResponse.setPasswordEnabled(template.getEnablePassword()); + } else { + userVmResponse.setTemplateId(-1L); + userVmResponse.setTemplateName("ISO Boot"); + userVmResponse.setTemplateDisplayText("ISO Boot"); + userVmResponse.setPasswordEnabled(false); + } } - if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)){ - // Service Offering Info - ServiceOffering offering = serviceOfferings.get(userVm.getServiceOfferingId()); - - if (offering == null) { - offering = ApiDBUtils.findServiceOfferingById(userVm.getServiceOfferingId()); - serviceOfferings.put(offering.getId(), offering); - } - - userVmResponse.setServiceOfferingId(offering.getId()); - userVmResponse.setServiceOfferingName(offering.getName()); - userVmResponse.setCpuNumber(offering.getCpu()); - userVmResponse.setCpuSpeed(offering.getSpeed()); - userVmResponse.setMemory(offering.getRamSize()); + if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) { + // ISO Info + VMTemplateVO iso = templates.get(userVm.getIsoId()); + if (iso == null) { + iso = ApiDBUtils.findTemplateById(userVm.getIsoId()); + if (iso != null) { + templates.put(iso.getId(), iso); + } + } + + if (iso != null) { + userVmResponse.setIsoId(iso.getId()); + userVmResponse.setIsoName(iso.getName()); + } } - if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)){ - VolumeVO rootVolume = ApiDBUtils.findRootVolume(userVm.getId()); - if (rootVolume != null) { - userVmResponse.setRootDeviceId(rootVolume.getDeviceId()); - String rootDeviceType = "Not created"; - if (rootVolume.getPoolId() != null) { - StoragePoolVO storagePool = ApiDBUtils.findStoragePoolById(rootVolume.getPoolId()); - rootDeviceType = storagePool.getPoolType().toString(); - } - userVmResponse.setRootDeviceType(rootDeviceType); - } + if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) { + // Service Offering Info + ServiceOffering offering = serviceOfferings.get(userVm.getServiceOfferingId()); + + if (offering == null) { + offering = ApiDBUtils.findServiceOfferingById(userVm.getServiceOfferingId()); + serviceOfferings.put(offering.getId(), offering); + } + + userVmResponse.setServiceOfferingId(offering.getId()); + userVmResponse.setServiceOfferingName(offering.getName()); + userVmResponse.setCpuNumber(offering.getCpu()); + userVmResponse.setCpuSpeed(offering.getSpeed()); + userVmResponse.setMemory(offering.getRamSize()); } - if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)){ - // stats calculation - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - String cpuUsed = null; - VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId()); - if (vmStats != null) { - float cpuUtil = (float) vmStats.getCPUUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - userVmResponse.setCpuUsed(cpuUsed); - - Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); - userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); - - Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); - userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); - } + if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) { + VolumeVO rootVolume = ApiDBUtils.findRootVolume(userVm.getId()); + if (rootVolume != null) { + userVmResponse.setRootDeviceId(rootVolume.getDeviceId()); + String rootDeviceType = "Not created"; + if (rootVolume.getPoolId() != null) { + StoragePoolVO storagePool = ApiDBUtils.findStoragePoolById(rootVolume.getPoolId()); + rootDeviceType = storagePool.getPoolType().toString(); + } + userVmResponse.setRootDeviceType(rootDeviceType); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) { + // stats calculation + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + String cpuUsed = null; + VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId()); + if (vmStats != null) { + float cpuUtil = (float) vmStats.getCPUUtilization(); + cpuUsed = decimalFormat.format(cpuUtil) + "%"; + userVmResponse.setCpuUsed(cpuUsed); + + Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); + userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); + + Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); + userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); + } } userVmResponse.setGuestOsId(userVm.getGuestOSId()); - - if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)){ - // security groups - list only when zone is security group enabled - if (zone.isSecurityGroupEnabled()) { - List securityGroups = ApiDBUtils.getSecurityGroupsForVm(userVm.getId()); - List securityGroupResponse = new ArrayList(); - for(SecurityGroupVO grp : securityGroups) { - SecurityGroupResponse resp = new SecurityGroupResponse(); - resp.setId(grp.getId()); - resp.setName(grp.getName()); - resp.setDescription(grp.getDescription()); - resp.setObjectName("securitygroup"); - securityGroupResponse.add(resp); - } - userVmResponse.setSecurityGroupList(securityGroupResponse); - } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) { + // security groups - list only when zone is security group enabled + if (zone.isSecurityGroupEnabled()) { + List securityGroups = ApiDBUtils.getSecurityGroupsForVm(userVm.getId()); + List securityGroupResponse = new ArrayList(); + for (SecurityGroupVO grp : securityGroups) { + SecurityGroupResponse resp = new SecurityGroupResponse(); + resp.setId(grp.getId()); + resp.setName(grp.getName()); + resp.setDescription(grp.getDescription()); + resp.setObjectName("securitygroup"); + securityGroupResponse.add(resp); + } + userVmResponse.setSecurityGroupList(securityGroupResponse); + } } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)){ - List nicProfiles = ApiDBUtils.getNics(userVm); - List nicResponses = new ArrayList(); - for (NicProfile singleNicProfile : nicProfiles) { - NicResponse nicResponse = new NicResponse(); - nicResponse.setId(singleNicProfile.getId()); - nicResponse.setIpaddress(singleNicProfile.getIp4Address()); - nicResponse.setGateway(singleNicProfile.getGateway()); - nicResponse.setNetmask(singleNicProfile.getNetmask()); - nicResponse.setNetworkid(singleNicProfile.getNetworkId()); - if (acct.getType() == Account.ACCOUNT_TYPE_ADMIN) { - if (singleNicProfile.getBroadCastUri() != null) { - nicResponse.setBroadcastUri(singleNicProfile.getBroadCastUri().toString()); - } - if (singleNicProfile.getIsolationUri() != null) { - nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); - } - } - - //Long networkId = singleNicProfile.getNetworkId(); - Network network = networks.get(singleNicProfile.getNetworkId()); - if (network == null) { - network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - networks.put(singleNicProfile.getNetworkId(), network); - } - - nicResponse.setTrafficType(network.getTrafficType().toString()); - nicResponse.setType(network.getGuestType().toString()); - nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); - nicResponse.setObjectName("nic"); - nicResponses.add(nicResponse); - } - userVmResponse.setNics(nicResponses); + + if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) { + List nicProfiles = ApiDBUtils.getNics(userVm); + List nicResponses = new ArrayList(); + for (NicProfile singleNicProfile : nicProfiles) { + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(singleNicProfile.getId()); + nicResponse.setIpaddress(singleNicProfile.getIp4Address()); + nicResponse.setGateway(singleNicProfile.getGateway()); + nicResponse.setNetmask(singleNicProfile.getNetmask()); + nicResponse.setNetworkid(singleNicProfile.getNetworkId()); + if (acct.getType() == Account.ACCOUNT_TYPE_ADMIN) { + if (singleNicProfile.getBroadCastUri() != null) { + nicResponse.setBroadcastUri(singleNicProfile.getBroadCastUri().toString()); + } + if (singleNicProfile.getIsolationUri() != null) { + nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); + } + } + + // Long networkId = singleNicProfile.getNetworkId(); + Network network = networks.get(singleNicProfile.getNetworkId()); + if (network == null) { + network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); + networks.put(singleNicProfile.getNetworkId(), network); + } + + nicResponse.setTrafficType(network.getTrafficType().toString()); + nicResponse.setType(network.getGuestType().toString()); + nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); + nicResponse.setObjectName("nic"); + nicResponses.add(nicResponse); + } + userVmResponse.setNics(nicResponses); } - + userVmResponse.setObjectName(objectName); vmResponses.add(userVmResponse); - } - + } + return vmResponses; } @@ -1455,22 +1449,22 @@ public class ApiResponseHelper implements ResponseGenerator { public List createUserVmResponse(String objectName, UserVm... userVms) { Account caller = UserContext.current().getCaller(); boolean caller_is_admin = ((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)); - + Hashtable vmDataList = new Hashtable(); // Initialise the vmdatalist with the input data for (UserVm userVm : userVms) { UserVmData userVmData = newUserVmData(userVm); vmDataList.put(userVm.getId(), userVmData); } - + vmDataList = ApiDBUtils.listVmDetails(vmDataList); - - //initialize vmresponse from vmdatalist + + // initialize vmresponse from vmdatalist List vmResponses = new ArrayList(); DecimalFormat decimalFormat = new DecimalFormat("#.##"); - for (UserVmData uvd: vmDataList.values()){ + for (UserVmData uvd : vmDataList.values()) { UserVmResponse userVmResponse = newUserVmResponse(uvd, caller_is_admin); - + // stats calculation String cpuUsed = null; // VmStats vmStats = ApiDBUtils.getVmStatistics(userVmResponse.getId()); @@ -1487,16 +1481,15 @@ public class ApiResponseHelper implements ResponseGenerator { userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); } userVmResponse.setObjectName(objectName); - + vmResponses.add(userVmResponse); } return vmResponses; } - @Override public DomainRouterResponse createDomainRouterResponse(VirtualRouter router) { - Account caller = UserContext.current().getCaller(); + Account caller = UserContext.current().getCaller(); Map serviceOfferings = new HashMap(); DomainRouterResponse routerResponse = new DomainRouterResponse(); @@ -1510,7 +1503,7 @@ public class ApiResponseHelper implements ResponseGenerator { routerResponse.setRedundantState(router.getRedundantState().toString()); if (caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - if (router.getHostId() != null) { + if (router.getHostId() != null) { routerResponse.setHostId(router.getHostId()); routerResponse.setHostName(ApiDBUtils.findHostById(router.getHostId()).getName()); } @@ -1553,7 +1546,6 @@ public class ApiResponseHelper implements ResponseGenerator { populateOwner(routerResponse, router); - DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterIdToDeployIn()); if (zone != null) { routerResponse.setZoneName(zone.getName()); @@ -1570,7 +1562,7 @@ public class ApiResponseHelper implements ResponseGenerator { SystemVmResponse vmResponse = new SystemVmResponse(); if (vm.getType() == Type.SecondaryStorageVm || vm.getType() == Type.ConsoleProxy) { // SystemVm vm = (SystemVm) systemVM; - vmResponse.setId(vm.getId()); + vmResponse.setId(vm.getId()); vmResponse.setObjectId(vm.getId()); vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); vmResponse.setZoneId(vm.getDataCenterIdToDeployIn()); @@ -1592,10 +1584,10 @@ public class ApiResponseHelper implements ResponseGenerator { // for console proxies, add the active sessions if (vm.getType() == Type.ConsoleProxy) { ConsoleProxyVO proxy = ApiDBUtils.findConsoleProxy(vm.getId()); - //proxy can be already destroyed + // proxy can be already destroyed if (proxy != null) { vmResponse.setActiveViewerSessions(proxy.getActiveSession()); - } + } } DataCenter zone = ApiDBUtils.findZoneById(vm.getDataCenterIdToDeployIn()); @@ -1608,7 +1600,7 @@ public class ApiResponseHelper implements ResponseGenerator { List nicProfiles = ApiDBUtils.getNics(vm); for (NicProfile singleNicProfile : nicProfiles) { Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - if (network != null) { + if (network != null) { if (network.getTrafficType() == TrafficType.Management) { vmResponse.setPrivateIp(singleNicProfile.getIp4Address()); vmResponse.setPrivateMacAddress(singleNicProfile.getMacAddress()); @@ -1617,7 +1609,7 @@ public class ApiResponseHelper implements ResponseGenerator { vmResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); vmResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); vmResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); - } else if (network.getTrafficType() == TrafficType.Public){ + } else if (network.getTrafficType() == TrafficType.Public) { vmResponse.setPublicIp(singleNicProfile.getIp4Address()); vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); vmResponse.setPublicNetmask(singleNicProfile.getNetmask()); @@ -1683,7 +1675,7 @@ public class ApiResponseHelper implements ResponseGenerator { vpnResponse.setDomainId(vpn.getDomainId()); populateOwner(vpnResponse, vpn); - + vpnResponse.setState(vpn.getState().toString()); vpnResponse.setObjectName("remoteaccessvpn"); @@ -1705,7 +1697,7 @@ public class ApiResponseHelper implements ResponseGenerator { Account caller = UserContext.current().getCaller(); if (result.getFormat() == ImageFormat.ISO) { // Templates are always bootable - response.setBootable(result.isBootable()); + response.setBootable(result.isBootable()); } else if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { response.setHypervisor(result.getHypervisorType().toString());// hypervisors are associated with templates } @@ -1714,7 +1706,7 @@ public class ApiResponseHelper implements ResponseGenerator { Account owner = ApiDBUtils.findAccountById(result.getAccountId()); populateAccount(response, owner.getId()); populateDomain(response, owner.getDomainId()); - + response.setObjectName("iso"); return response; } @@ -1729,7 +1721,7 @@ public class ApiResponseHelper implements ResponseGenerator { return responses; } dcs.addAll(ApiDBUtils.listZones()); - for (DataCenterVO dc : dcs ) { + for (DataCenterVO dc : dcs) { responses.addAll(createTemplateResponses(templateId, dc.getId(), readyOnly)); } return responses; @@ -1763,7 +1755,7 @@ public class ApiResponseHelper implements ResponseGenerator { if (template.getTemplateType() != null) { templateResponse.setTemplateType(template.getTemplateType().toString()); } - + Account caller = UserContext.current().getCaller(); if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { templateResponse.setHypervisor(template.getHypervisorType().toString()); @@ -1840,12 +1832,12 @@ public class ApiResponseHelper implements ResponseGenerator { if (template.getTemplateType() != null) { templateResponse.setTemplateType(template.getTemplateType().toString()); } - + Account caller = UserContext.current().getCaller(); if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { templateResponse.setHypervisor(template.getHypervisorType().toString()); } - + templateResponse.setDetails(template.getDetails()); GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); @@ -1910,12 +1902,13 @@ public class ApiResponseHelper implements ResponseGenerator { responses.add(templateResponse); return responses; } + @Override public List createIsoResponses(long isoId, Long zoneId, boolean readyOnly) { List isoResponses = new ArrayList(); VirtualMachineTemplate iso = findTemplateById(isoId); - if ( iso.getTemplateType() == TemplateType.PERHOST) { + if (iso.getTemplateType() == TemplateType.PERHOST) { TemplateResponse isoResponse = new TemplateResponse(); isoResponse.setId(iso.getId()); isoResponse.setName(iso.getName()); @@ -1931,24 +1924,24 @@ public class ApiResponseHelper implements ResponseGenerator { isoResponse.setChecksum(iso.getChecksum()); isoResponse.setPasswordEnabled(false); isoResponse.setDetails(iso.getDetails()); - + // add account ID and name Account owner = ApiDBUtils.findAccountById(iso.getAccountId()); populateAccount(isoResponse, owner.getId()); populateDomain(isoResponse, owner.getDomainId()); - + isoResponse.setObjectName("iso"); isoResponses.add(isoResponse); return isoResponses; } else { - if (zoneId == null || zoneId == -1 ) { + if (zoneId == null || zoneId == -1) { isoResponses = createSwiftIsoResponses(iso); if (!isoResponses.isEmpty()) { return isoResponses; } List dcs = new ArrayList(); dcs.addAll(ApiDBUtils.listZones()); - for (DataCenterVO dc : dcs ) { + for (DataCenterVO dc : dcs) { isoResponses.addAll(createIsoResponses(iso, dc.getId(), readyOnly)); } return isoResponses; @@ -2016,7 +2009,7 @@ public class ApiResponseHelper implements ResponseGenerator { long isoId = iso.getId(); List isoResponses = new ArrayList(); VMTemplateHostVO isoHost = ApiDBUtils.findTemplateHostRef(isoId, zoneId, readyOnly); - if( isoHost == null ) { + if (isoHost == null) { return isoResponses; } TemplateResponse isoResponse = new TemplateResponse(); @@ -2043,7 +2036,7 @@ public class ApiResponseHelper implements ResponseGenerator { isoResponse.setOsTypeId(-1L); isoResponse.setOsTypeName(""); } - + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId()); populateAccount(isoResponse, account.getId()); populateDomain(isoResponse, account.getDomainId()); @@ -2153,10 +2146,11 @@ public class ApiResponseHelper implements ResponseGenerator { response.setResponses(netGrpResponses); return response; } + @Override public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) { SecurityGroupResponse response = new SecurityGroupResponse(); - + populateOwner(response, group); response.setDescription(group.getDescription()); @@ -2200,32 +2194,31 @@ public class ApiResponseHelper implements ResponseGenerator { jobResponse.setUserId(job.getUserId()); jobResponse.setCmd(job.getCmd()); jobResponse.setCreated(job.getCreated()); - jobResponse.setJobId(job.getId()); - jobResponse.setJobStatus(job.getStatus()); - jobResponse.setJobProcStatus(job.getProcessStatus()); + jobResponse.setJobId(job.getId()); + jobResponse.setJobStatus(job.getStatus()); + jobResponse.setJobProcStatus(job.getProcessStatus()); if (job.getInstanceType() != null && job.getInstanceId() != null) { jobResponse.setJobInstanceType(job.getInstanceType().toString()); jobResponse.setJobInstanceId(job.getInstanceId()); } jobResponse.setJobResultCode(job.getResultCode()); - + boolean savedValue = SerializationContext.current().getUuidTranslation(); SerializationContext.current().setUuidTranslation(false); jobResponse.setJobResult((ResponseObject) ApiSerializerHelper.fromSerializedString(job.getResult())); SerializationContext.current().setUuidTranslation(savedValue); - + Object resultObject = ApiSerializerHelper.fromSerializedString(job.getResult()); if (resultObject != null) { Class clz = resultObject.getClass(); if (clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { jobResponse.setJobResultType("text"); } else { - jobResponse.setJobResultType("object"); + jobResponse.setJobResultType("object"); } } - - + jobResponse.setObjectName("asyncjobs"); return jobResponse; } @@ -2260,9 +2253,9 @@ public class ApiResponseHelper implements ResponseGenerator { responseEvent.setLevel(event.getLevel()); responseEvent.setParentId(event.getStartId()); responseEvent.setState(event.getState()); - + populateOwner(responseEvent, event); - + User user = ApiDBUtils.findUserById(event.getUserId()); if (user != null) { responseEvent.setUsername(user.getUsername()); @@ -2272,7 +2265,6 @@ public class ApiResponseHelper implements ResponseGenerator { return responseEvent; } - private List sumCapacities(List hostCapacities) { Map totalCapacityMap = new HashMap(); Map usedCapacityMap = new HashMap(); @@ -2292,17 +2284,17 @@ public class ApiResponseHelper implements ResponseGenerator { // collect all the capacity types, sum allocated/used and sum total...get one capacity number for each for (Capacity capacity : hostCapacities) { - - //check if zone exist + + // check if zone exist DataCenter zone = ApiDBUtils.findZoneById(capacity.getDataCenterId()); if (zone == null) { continue; } - + short capacityType = capacity.getCapacityType(); - //If local storage then ignore - if ( (capacityType == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED || capacityType == Capacity.CAPACITY_TYPE_STORAGE) + // If local storage then ignore + if ((capacityType == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED || capacityType == Capacity.CAPACITY_TYPE_STORAGE) && poolIdsToIgnore.contains(capacity.getHostOrPoolId())) { continue; } @@ -2339,11 +2331,16 @@ public class ApiResponseHelper implements ResponseGenerator { if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved // Capacity - // accounts for - // stopped vms - // that have been - // stopped within - // an interval + // accounts +// for + // stopped +// vms + // that +// have been + // stopped +// within + // an +// interval usedCapacity += capacity.getReservedCapacity(); } @@ -2376,11 +2373,14 @@ public class ApiResponseHelper implements ResponseGenerator { // accounts // for // stopped - // vms that - // have been - // stopped - // within an - // interval + // vms +// that + // have +// been + // stopped + // within +// an + // interval usedCapacity += capacity.getReservedCapacity(); } @@ -2411,8 +2411,8 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public List createCapacityResponse(List result, DecimalFormat format) { List capacityResponses = new ArrayList(); - //List summedCapacities = sumCapacities(result); - for (Capacity summedCapacity : result) { + // List summedCapacities = sumCapacities(result); + for (Capacity summedCapacity : result) { CapacityResponse capacityResponse = new CapacityResponse(); capacityResponse.setCapacityTotal(summedCapacity.getTotalCapacity()); capacityResponse.setCapacityType(summedCapacity.getCapacityType()); @@ -2421,20 +2421,20 @@ public class ApiResponseHelper implements ResponseGenerator { capacityResponse.setPodId(summedCapacity.getPodId()); HostPodVO pod = ApiDBUtils.findPodById(summedCapacity.getPodId()); if (pod != null) { - capacityResponse.setPodName(pod.getName()); + capacityResponse.setPodName(pod.getName()); } } if (summedCapacity.getClusterId() != null) { capacityResponse.setClusterId(summedCapacity.getClusterId()); ClusterVO cluster = ApiDBUtils.findClusterById(summedCapacity.getClusterId()); if (cluster != null) { - capacityResponse.setClusterName(cluster.getName()); - if (summedCapacity.getPodId() == null){ - long podId = cluster.getPodId(); - capacityResponse.setPodId(podId); - capacityResponse.setPodName(ApiDBUtils.findPodById(podId).getName()); - } - } + capacityResponse.setClusterName(cluster.getName()); + if (summedCapacity.getPodId() == null) { + long podId = cluster.getPodId(); + capacityResponse.setPodId(podId); + capacityResponse.setPodName(ApiDBUtils.findPodById(podId).getName()); + } + } } capacityResponse.setZoneId(summedCapacity.getDataCenterId()); capacityResponse.setZoneName(ApiDBUtils.findZoneById(summedCapacity.getDataCenterId()).getName()); @@ -2469,8 +2469,8 @@ public class ApiResponseHelper implements ResponseGenerator { if (isAdmin && (templateOwnerDomain != null)) { response.setDomainId(templateOwnerDomain); } - - //Set accounts + + // Set accounts List projectIds = new ArrayList(); List regularAccounts = new ArrayList(); for (String accountName : accountNames) { @@ -2478,24 +2478,24 @@ public class ApiResponseHelper implements ResponseGenerator { if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) { regularAccounts.add(accountName); } else { - //convert account to projectIds + // convert account to projectIds Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); - if(project.getUuid() != null && !project.getUuid().isEmpty()) + if (project.getUuid() != null && !project.getUuid().isEmpty()) projectIds.add(project.getUuid()); else - projectIds.add(String.valueOf(project.getId())); + projectIds.add(String.valueOf(project.getId())); } } - + if (!projectIds.isEmpty()) { response.setProjectIds(projectIds); } - + if (!regularAccounts.isEmpty()) { response.setAccountNames(regularAccounts); } - + response.setObjectName("templatepermission"); return response; } @@ -2525,7 +2525,7 @@ public class ApiResponseHelper implements ResponseGenerator { account = ApiDBUtils.findAccountById(securityGroup.getAccountId()); securiytGroupAccounts.put(securityGroup.getAccountId(), account); } - + populateAccount(response, account.getId()); populateDomain(response, account.getDomainId()); @@ -2594,32 +2594,32 @@ public class ApiResponseHelper implements ResponseGenerator { response.setConserveMode(offering.isConserveMode()); response.setSpecifyIpRanges(offering.getSpecifyIpRanges()); response.setAvailability(offering.getAvailability().toString()); - response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); + response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); if (offering.getServiceOfferingId() != null) { - response.setServiceOfferingId(offering.getServiceOfferingId()); + response.setServiceOfferingId(offering.getServiceOfferingId()); } else { response.setServiceOfferingId(ApiDBUtils.findDefaultRouterServiceOffering()); - } + } if (offering.getGuestType() != null) { response.setGuestIpType(offering.getGuestType().toString()); } - + response.setState(offering.getState().name()); - + Map> serviceProviderMap = ApiDBUtils.listNetworkOfferingServices(offering.getId()); List serviceResponses = new ArrayList(); for (Service service : serviceProviderMap.keySet()) { ServiceResponse svcRsp = new ServiceResponse(); - //skip gateway service + // skip gateway service if (service == Service.Gateway) { - continue; + continue; } svcRsp.setName(service.getName()); List providers = new ArrayList(); for (Provider provider : serviceProviderMap.get(service)) { if (provider != null) { - ProviderResponse providerRsp = new ProviderResponse(); - providerRsp.setName(provider.getName()); + ProviderResponse providerRsp = new ProviderResponse(); + providerRsp.setName(provider.getName()); providers.add(providerRsp); } } @@ -2627,37 +2627,37 @@ public class ApiResponseHelper implements ResponseGenerator { if (Service.Lb == service) { List lbCapResponse = new ArrayList(); - + CapabilityResponse lbIsoaltion = new CapabilityResponse(); lbIsoaltion.setName(Capability.SupportedLBIsolation.getName()); - lbIsoaltion.setValue(offering.getDedicatedLB()?"dedicated":"shared"); + lbIsoaltion.setValue(offering.getDedicatedLB() ? "dedicated" : "shared"); lbCapResponse.add(lbIsoaltion); - + CapabilityResponse eLb = new CapabilityResponse(); eLb.setName(Capability.ElasticLb.getName()); - eLb.setValue(offering.getElasticLb()?"true":"false"); + eLb.setValue(offering.getElasticLb() ? "true" : "false"); lbCapResponse.add(eLb); - + svcRsp.setCapabilities(lbCapResponse); } else if (Service.SourceNat == service) { List capabilities = new ArrayList(); CapabilityResponse sharedSourceNat = new CapabilityResponse(); - sharedSourceNat.setName(Capability.SupportedSourceNatTypes.getName()); - sharedSourceNat.setValue(offering.getSharedSourceNat()?"perzone":"peraccount"); + sharedSourceNat.setName(Capability.SupportedSourceNatTypes.getName()); + sharedSourceNat.setValue(offering.getSharedSourceNat() ? "perzone" : "peraccount"); capabilities.add(sharedSourceNat); - + CapabilityResponse redundantRouter = new CapabilityResponse(); redundantRouter.setName(Capability.RedundantRouter.getName()); - redundantRouter.setValue(offering.getRedundantRouter()?"true":"false"); + redundantRouter.setValue(offering.getRedundantRouter() ? "true" : "false"); capabilities.add(redundantRouter); - + svcRsp.setCapabilities(capabilities); } else if (service == Service.StaticNat) { List staticNatCapResponse = new ArrayList(); - + CapabilityResponse eIp = new CapabilityResponse(); eIp.setName(Capability.ElasticIp.getName()); - eIp.setValue(offering.getElasticLb()?"true":"false"); + eIp.setValue(offering.getElasticLb() ? "true" : "false"); staticNatCapResponse.add(eIp); svcRsp.setCapabilities(staticNatCapResponse); @@ -2685,30 +2685,30 @@ public class ApiResponseHelper implements ResponseGenerator { if (network.getTrafficType() != null) { response.setTrafficType(network.getTrafficType().name()); } - + if (network.getGuestType() != null) { response.setType(network.getGuestType().toString()); } - + response.setGateway(network.getGateway()); - - //FIXME - either set netmask or cidr + + // FIXME - either set netmask or cidr response.setCidr(network.getCidr()); - if(network.getCidr() != null){ - response.setNetmask(NetUtils.cidr2Netmask(network.getCidr())); + if (network.getCidr() != null) { + response.setNetmask(NetUtils.cidr2Netmask(network.getCidr())); } - - //FIXME - either set broadcast URI or vlan + + // FIXME - either set broadcast URI or vlan if (network.getBroadcastUri() != null) { - String broadcastUri = network.getBroadcastUri().toString(); + String broadcastUri = network.getBroadcastUri().toString(); response.setBroadcastUri(broadcastUri); String vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length()); response.setVlan(vlan); } - + DataCenter zone = ApiDBUtils.findZoneById(network.getDataCenterId()); response.setZoneId(network.getDataCenterId()); - response.setZoneName(zone.getName()); + response.setZoneName(zone.getName()); response.setPhysicalNetworkId(network.getPhysicalNetworkId()); // populate network offering information @@ -2737,9 +2737,9 @@ public class ApiResponseHelper implements ResponseGenerator { if (serviceCapabilitiesMap != null) { for (Service service : serviceCapabilitiesMap.keySet()) { ServiceResponse serviceResponse = new ServiceResponse(); - //skip gateway service + // skip gateway service if (service == Service.Gateway) { - continue; + continue; } serviceResponse.setName(service.getName()); @@ -2763,14 +2763,14 @@ public class ApiResponseHelper implements ResponseGenerator { } } response.setServices(serviceResponses); - + if (network.getAclType() == null || network.getAclType() == ACLType.Account) { - populateOwner(response, network); + populateOwner(response, network); } else { - //get domain from network_domain table - Pair domainNetworkDetails = ApiDBUtils.getDomainNetworkDetails(network.getId()); - response.setDomainId(domainNetworkDetails.first()); - response.setSubdomainAccess(domainNetworkDetails.second()); + // get domain from network_domain table + Pair domainNetworkDetails = ApiDBUtils.getDomainNetworkDetails(network.getId()); + response.setDomainId(domainNetworkDetails.first()); + response.setSubdomainAccess(domainNetworkDetails.second()); } Long dedicatedDomainId = ApiDBUtils.getDedicatedNetworkDomain(network.getId()); @@ -2779,7 +2779,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setDomainId(dedicatedDomainId); response.setDomainName(domain.getName()); } - + response.setSpecifyIpRanges(network.getSpecifyIpRanges()); response.setObjectName("network"); @@ -2787,7 +2787,7 @@ public class ApiResponseHelper implements ResponseGenerator { } @Override - public Long getSecurityGroupId (String groupName, long accountId) { + public Long getSecurityGroupId(String groupName, long accountId) { SecurityGroup sg = ApiDBUtils.getSecurityGroup(groupName, accountId); if (sg == null) { return null; @@ -2807,14 +2807,13 @@ public class ApiResponseHelper implements ResponseGenerator { Domain domain = ApiDBUtils.findDomainById(project.getDomainId()); response.setDomainId(domain.getId()); response.setDomain(domain.getName()); - + response.setOwner(ApiDBUtils.getProjectOwner(project.getId()).getAccountName()); response.setObjectName("project"); return response; } - - + @Override public FirewallResponse createFirewallResponse(FirewallRule fwRule) { FirewallResponse response = new FirewallResponse(); @@ -2849,10 +2848,8 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("firewallrule"); return response; } - - - public UserVmData newUserVmData(UserVm userVm){ + public UserVmData newUserVmData(UserVm userVm) { UserVmData userVmData = new UserVmData(); userVmData.setId(userVm.getId()); userVmData.setName(userVm.getHostName()); @@ -2864,12 +2861,12 @@ public class ApiResponseHelper implements ResponseGenerator { } if (userVm.getDisplayName() != null) { userVmData.setDisplayName(userVm.getDisplayName()); - } + } userVmData.setDomainId(userVm.getDomainId()); Account caller = UserContext.current().getCaller(); if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - if (userVm.getHypervisorType() != null) { + if (userVm.getHypervisorType() != null) { userVmData.setHypervisor(userVm.getHypervisorType().toString()); } } @@ -2879,10 +2876,10 @@ public class ApiResponseHelper implements ResponseGenerator { } return userVmData; } - - public UserVmResponse newUserVmResponse(UserVmData userVmData, boolean caller_is_admin){ + + public UserVmResponse newUserVmResponse(UserVmData userVmData, boolean caller_is_admin) { UserVmResponse userVmResponse = new UserVmResponse(); - + userVmResponse.setHypervisor(userVmData.getHypervisor()); userVmResponse.setId(userVmData.getId()); userVmResponse.setName(userVmData.getName()); @@ -2890,7 +2887,7 @@ public class ApiResponseHelper implements ResponseGenerator { populateAccount(userVmResponse, userVmData.getAccountId()); populateDomain(userVmResponse, userVmData.getDomainId()); - + userVmResponse.setCreated(userVmData.getCreated()); userVmResponse.setState(userVmData.getState()); userVmResponse.setHaEnable(userVmData.getHaEnable()); @@ -2898,7 +2895,7 @@ public class ApiResponseHelper implements ResponseGenerator { userVmResponse.setGroup(userVmData.getGroup()); userVmResponse.setZoneId(userVmData.getZoneId()); userVmResponse.setZoneName(userVmData.getZoneName()); - if (caller_is_admin){ + if (caller_is_admin) { userVmResponse.setHostId(userVmData.getHostId()); userVmResponse.setHostName(userVmData.getHostName()); } @@ -2926,19 +2923,19 @@ public class ApiResponseHelper implements ResponseGenerator { userVmResponse.setForVirtualNetwork(userVmData.getForVirtualNetwork()); Set securityGroupResponse = new HashSet(); - for (SecurityGroupData sgd: userVmData.getSecurityGroupList()){ + for (SecurityGroupData sgd : userVmData.getSecurityGroupList()) { if (sgd.getId() != null) { SecurityGroupResponse sgr = new SecurityGroupResponse(); sgr.setId(sgd.getId()); sgr.setName(sgd.getName()); sgr.setDescription(sgd.getDescription()); - + Account account = ApiDBUtils.findAccountByNameDomain(sgd.getAccountName(), sgd.getDomainId()); if (account != null) { populateAccount(sgr, account.getId()); populateDomain(sgr, account.getDomainId()); } - + sgr.setObjectName(sgd.getObjectName()); securityGroupResponse.add(sgr); } @@ -2946,7 +2943,7 @@ public class ApiResponseHelper implements ResponseGenerator { userVmResponse.setSecurityGroupList(new ArrayList(securityGroupResponse)); Set nicResponses = new HashSet(); - for (NicData nd: userVmData.getNics()){ + for (NicData nd : userVmData.getNics()) { NicResponse nr = new NicResponse(); nr.setId(nd.getId()); nr.setNetworkid(nd.getNetworkid()); @@ -2966,9 +2963,9 @@ public class ApiResponseHelper implements ResponseGenerator { return userVmResponse; } - + @Override - public HypervisorCapabilitiesResponse createHypervisorCapabilitiesResponse(HypervisorCapabilities hpvCapabilities){ + public HypervisorCapabilitiesResponse createHypervisorCapabilitiesResponse(HypervisorCapabilities hpvCapabilities) { HypervisorCapabilitiesResponse hpvCapabilitiesResponse = new HypervisorCapabilitiesResponse(); hpvCapabilitiesResponse.setId(hpvCapabilities.getId()); hpvCapabilitiesResponse.setHypervisor(hpvCapabilities.getHypervisorType()); @@ -2977,28 +2974,28 @@ public class ApiResponseHelper implements ResponseGenerator { hpvCapabilitiesResponse.setMaxGuestsLimit(hpvCapabilities.getMaxGuestsLimit()); return hpvCapabilitiesResponse; } - + private void populateOwner(ControlledEntityResponse response, ControlledEntity object) { Account account = ApiDBUtils.findAccountByIdIncludingRemoved(object.getAccountId()); - + if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - //find the project + // find the project Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); response.setProjectId(project.getId()); response.setProjectName(project.getName()); } else { response.setAccountName(account.getAccountName()); } - + Domain domain = ApiDBUtils.findDomainById(object.getDomainId()); response.setDomainId(domain.getId()); response.setDomainName(domain.getName()); } - + private void populateAccount(ControlledEntityResponse response, long accountId) { Account account = ApiDBUtils.findAccountByIdIncludingRemoved(accountId); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - //find the project + // find the project Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); response.setProjectId(project.getId()); response.setProjectName(project.getName()); @@ -3006,29 +3003,29 @@ public class ApiResponseHelper implements ResponseGenerator { response.setAccountName(account.getAccountName()); } } - + private void populateDomain(ControlledEntityResponse response, long domainId) { Domain domain = ApiDBUtils.findDomainById(domainId); - + response.setDomainId(domain.getId()); response.setDomainName(domain.getName()); } - - @Override + + @Override public ProjectAccountResponse createProjectAccountResponse(ProjectAccount projectAccount) { Account account = ApiDBUtils.findAccountById(projectAccount.getAccountId()); ProjectAccountResponse projectAccountResponse = new ProjectAccountResponse(); - + long projectId = projectAccount.getProjectId(); projectAccountResponse.setProjectId(projectId); projectAccountResponse.setProjectName(ApiDBUtils.findProjectById(projectId).getName()); - + projectAccountResponse.setId(account.getId()); projectAccountResponse.setAccountName(account.getAccountName()); projectAccountResponse.setAccountType(account.getType()); projectAccountResponse.setRole(projectAccount.getAccountRole().toString()); populateDomain(projectAccountResponse, account.getDomainId()); - + // add all the users for an account as part of the response obj List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); List userResponseList = new ArrayList(); @@ -3039,10 +3036,10 @@ public class ApiResponseHelper implements ResponseGenerator { projectAccountResponse.setUsers(userResponseList); projectAccountResponse.setObjectName("projectaccount"); - - return projectAccountResponse; + + return projectAccountResponse; } - + @Override public ProjectInvitationResponse createProjectInvitationResponse(ProjectInvitation invite) { ProjectInvitationResponse response = new ProjectInvitationResponse(); @@ -3050,23 +3047,23 @@ public class ApiResponseHelper implements ResponseGenerator { response.setProjectId(invite.getProjectId()); response.setProjectName(ApiDBUtils.findProjectById(invite.getProjectId()).getName()); response.setInvitationState(invite.getState().toString()); - + if (invite.getForAccountId() != null) { Account account = ApiDBUtils.findAccountById(invite.getForAccountId()); response.setAccountName(account.getAccountName()); - + } else { response.setEmail(invite.getEmail()); } - + populateDomain(response, invite.getInDomainId()); - + response.setObjectName("projectinvitation"); return response; } - + @Override - public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm){ + public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm) { SystemVmInstanceResponse vmResponse = new SystemVmInstanceResponse(); vmResponse.setId(vm.getId()); vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); @@ -3078,8 +3075,8 @@ public class ApiResponseHelper implements ResponseGenerator { vmResponse.setState(vm.getState().toString()); } if (vm.getType() == Type.DomainRouter) { - VirtualRouter router = (VirtualRouter)vm; - if(router.getRole() != null){ + VirtualRouter router = (VirtualRouter) vm; + if (router.getRole() != null) { vmResponse.setRole(router.getRole().toString()); } } @@ -3090,67 +3087,67 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result) { PhysicalNetworkResponse response = new PhysicalNetworkResponse(); - + response.setZoneId(result.getDataCenterId()); response.setNetworkSpeed(result.getSpeed()); response.setVlan(result.getVnet()); response.setDomainId(result.getDomainId()); response.setId(result.getUuid()); - if(result.getBroadcastDomainRange() != null){ + if (result.getBroadcastDomainRange() != null) { response.setBroadcastDomainRange(result.getBroadcastDomainRange().toString()); } response.setIsolationMethods(result.getIsolationMethods()); response.setTags(result.getTags()); - if(result.getState() != null){ + if (result.getState() != null) { response.setState(result.getState().toString()); } - + response.setName(result.getName()); - + response.setObjectName("physicalnetwork"); return response; } @Override - public ServiceResponse createNetworkServiceResponse(Service service){ + public ServiceResponse createNetworkServiceResponse(Service service) { ServiceResponse response = new ServiceResponse(); response.setName(service.getName()); - + // set list of capabilities required for the service List capabilityResponses = new ArrayList(); Capability[] capabilities = service.getCapabilities(); - for(Capability cap : capabilities){ + for (Capability cap : capabilities) { CapabilityResponse capabilityResponse = new CapabilityResponse(); capabilityResponse.setName(cap.getName()); capabilityResponse.setObjectName("capability"); - if (cap.getName().equals(Capability.SupportedLBIsolation.getName()) || - cap.getName().equals(Capability.SupportedSourceNatTypes.getName()) || - cap.getName().equals(Capability.RedundantRouter.getName()) ) { - capabilityResponse.setCanChoose(true); - } else { - capabilityResponse.setCanChoose(false); - } + if (cap.getName().equals(Capability.SupportedLBIsolation.getName()) || + cap.getName().equals(Capability.SupportedSourceNatTypes.getName()) || + cap.getName().equals(Capability.RedundantRouter.getName())) { + capabilityResponse.setCanChoose(true); + } else { + capabilityResponse.setCanChoose(false); + } capabilityResponses.add(capabilityResponse); } response.setCapabilities(capabilityResponses); - - //set list of providers providing this service + + // set list of providers providing this service List serviceProviders = ApiDBUtils.getProvidersForService(service); List serviceProvidersResponses = new ArrayList(); for (Network.Provider serviceProvider : serviceProviders) { - //return only Virtual Router as a provider for the firewall - if (service == Service.Firewall && !(serviceProvider == Provider.VirtualRouter)) { - continue; - } - + // return only Virtual Router as a provider for the firewall + if (service == Service.Firewall && !(serviceProvider == Provider.VirtualRouter)) { + continue; + } + ProviderResponse serviceProviderResponse = createServiceProviderResponse(serviceProvider); serviceProvidersResponses.add(serviceProviderResponse); } response.setProviders(serviceProvidersResponses); - + response.setObjectName("networkservice"); return response; - + } private ProviderResponse createServiceProviderResponse(Provider serviceProvider) { @@ -3160,23 +3157,23 @@ public class ApiResponseHelper implements ResponseGenerator { response.setCanEnableIndividualServices(canEnableIndividualServices); return response; } - + @Override - public ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result){ + public ProviderResponse createNetworkServiceProviderResponse(PhysicalNetworkServiceProvider result) { ProviderResponse response = new ProviderResponse(); response.setId(result.getUuid()); response.setName(result.getProviderName()); response.setPhysicalNetworkId(result.getPhysicalNetworkId()); response.setDestinationPhysicalNetworkId(result.getDestinationPhysicalNetworkId()); response.setState(result.getState().toString()); - - //set enabled services + + // set enabled services List services = new ArrayList(); - for (Service service: result.getEnabledServices()){ + for (Service service : result.getEnabledServices()) { services.add(service.getName()); } response.setServices(services); - + response.setObjectName("networkserviceprovider"); return response; } @@ -3190,22 +3187,22 @@ public class ApiResponseHelper implements ResponseGenerator { response.setXenLabel(result.getXenNetworkLabel()); response.setKvmLabel(result.getKvmNetworkLabel()); response.setVmwareLabel(result.getVmwareNetworkLabel()); - + response.setObjectName("traffictype"); return response; } - - - @Override - public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) { - VirtualRouterProviderResponse response = new VirtualRouterProviderResponse(); - response.setId(result.getId()); - response.setNspId(result.getNspId()); - response.setEnabled(result.isEnabled()); - - response.setObjectName("virtualrouterelement"); - return response; + + @Override + public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) { + VirtualRouterProviderResponse response = new VirtualRouterProviderResponse(); + response.setId(result.getId()); + response.setNspId(result.getNspId()); + response.setEnabled(result.isEnabled()); + + response.setObjectName("virtualrouterelement"); + return response; } + @Override public LBStickinessResponse createLBStickinessPolicyResponse( StickinessPolicy stickinessPolicy, LoadBalancer lb) { @@ -3230,13 +3227,14 @@ public class ApiResponseHelper implements ResponseGenerator { spResponse.setObjectName("stickinesspolicies"); return spResponse; } - + @Override public LBStickinessResponse createLBStickinessPolicyResponse( List stickinessPolicies, LoadBalancer lb) { LBStickinessResponse spResponse = new LBStickinessResponse(); - if (lb == null) return spResponse ; + if (lb == null) + return spResponse; spResponse.setlbRuleId(lb.getId()); Account account = ApiDBUtils.findAccountById(lb.getAccountId()); if (account != null) { @@ -3272,17 +3270,18 @@ public class ApiResponseHelper implements ResponseGenerator { return lr; } - @Override + @Override public StorageNetworkIpRangeResponse createStorageNetworkIpRangeResponse(StorageNetworkIpRange result) { - StorageNetworkIpRangeResponse response = new StorageNetworkIpRangeResponse(); - response.setUuid(result.getUuid()); - response.setVlan(result.getVlan()); - response.setEndIp(result.getEndIp()); - response.setStartIp(result.getStartIp()); - response.setPodUuid(result.getPodUuid()); - response.setZoneUuid(result.getZoneUuid()); - response.setNetworkUuid(result.getNetworkUuid()); - response.setObjectName("storagenetworkiprange"); - return response; - } -} + StorageNetworkIpRangeResponse response = new StorageNetworkIpRangeResponse(); + response.setUuid(result.getUuid()); + response.setVlan(result.getVlan()); + response.setEndIp(result.getEndIp()); + response.setStartIp(result.getStartIp()); + response.setPodUuid(result.getPodUuid()); + response.setZoneUuid(result.getZoneUuid()); + response.setNetworkUuid(result.getNetworkUuid()); + response.setObjectName("storagenetworkiprange"); + return response; + } + +} diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index aad5e4b379b..5676b3c3169 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -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 s_allCommands = null; private static List 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(), 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 pluggableServicesApiConfigs = new ArrayList(); - + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); List 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 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 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); diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java index bce11e1fd94..c043fbf0da9 100644 --- a/server/src/com/cloud/configuration/ConfigurationManager.java +++ b/server/src/com/cloud/configuration/ConfigurationManager.java @@ -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 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 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 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 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> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode, Map> serviceCapabilityMap, boolean specifyIpRanges); + NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, Integer networkRate, + Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode, + Map> 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); - + } diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 786f24bd01c..f626ff23b95 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -233,13 +233,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura SecondaryStorageVmManager _ssvmMgr; @Inject NetworkOfferingServiceMapDao _ntwkOffServiceMapDao; - @Inject + @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject SwiftManager _swiftMgr; @Inject PhysicalNetworkTrafficTypeDao _trafficTypeDao; - + // FIXME - why don't we have interface for DataCenterLinkLocalIpAddressDao? protected static final DataCenterLinkLocalIpAddressDaoImpl _LinkLocalIpAllocDao = ComponentLocator.inject(DataCenterLinkLocalIpAddressDaoImpl.class); @@ -272,7 +272,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura configValuesForValidation.add("investigate.retry.interval"); configValuesForValidation.add("migrate.retry.interval"); configValuesForValidation.add("network.gc.interval"); - configValuesForValidation.add("ping.interval"); + configValuesForValidation.add("ping.interval"); configValuesForValidation.add("snapshot.poll.interval"); configValuesForValidation.add("stop.retry.interval"); configValuesForValidation.add("storage.stats.interval"); @@ -332,16 +332,15 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException(validationMsg); } - //Execute all updates in a single transaction + // Execute all updates in a single transaction Transaction txn = Transaction.currentTxn(); txn.start(); - + if (!_configDao.update(name, category, value)) { s_logger.error("Failed to update configuration option, name: " + name + ", value:" + value); throw new CloudRuntimeException("Failed to update configuration value. Please contact Cloud Support."); } - - + PreparedStatement pstmt = null; if (Config.XenGuestNetwork.key().equalsIgnoreCase(name)) { String sql = "update host_details set value=? where name=?"; @@ -423,11 +422,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (serviceOffering != null) { serviceOffering.setUseLocalStorage(useLocalStorage); if (!_serviceOfferingDao.update(serviceOffering.getId(), serviceOffering)) { - throw new CloudRuntimeException("Failed to update SecondaryStorage offering's use_local_storage option to value:" + useLocalStorage); + throw new CloudRuntimeException("Failed to update SecondaryStorage offering's use_local_storage option to value:" + useLocalStorage); } } } - + txn.commit(); } @@ -437,8 +436,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Long userId = UserContext.current().getCallerUserId(); String name = cmd.getCfgName(); String value = cmd.getValue(); - UserContext.current().setEventDetails(" Name: "+name +" New Value: "+ (((name.toLowerCase()).contains("password")) ? "*****" : - (((value == null) ? "" : value)))); + UserContext.current().setEventDetails(" Name: " + name + " New Value: " + (((name.toLowerCase()).contains("password")) ? "*****" : + (((value == null) ? "" : value)))); // check if config value exists ConfigurationVO config = _configDao.findByName(name); if (config == null) { @@ -536,7 +535,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!NetUtils.verifyInstanceName(value)) { return "Instance name can not contain hyphen, spaces and plus sign"; } - }else { + } else { String[] options = range.split(","); for (String option : options) { if (option.trim().equalsIgnoreCase(value)) { @@ -638,25 +637,25 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } } - + @Override public void checkCidrVlanOverlap(long zoneId, String cidr) { - // Prevent using the same CIDR for POD and virtual networking - List vlans = _vlanDao.listByZoneAndType(zoneId, VlanType.VirtualNetwork); - for (VlanVO vlan : vlans) { - String vlanCidr = NetUtils.ipAndNetMaskToCidr(vlan.getVlanGateway(), vlan.getVlanNetmask()); - String[] cidrPairVlan = vlanCidr.split("\\/"); - String[] vlanIpRange = NetUtils.getIpRangeFromCidr(cidrPairVlan[0], Long.valueOf(cidrPairVlan[1])); + // Prevent using the same CIDR for POD and virtual networking + List vlans = _vlanDao.listByZoneAndType(zoneId, VlanType.VirtualNetwork); + for (VlanVO vlan : vlans) { + String vlanCidr = NetUtils.ipAndNetMaskToCidr(vlan.getVlanGateway(), vlan.getVlanNetmask()); + String[] cidrPairVlan = vlanCidr.split("\\/"); + String[] vlanIpRange = NetUtils.getIpRangeFromCidr(cidrPairVlan[0], Long.valueOf(cidrPairVlan[1])); - String[] cidrPairPod = cidr.split("\\/"); - String[] podIpRange = NetUtils.getIpRangeFromCidr(cidrPairPod[0], Long.valueOf(cidrPairPod[1])); + String[] cidrPairPod = cidr.split("\\/"); + String[] podIpRange = NetUtils.getIpRangeFromCidr(cidrPairPod[0], Long.valueOf(cidrPairPod[1])); - if (NetUtils.ipRangesOverlap(vlanIpRange[0], vlanIpRange[1], podIpRange[0], podIpRange[1])) { - throw new InvalidParameterValueException("Pod's cidr conflicts with cidr of virtual network in zone id=" + zoneId); - } + if (NetUtils.ipRangesOverlap(vlanIpRange[0], vlanIpRange[1], podIpRange[0], podIpRange[1])) { + throw new InvalidParameterValueException("Pod's cidr conflicts with cidr of virtual network in zone id=" + zoneId); } + } } - + private void checkPodAttributes(long podId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationStateStr, boolean checkForDuplicates, boolean skipGatewayOverlapCheck) { if (checkForDuplicates) { @@ -681,8 +680,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (startIp != null || endIp != null) { checkIpRange(startIp, endIp, cidrAddress, cidrSize); } - - // Check if the IP range overlaps with the public ip + + // Check if the IP range overlaps with the public ip checkOverlapPublicIpRange(zoneId, startIp, endIp); // Check if the gateway is a valid IP address @@ -705,7 +704,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String checkPodCIDRs = _configDao.getValue("check.pod.cidrs"); if (checkPodCIDRs == null || checkPodCIDRs.trim().isEmpty() || Boolean.parseBoolean(checkPodCIDRs)) { checkPodCidrSubnets(zoneId, podId, cidr); - /* Commenting out due to Bug 11593 - CIDR conflicts with zone when extending pod but not when creating it + /* + * Commenting out due to Bug 11593 - CIDR conflicts with zone when extending pod but not when creating it * * checkCidrVlanOverlap(zoneId, cidr); */ @@ -744,7 +744,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!privateIps.isEmpty()) { if (!(_privateIpAddressDao.deleteIpAddressByPod(podId))) { throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId); - } + } } // Delete link local ip addresses for the pod @@ -762,10 +762,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura _vlanDao.remove(vlan.getId()); } } - + // Delete corresponding capacity records _capacityDao.removeBy(null, null, podId, null, null); - + // Delete the pod if (!(_podDao.remove(podId))) { throw new CloudRuntimeException("Failed to delete pod " + podId); @@ -1165,26 +1165,28 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura List existingPublicIPs = _publicIpAddressDao.listByDcId(zoneId); for (IPAddressVO publicIPVO : existingPublicIPs) { - long publicIP = NetUtils.ip2Long(publicIPVO.getAddress().addr()); - if ((publicIP >= privateStartIp) && (publicIP <= privateEndIp)) { - throw new InvalidParameterValueException("The Start IP and endIP address range overlap with Public IP :" + publicIPVO.getAddress().addr()); - } + long publicIP = NetUtils.ip2Long(publicIPVO.getAddress().addr()); + if ((publicIP >= privateStartIp) && (publicIP <= privateEndIp)) { + throw new InvalidParameterValueException("The Start IP and endIP address range overlap with Public IP :" + publicIPVO.getAddress().addr()); + } } } - + private void checkOverlapPrivateIpRange(Long zoneId, String startIp, String endIp) { List podsInZone = _podDao.listByDataCenterId(zoneId); for (HostPodVO hostPod : podsInZone) { String[] IpRange = hostPod.getDescription().split("-"); - if (IpRange[0]==null || IpRange[1]==null) continue; - if (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1])) continue; + if (IpRange[0] == null || IpRange[1] == null) + continue; + if (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1])) + continue; if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { throw new InvalidParameterValueException("The Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]); } } } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_ZONE_DELETE, eventDescription = "deleting zone", async = false) @@ -1218,7 +1220,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura success = _zoneDao.remove(zoneId); if (success) { - //delete all capacity records for the zone + // delete all capacity records for the zone _capacityDao.removeBy(null, zoneId, null, null, null); } @@ -1227,7 +1229,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return success; } - @Override @DB @@ -1241,78 +1242,85 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Boolean useSSL = cmd.getUseSSL(); String bindDN = cmd.getBindDN(); String bindPasswd = cmd.getBindPassword(); - - if (bindDN != null && bindPasswd == null ){ - throw new InvalidParameterValueException("If you specify a bind name then you need to provide bind password too."); + + if (bindDN != null && bindPasswd == null) { + throw new InvalidParameterValueException("If you specify a bind name then you need to provide bind password too."); } - - //System.setProperty("javax.net.ssl.keyStore", "/cygdrive/c/citrix/info/cacerts.jks"); - //System.setProperty("javax.net.ssl.keyStorePassword", "1111_aaaa"); - + + // System.setProperty("javax.net.ssl.keyStore", "/cygdrive/c/citrix/info/cacerts.jks"); + // System.setProperty("javax.net.ssl.keyStorePassword", "1111_aaaa"); + // check if the info is correct Hashtable env = new Hashtable(11); - env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); - String protocol = "ldap://" ; - if (new Boolean(useSSL)){ - env.put(Context.SECURITY_PROTOCOL, "ssl"); - protocol="ldaps://" ; + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + String protocol = "ldap://"; + if (new Boolean(useSSL)) { + env.put(Context.SECURITY_PROTOCOL, "ssl"); + protocol = "ldaps://"; } - env.put(Context.PROVIDER_URL, protocol + hostname + ":" + port); - if (bindDN != null && bindPasswd != null){ - env.put(Context.SECURITY_PRINCIPAL, bindDN); - env.put(Context.SECURITY_CREDENTIALS, bindPasswd); + env.put(Context.PROVIDER_URL, protocol + hostname + ":" + port); + if (bindDN != null && bindPasswd != null) { + env.put(Context.SECURITY_PRINCIPAL, bindDN); + env.put(Context.SECURITY_CREDENTIALS, bindPasswd); } // Create the initial context DirContext ctx = new InitialDirContext(env); ctx.close(); - // store the result in DB COnfiguration - ConfigurationVO cvo = _configDao.findByName(LDAPParams.hostname.toString()); - if (cvo==null){ + ConfigurationVO cvo = _configDao.findByName(LDAPParams.hostname.toString()); + if (cvo == null) { cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.hostname.toString(), null, "Hostname or ip address of the ldap server eg: my.ldap.com"); } - cvo.setValue(hostname); _configDao.persist(cvo); - - cvo = _configDao.findByName(LDAPParams.port.toString()); - if (cvo==null){ + cvo.setValue(hostname); + _configDao.persist(cvo); + + cvo = _configDao.findByName(LDAPParams.port.toString()); + if (cvo == null) { cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.port.toString(), null, "Specify the LDAP port if required, default is 389"); - } - cvo.setValue(port.toString()); _configDao.persist(cvo); - - cvo = _configDao.findByName(LDAPParams.queryfilter.toString()); - if (cvo==null){ - cvo = new ConfigurationVO("Advanced","DEFAULT", "management-server", LDAPParams.queryfilter.toString(), null, "You specify a query filter here, which narrows down the users, who can be part of this domain"); - } - cvo.setValue(queryFilter); _configDao.persist(cvo); - - cvo = _configDao.findByName(LDAPParams.searchbase.toString()); - if (cvo==null){ - cvo = new ConfigurationVO("Advanced","DEFAULT", "management-server", LDAPParams.searchbase.toString(), null, "The search base defines the starting point for the search in the directory tree Example: dc=cloud,dc=com."); - } - cvo.setValue(searchBase); _configDao.persist(cvo); - + } + cvo.setValue(port.toString()); + _configDao.persist(cvo); + + cvo = _configDao.findByName(LDAPParams.queryfilter.toString()); + if (cvo == null) { + cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.queryfilter.toString(), null, + "You specify a query filter here, which narrows down the users, who can be part of this domain"); + } + cvo.setValue(queryFilter); + _configDao.persist(cvo); + + cvo = _configDao.findByName(LDAPParams.searchbase.toString()); + if (cvo == null) { + cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.searchbase.toString(), null, + "The search base defines the starting point for the search in the directory tree Example: dc=cloud,dc=com."); + } + cvo.setValue(searchBase); + _configDao.persist(cvo); + cvo = _configDao.findByName(LDAPParams.usessl.toString()); - if (cvo==null){ - cvo = new ConfigurationVO("Advanced","DEFAULT", "management-server", LDAPParams.usessl.toString(), null, "Check Use SSL if the external LDAP server is configured for LDAP over SSL."); - } - cvo.setValue(useSSL.toString()); _configDao.persist(cvo); - + if (cvo == null) { + cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.usessl.toString(), null, "Check Use SSL if the external LDAP server is configured for LDAP over SSL."); + } + cvo.setValue(useSSL.toString()); + _configDao.persist(cvo); + cvo = _configDao.findByName(LDAPParams.dn.toString()); - if (cvo==null){ - cvo = new ConfigurationVO("Advanced","DEFAULT", "management-server", LDAPParams.dn.toString(), null, "Specify the distinguished name of a user with the search permission on the directory"); - } - cvo.setValue(bindDN); _configDao.persist(cvo); - + if (cvo == null) { + cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.dn.toString(), null, "Specify the distinguished name of a user with the search permission on the directory"); + } + cvo.setValue(bindDN); + _configDao.persist(cvo); + cvo = _configDao.findByName(LDAPParams.passwd.toString()); - if (cvo==null){ - cvo = new ConfigurationVO("Advanced","DEFAULT", "management-server", LDAPParams.passwd.toString(), null, "Enter the password"); - } - cvo.setValue(bindPasswd); _configDao.persist(cvo); - } - catch (NamingException ne){ + if (cvo == null) { + cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.passwd.toString(), null, "Enter the password"); + } + cvo.setValue(bindPasswd); + _configDao.persist(cvo); + } catch (NamingException ne) { ne.printStackTrace(); - throw new InvalidParameterValueException("Naming Exception, check you ldap data ! " + ne.getMessage() + (ne.getCause() != null ? ( "Caused by:" + ne.getCause().getMessage()) : "")); + throw new InvalidParameterValueException("Naming Exception, check you ldap data ! " + ne.getMessage() + (ne.getCause() != null ? ("Caused by:" + ne.getCause().getMessage()) : "")); } return true; } @@ -1427,13 +1435,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura zone.setDns2(dns2); zone.setInternalDns1(internalDns1); zone.setInternalDns2(internalDns2); - + if (networkDomain != null) { - if (networkDomain.isEmpty()) { - zone.setDomain(null); - } else { + if (networkDomain.isEmpty()) { + zone.setDomain(null); + } else { zone.setDomain(networkDomain); - } + } } // update a private zone to public; not vice versa @@ -1456,31 +1464,32 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (allocationStateStr != null && !allocationStateStr.isEmpty()) { Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr); - if(allocationState == Grouping.AllocationState.Enabled){ - //check if zone has necessary trafficTypes before enabling - try{ - PhysicalNetwork mgmtPhyNetwork; - if(NetworkType.Advanced == zone.getNetworkType()){ - //zone should have a physical network with public and management traffiType + if (allocationState == Grouping.AllocationState.Enabled) { + // check if zone has necessary trafficTypes before enabling + try { + PhysicalNetwork mgmtPhyNetwork; + if (NetworkType.Advanced == zone.getNetworkType()) { + // zone should have a physical network with public and management traffiType _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public); mgmtPhyNetwork = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management); - }else{ - //zone should have a physical network with management traffiType - mgmtPhyNetwork = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management); + } else { + // zone should have a physical network with management traffiType + mgmtPhyNetwork = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management); } - + try { - _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage); + _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage); } catch (InvalidParameterValueException noStorage) { - PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(), TrafficType.Management); - _networkMgr.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(), TrafficType.Storage.toString(), mgmtTraffic.getXenNetworkLabel(), mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVmwareNetworkLabel(), mgmtTraffic.getSimulatorNetworkLabel(), mgmtTraffic.getVlan()); - s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network " + mgmtPhyNetwork.getId() + " with same configure of management traffic type"); + PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(), TrafficType.Management); + _networkMgr.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(), TrafficType.Storage.toString(), mgmtTraffic.getXenNetworkLabel(), mgmtTraffic.getKvmNetworkLabel(), + mgmtTraffic.getVmwareNetworkLabel(), mgmtTraffic.getSimulatorNetworkLabel(), mgmtTraffic.getVlan()); + s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network " + mgmtPhyNetwork.getId() + " with same configure of management traffic type"); } - }catch(InvalidParameterValueException ex){ - throw new InvalidParameterValueException("Cannot enable this Zone since: "+ ex.getMessage()); + } catch (InvalidParameterValueException ex) { + throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage()); } } - + zone.setAllocationState(allocationState); } @@ -1526,12 +1535,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (allocationStateStr != null && !allocationStateStr.isEmpty()) { Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr); zone.setAllocationState(allocationState); - }else{ - //Zone will be disabled since 3.0. Admin shoul enable it after physical network and providers setup. + } else { + // Zone will be disabled since 3.0. Admin shoul enable it after physical network and providers setup. zone.setAllocationState(Grouping.AllocationState.Disabled); } - zone = _zoneDao.persist(zone); - + zone = _zoneDao.persist(zone); + // Create default system networks createDefaultSystemNetworks(zone.getId()); @@ -1547,7 +1556,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - @Override public void createDefaultSystemNetworks(long zoneId) throws ConcurrentOperationException { DataCenterVO zone = _zoneDao.findById(zoneId); @@ -1575,7 +1583,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura continue; } } - + userNetwork.setBroadcastDomainType(broadcastDomainType); userNetwork.setNetworkDomain(networkDomain); _networkMgr.setupNetwork(systemAccount, offering, userNetwork, plan, null, null, false, Domain.ROOT_DOMAIN, null, null); @@ -1762,7 +1770,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (displayText != null) { offering.setDisplayText(displayText); } - + if (sortKey != null) { offering.setSortKey(sortKey); } @@ -1881,7 +1889,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (displayText != null) { diskOffering.setDisplayText(displayText); } - + if (sortKey != null) { diskOffering.setSortKey(sortKey); } @@ -2002,7 +2010,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Long networkId = cmd.getNetworkID(); String networkVlanId = null; Long physicalNetworkId = cmd.getPhysicalNetworkId(); - //projectId and accountName can't be specified together + // projectId and accountName can't be specified together String accountName = cmd.getAccountName(); Long projectId = cmd.getProjectId(); Long domainId = cmd.getDomainId(); @@ -2026,7 +2034,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Please specify a valid account."); } } - + // Verify that network exists Network network = null; if (networkId != null) { @@ -2039,15 +2047,15 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - //verify that physical network exists + // verify that physical network exists PhysicalNetworkVO pNtwk = null; - if(physicalNetworkId != null){ + if (physicalNetworkId != null) { pNtwk = _physicalNetworkDao.findById(physicalNetworkId); if (pNtwk == null) { throw new InvalidParameterValueException("Unable to find Physical Network with id=" + physicalNetworkId); } } - if(zoneId == null && pNtwk != null){ + if (zoneId == null && pNtwk != null) { zoneId = pNtwk.getDataCenterId(); } // Verify that zone exists @@ -2055,30 +2063,30 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zone == null) { throw new InvalidParameterValueException("Unable to find zone by id " + zoneId); } - - if(physicalNetworkId == null){ - //deduce physicalNetworkFrom Zone or Network. - if(network != null && network.getPhysicalNetworkId() != null){ + + if (physicalNetworkId == null) { + // deduce physicalNetworkFrom Zone or Network. + if (network != null && network.getPhysicalNetworkId() != null) { physicalNetworkId = network.getPhysicalNetworkId(); - }else{ + } else { if (forVirtualNetwork) { - //default physical network with public traffic in the zone + // default physical network with public traffic in the zone physicalNetworkId = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId(); } else { if (zone.getNetworkType() == DataCenter.NetworkType.Basic) { - //default physical network with guest traffic in the zone + // default physical network with guest traffic in the zone physicalNetworkId = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId(); - }else if(zone.getNetworkType() == DataCenter.NetworkType.Advanced) { - if(zone.isSecurityGroupEnabled()){ + } else if (zone.getNetworkType() == DataCenter.NetworkType.Advanced) { + if (zone.isSecurityGroupEnabled()) { physicalNetworkId = _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId(); - }else{ + } else { throw new InvalidParameterValueException("Physical Network Id is null, please provide the Network id for Direct vlan creation "); } } } } } - + // Check if zone is disabled Account caller = UserContext.current().getCaller(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { @@ -2113,14 +2121,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getGuestType()); } } - + if (network == null) { - network = _networkMgr.getNetwork(networkId); + network = _networkMgr.getNetwork(networkId); } - - //Can add vlan range only to the network which allows it + + // Can add vlan range only to the network which allows it if (!network.getSpecifyIpRanges()) { - throw new InvalidParameterValueException("Network " + network + " doesn't support adding multiple ip ranges"); + throw new InvalidParameterValueException("Network " + network + " doesn't support adding multiple ip ranges"); } // if end ip is not specified, default it to startIp @@ -2195,8 +2203,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura associateIpRangeToAccount = true; } } - - // Check if the IP range overlaps with the private ip + + // Check if the IP range overlaps with the private ip checkOverlapPrivateIpRange(zoneId, startIP, endIP); Transaction txn = Transaction.currentTxn(); txn.start(); @@ -2251,7 +2259,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zoneId == null || ((zone = _zoneDao.findById(zoneId)) == null)) { throw new InvalidParameterValueException("Please specify a valid zone."); } - + if (physicalNetworkId == null || ((_physicalNetworkDao.findById(physicalNetworkId)) == null)) { throw new InvalidParameterValueException("Please specify a valid physical network."); } @@ -2399,7 +2407,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura vlan = _vlanDao.persist(vlan); if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId, physicalNetworkId)) { - throw new CloudRuntimeException("Failed to save IP range. Please contact Cloud Support."); // It can be Direct IP or + throw new CloudRuntimeException("Failed to save IP range. Please contact Cloud Support."); // It can be +// Direct IP or // Public IP. } @@ -2713,7 +2722,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura public void checkPodCidrSubnets(long dcId, Long podIdToBeSkipped, String cidr) { // For each pod, return an error if any of the following is true: // The pod's CIDR subnet conflicts with the CIDR subnet of any other pod - + // Check if the CIDR conflicts with the Guest Network or other pods long skipPod = 0; if (podIdToBeSkipped != null) { @@ -2722,11 +2731,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura HashMap> currentPodCidrSubnets = _podDao.getCurrentPodCidrSubnets(dcId, skipPod); List newCidrPair = new ArrayList(); newCidrPair.add(0, getCidrAddress(cidr)); - newCidrPair.add(1, (long)getCidrSize(cidr)); + newCidrPair.add(1, (long) getCidrSize(cidr)); currentPodCidrSubnets.put(new Long(-1), newCidrPair); - + String zoneName = getZoneName(dcId); - + // Iterate through all pods in this zone for (Long podId : currentPodCidrSubnets.keySet()) { String podName; @@ -2744,7 +2753,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura cidrSizeToUse = cidrSize; String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSizeToUse); - + // Iterate through the rest of the pods for (Long otherPodId : currentPodCidrSubnets.keySet()) { if (podId.equals(otherPodId)) { @@ -2924,12 +2933,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (trafficType == null) { throw new InvalidParameterValueException("Invalid value for traffictype. Supported traffic types: Public, Management, Control, Guest, Vlan or Storage"); } - - //Only GUEST traffic type is supported in Acton + + // Only GUEST traffic type is supported in Acton if (trafficType != TrafficType.Guest) { throw new InvalidParameterValueException("Only traffic type " + TrafficType.Guest + " is supported in the current release"); } - + // Verify offering type for (Network.GuestType offType : Network.GuestType.values()) { if (offType.name().equalsIgnoreCase(cmd.getGuestIpType())) { @@ -2954,7 +2963,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } Long serviceOfferingId = cmd.getServiceOfferingId(); - + if (serviceOfferingId != null) { ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOfferingId); if (offering == null) { @@ -2964,21 +2973,21 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("The specified service offering " + serviceOfferingId + " cannot be used by virtual router!"); } } - + // configure service provider map Map> serviceProviderMap = new HashMap>(); Set defaultProviders = new HashSet(); - - //populate the services first + + // populate the services first for (String serviceName : cmd.getSupportedServices()) { - //validate if the service is supported + // validate if the service is supported Service service = Network.Service.getService(serviceName); if (service == null || service == Service.Gateway) { throw new InvalidParameterValueException("Invalid service " + serviceName); } - + if (service == Service.SecurityGroup) { - //allow security group service for Shared networks only + // allow security group service for Shared networks only if (guestType != GuestType.Shared) { throw new InvalidParameterValueException("Secrity group service is supported for network offerings with guest ip type " + GuestType.Shared); } @@ -2989,8 +2998,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } serviceProviderMap.put(service, defaultProviders); } - - //add gateway provider (if sourceNat provider is enabled) + + // add gateway provider (if sourceNat provider is enabled) Set sourceNatServiceProviders = serviceProviderMap.get(Service.SourceNat); if (sourceNatServiceProviders != null && !sourceNatServiceProviders.isEmpty()) { serviceProviderMap.put(Service.Gateway, sourceNatServiceProviders); @@ -3004,7 +3013,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Network.Service service = Network.Service.getService(serviceStr); if (serviceProviderMap.containsKey(service)) { Set providers = new HashSet(); - //in Acton, don't allow to specify more than 1 provider per service + // in Acton, don't allow to specify more than 1 provider per service if (svcPrv.get(serviceStr) != null && svcPrv.get(serviceStr).size() > 1) { throw new InvalidParameterValueException("In the current release only one provider can be specified for the service"); } @@ -3014,14 +3023,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (provider == null) { throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); } - - //Only VirtualRouter can be specified as a firewall provider + + // Only VirtualRouter can be specified as a firewall provider if (service == Service.Firewall && provider != Provider.VirtualRouter) { - throw new InvalidParameterValueException("Only Virtual router can be specified as a provider for the Firewall service"); + throw new InvalidParameterValueException("Only Virtual router can be specified as a provider for the Firewall service"); } - + providers.add(provider); - + Set serviceSet = null; if (providerCombinationToVerify.get(provider) == null) { serviceSet = new HashSet(); @@ -3030,7 +3039,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } serviceSet.add(service); providerCombinationToVerify.put(provider, serviceSet); - + } serviceProviderMap.put(service, providers); } else { @@ -3038,10 +3047,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } } - - //validate providers combination here + + // validate providers combination here _networkMgr.canProviderSupportServices(providerCombinationToVerify); - + // validate the LB service capabilities specified in the network offering Map lbServiceCapabilityMap = cmd.getServiceCapabilities(Service.Lb); if (!serviceProviderMap.containsKey(Service.Lb) && lbServiceCapabilityMap != null && !lbServiceCapabilityMap.isEmpty()) { @@ -3055,19 +3064,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Capabilities for source NAT service can be specifed only when source NAT service is enabled for network offering."); } validateSourceNatServiceCapablities(sourceNatServiceCapabilityMap); - + // validate the Static Nat service capabilities specified in the network offering Map staticNatServiceCapabilityMap = cmd.getServiceCapabilities(Service.StaticNat); if (!serviceProviderMap.containsKey(Service.StaticNat) && sourceNatServiceCapabilityMap != null && !staticNatServiceCapabilityMap.isEmpty()) { throw new InvalidParameterValueException("Capabilities for static NAT service can be specifed only when static NAT service is enabled for network offering."); } validateStaticNatServiceCapablities(staticNatServiceCapabilityMap); - + Map> serviceCapabilityMap = new HashMap>(); serviceCapabilityMap.put(Service.Lb, lbServiceCapabilityMap); serviceCapabilityMap.put(Service.SourceNat, sourceNatServiceCapabilityMap); serviceCapabilityMap.put(Service.StaticNat, staticNatServiceCapabilityMap); - + return createNetworkOffering(userId, name, displayText, trafficType, tags, specifyVlan, availability, networkRate, serviceProviderMap, false, guestType, false, serviceOfferingId, conserveMode, serviceCapabilityMap, specifyIpRanges); } @@ -3077,16 +3086,16 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (lbServiceCapabilityMap.keySet().size() > 2 || !lbServiceCapabilityMap.containsKey(Capability.SupportedLBIsolation)) { throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service"); } - + for (Capability cap : lbServiceCapabilityMap.keySet()) { - String value = lbServiceCapabilityMap.get(cap); - if (cap == Capability.SupportedLBIsolation) { - boolean dedicatedLb = value.contains("dedicated"); - boolean sharedLB = value.contains("shared"); - if ((dedicatedLb && sharedLB) || (!dedicatedLb && !sharedLB)){ + String value = lbServiceCapabilityMap.get(cap); + if (cap == Capability.SupportedLBIsolation) { + boolean dedicatedLb = value.contains("dedicated"); + boolean sharedLB = value.contains("shared"); + if ((dedicatedLb && sharedLB) || (!dedicatedLb && !sharedLB)) { throw new InvalidParameterValueException("Either dedicated or shared isolation can be specified for " + Capability.SupportedLBIsolation.getName()); } - } else if (cap == Capability.ElasticLb) { + } else if (cap == Capability.ElasticLb) { boolean enabled = value.contains("true"); boolean disabled = value.contains("false"); if (!enabled && !disabled) { @@ -3095,8 +3104,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } else { throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service"); } - } - } + } + } } void validateSourceNatServiceCapablities(Map sourceNatServiceCapabilityMap) { @@ -3104,15 +3113,15 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (sourceNatServiceCapabilityMap.keySet().size() > 2) { throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + " capabilities can be sepcified for source nat service"); } - + for (Capability capability : sourceNatServiceCapabilityMap.keySet()) { String value = sourceNatServiceCapabilityMap.get(capability); if (capability == Capability.SupportedSourceNatTypes) { - boolean perAccount = value.contains("peraccount"); - boolean perZone = value.contains("perzone"); - if ((perAccount && perZone) || (!perAccount && !perZone)) { - throw new InvalidParameterValueException("Either perAccount or perZone source NAT type can be specified for " + Capability.SupportedSourceNatTypes.getName()); - } + boolean perAccount = value.contains("peraccount"); + boolean perZone = value.contains("perzone"); + if ((perAccount && perZone) || (!perAccount && !perZone)) { + throw new InvalidParameterValueException("Either perAccount or perZone source NAT type can be specified for " + Capability.SupportedSourceNatTypes.getName()); + } } else if (capability == Capability.RedundantRouter) { boolean enabled = value.contains("true"); boolean disabled = value.contains("false"); @@ -3125,14 +3134,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } } - - + void validateStaticNatServiceCapablities(Map staticNatServiceCapabilityMap) { if (staticNatServiceCapabilityMap != null && !staticNatServiceCapabilityMap.isEmpty()) { if (staticNatServiceCapabilityMap.keySet().size() > 1) { throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capabilitiy can be sepcified for static nat service"); } - + for (Capability capability : staticNatServiceCapabilityMap.keySet()) { String value = staticNatServiceCapabilityMap.get(capability); if (capability == Capability.ElasticIp) { @@ -3151,87 +3159,90 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @DB public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, - Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, + Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode, Map> serviceCapabilityMap, boolean specifyIpRanges) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - - //specifyIpRanges should always be true for Shared network offerings + + // specifyIpRanges should always be true for Shared network offerings if (!specifyIpRanges && type == GuestType.Shared) { - throw new InvalidParameterValueException("SpecifyIpRanges should be true if network offering's type is " + type); + throw new InvalidParameterValueException("SpecifyIpRanges should be true if network offering's type is " + type); } - - //specifyVlan should always be true for Shared network offerings and Isolated network offerings with specifyIpRanges = true + + // specifyVlan should always be true for Shared network offerings and Isolated network offerings with +// specifyIpRanges = true if (!specifyVlan) { - if (type == GuestType.Shared) { - throw new InvalidParameterValueException("SpecifyVlan should be true if network offering's type is " + type); + if (type == GuestType.Shared) { + throw new InvalidParameterValueException("SpecifyVlan should be true if network offering's type is " + type); } else if (specifyIpRanges) { - throw new InvalidParameterValueException("SpecifyVlan should be true if network offering has specifyIpRanges=true"); + throw new InvalidParameterValueException("SpecifyVlan should be true if network offering has specifyIpRanges=true"); } } - - //validate availability value + + // validate availability value if (availability == NetworkOffering.Availability.Required) { - boolean canOffBeRequired = (type == GuestType.Isolated && serviceProviderMap.containsKey(Service.SourceNat)); - if (!canOffBeRequired) { - throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); - } - - //only one network offering in the system can be Required - List offerings = _networkOfferingDao.listByAvailability(Availability.Required, false); + boolean canOffBeRequired = (type == GuestType.Isolated && serviceProviderMap.containsKey(Service.SourceNat)); + if (!canOffBeRequired) { + throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + + Service.SourceNat.getName() + " enabled"); + } + + // only one network offering in the system can be Required + List offerings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (!offerings.isEmpty()) { - throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId() + " with availability " + Availability.Required); + throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId() + " with availability " + Availability.Required); } } Map lbServiceCapabilityMap = serviceCapabilityMap.get(Service.Lb); boolean dedicatedLb = false; boolean elasticLb = false; - if ((lbServiceCapabilityMap != null) && (!lbServiceCapabilityMap.isEmpty())) { - String isolationCapability = lbServiceCapabilityMap.get(Capability.SupportedLBIsolation); - if (isolationCapability != null) { - _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb, Capability.SupportedLBIsolation, isolationCapability); - dedicatedLb = isolationCapability.contains("dedicated"); + if ((lbServiceCapabilityMap != null) && (!lbServiceCapabilityMap.isEmpty())) { + String isolationCapability = lbServiceCapabilityMap.get(Capability.SupportedLBIsolation); + if (isolationCapability != null) { + _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb, Capability.SupportedLBIsolation, isolationCapability); + dedicatedLb = isolationCapability.contains("dedicated"); } else { - dedicatedLb = true; + dedicatedLb = true; } - + String param = lbServiceCapabilityMap.get(Capability.ElasticLb); if (param != null) { - elasticLb = param.contains("true"); + elasticLb = param.contains("true"); } } Map sourceNatServiceCapabilityMap = serviceCapabilityMap.get(Service.SourceNat); boolean sharedSourceNat = false; boolean redundantRouter = false; - if ((sourceNatServiceCapabilityMap != null) && (!sourceNatServiceCapabilityMap.isEmpty())) { + if ((sourceNatServiceCapabilityMap != null) && (!sourceNatServiceCapabilityMap.isEmpty())) { String sourceNatType = sourceNatServiceCapabilityMap.get(Capability.SupportedSourceNatTypes.getName()); if (sourceNatType != null) { - _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.SourceNat), Service.SourceNat, Capability.SupportedSourceNatTypes, sourceNatType); - sharedSourceNat = sourceNatType.contains("perzone"); + _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.SourceNat), Service.SourceNat, Capability.SupportedSourceNatTypes, sourceNatType); + sharedSourceNat = sourceNatType.contains("perzone"); } - + String param = sourceNatServiceCapabilityMap.get(Capability.RedundantRouter); if (param != null) { - _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.SourceNat), Service.SourceNat, Capability.RedundantRouter, param); + _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.SourceNat), Service.SourceNat, Capability.RedundantRouter, param); redundantRouter = param.contains("true"); } } - + Map staticNatServiceCapabilityMap = serviceCapabilityMap.get(Service.StaticNat); boolean elasticIp = false; - if ((staticNatServiceCapabilityMap != null) && (!staticNatServiceCapabilityMap.isEmpty())) { + if ((staticNatServiceCapabilityMap != null) && (!staticNatServiceCapabilityMap.isEmpty())) { String param = staticNatServiceCapabilityMap.get(Capability.ElasticIp); if (param != null) { elasticIp = param.contains("true"); } } - NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, isDefault, availability, tags, type, conserveMode, dedicatedLb, sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges); - + NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, isDefault, availability, tags, type, conserveMode, dedicatedLb, + sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges); + if (serviceOfferingId != null) { offering.setServiceOfferingId(serviceOfferingId); } @@ -3244,18 +3255,18 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // populate services and providers if (serviceProviderMap != null) { for (Network.Service service : serviceProviderMap.keySet()) { - Set providers = serviceProviderMap.get(service); - if (providers != null && !providers.isEmpty()) { - for (Network.Provider provider : providers) { + Set providers = serviceProviderMap.get(service); + if (providers != null && !providers.isEmpty()) { + for (Network.Provider provider : providers) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service, provider); _ntwkOffServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService + " with provider " + provider.getName()); } - } else { + } else { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service, null); _ntwkOffServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService + " with null provider"); - } + } } } @@ -3291,7 +3302,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (zoneId != null) { zone = getZone(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Unable to find the zone by id=" + zoneId); + throw new InvalidParameterValueException("Unable to find the zone by id=" + zoneId); } } @@ -3336,9 +3347,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (state != null) { sc.addAnd("state", SearchCriteria.Op.EQ, state); } - + if (specifyIpRanges != null) { - sc.addAnd("specifyIpRanges", SearchCriteria.Op.EQ, specifyIpRanges); + sc.addAnd("specifyIpRanges", SearchCriteria.Op.EQ, specifyIpRanges); } if (zone != null) { @@ -3379,19 +3390,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); } - + List offerings = _networkOfferingDao.search(sc, searchFilter); Boolean sourceNatSupported = cmd.getSourceNatSupported(); - - //filter by supported services + + // filter by supported services boolean listBySupportedServices = (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !offerings.isEmpty()); boolean checkIfProvidersAreEnabled = (zoneId != null); boolean parseOfferings = (listBySupportedServices || sourceNatSupported != null || checkIfProvidersAreEnabled); - + if (parseOfferings) { List supportedOfferings = new ArrayList(); Service[] supportedServices = null; - + if (listBySupportedServices) { supportedServices = new Service[supportedServicesStr.size()]; int i = 0; @@ -3405,29 +3416,29 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura i++; } } - + for (NetworkOfferingVO offering : offerings) { boolean addOffering = true; List checkForProviders = new ArrayList(); - + if (listBySupportedServices) { addOffering = addOffering && _networkMgr.areServicesSupportedByNetworkOffering(offering.getId(), supportedServices); } - + if (checkIfProvidersAreEnabled) { - if (supportedServices != null && supportedServices.length > 0) { - checkForProviders = Arrays.asList(supportedServices); - } else { - checkForProviders = _networkMgr.listNetworkOfferingServices(offering.getId()); - } - - addOffering = addOffering && _networkMgr.areServicesEnabledInZone(zoneId, offering.getId(), offering.getTags(), checkForProviders); + if (supportedServices != null && supportedServices.length > 0) { + checkForProviders = Arrays.asList(supportedServices); + } else { + checkForProviders = _networkMgr.listNetworkOfferingServices(offering.getId()); + } + + addOffering = addOffering && _networkMgr.areServicesEnabledInZone(zoneId, offering.getId(), offering.getTags(), checkForProviders); } - + if (sourceNatSupported != null) { addOffering = addOffering && (_networkMgr.areServicesSupportedByNetworkOffering(offering.getId(), Network.Service.SourceNat) == sourceNatSupported); } - + if (addOffering) { supportedOfferings.add(offering); } @@ -3497,7 +3508,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (displayText != null) { offering.setDisplayText(displayText); } - + if (sortKey != null) { offering.setSortKey(sortKey); } @@ -3525,18 +3536,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (availability == null) { throw new InvalidParameterValueException("Invalid value for Availability. Supported types: " + Availability.Required + ", " + Availability.Optional); } else { - if (availability == NetworkOffering.Availability.Required) { - boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkMgr.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat)); - if (!canOffBeRequired) { - throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); - } - - //only one network offering in the system can be Required - List offerings = _networkOfferingDao.listByAvailability(Availability.Required, false); - if (!offerings.isEmpty() && offerings.get(0).getId() != offeringToUpdate.getId()) { - throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId() + " with availability " + Availability.Required); - } - } + if (availability == NetworkOffering.Availability.Required) { + boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkMgr.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat)); + if (!canOffBeRequired) { + throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + + Service.SourceNat.getName() + " enabled"); + } + + // only one network offering in the system can be Required + List offerings = _networkOfferingDao.listByAvailability(Availability.Required, false); + if (!offerings.isEmpty() && offerings.get(0).getId() != offeringToUpdate.getId()) { + throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId() + " with availability " + Availability.Required); + } + } offering.setAvailability(availability); } } diff --git a/server/src/com/cloud/configuration/dao/ResourceLimitDao.java b/server/src/com/cloud/configuration/dao/ResourceLimitDao.java index 90ac4ffbcd8..04d872eb7eb 100644 --- a/server/src/com/cloud/configuration/dao/ResourceLimitDao.java +++ b/server/src/com/cloud/configuration/dao/ResourceLimitDao.java @@ -26,9 +26,12 @@ import com.cloud.configuration.ResourceLimitVO; import com.cloud.utils.db.GenericDao; public interface ResourceLimitDao extends GenericDao { - - List 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 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); } diff --git a/server/src/com/cloud/configuration/dao/ResourceLimitDaoImpl.java b/server/src/com/cloud/configuration/dao/ResourceLimitDaoImpl.java index 504068e808b..8c694c43434 100644 --- a/server/src/com/cloud/configuration/dao/ResourceLimitDaoImpl.java +++ b/server/src/com/cloud/configuration/dao/ResourceLimitDaoImpl.java @@ -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 implements ResourceLimitDao { - private SearchBuilder IdTypeSearch; + private SearchBuilder 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 listByOwner(Long ownerId, ResourceOwnerType ownerType) { - SearchCriteria 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 listByOwner(Long ownerId, ResourceOwnerType ownerType) { + SearchCriteria 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 } else { return new ArrayList(); } - } - - - @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 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 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; } - } + } } diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java index e18b876ba9a..7a0525c3014 100644 --- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java @@ -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 listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); 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 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 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 lbDevices =null; + List 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 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 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 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 lbDeviceUsageAnswerMap = new HashMap(); List accountsProcessed = new ArrayList(); - + 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 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); } + } diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 0bb62915002..6852f1303b4 100755 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -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 vm, List> networks) throws InsufficientCapacityException, ConcurrentOperationException; void prepare(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, - ResourceUnavailableException; + ResourceUnavailableException; void release(VirtualMachineProfile vmProfile, boolean forced); @@ -144,7 +146,7 @@ public interface NetworkManager extends NetworkService { String getNextAvailableMacAddressInNetwork(long networkConfigurationId) throws InsufficientAddressCapacityException; boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException; - + public boolean validateRule(FirewallRule rule); List getRemoteAccessVpnElements(); @@ -154,7 +156,7 @@ public interface NetworkManager extends NetworkService { List listPodVlans(long podId); Pair implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException; + InsufficientCapacityException; List 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> providersMap); + boolean isProviderForNetwork(Provider provider, long networkId); - PhysicalNetworkServiceProvider addDefaultSecurityGroupProviderToPhysicalNetwork( - long physicalNetworkId); + boolean isProviderForNetworkOffering(Provider provider, long networkOfferingId); + + void canProviderSupportServices(Map> providersMap); + + PhysicalNetworkServiceProvider addDefaultSecurityGroupProviderToPhysicalNetwork( + long physicalNetworkId); + + List getPhysicalNetworkInfo(long dcId, + HypervisorType hypervisorType); + + boolean canAddDefaultSecurityGroup(); + + List listNetworkOfferingServices(long networkOfferingId); + + boolean areServicesEnabledInZone(long zoneId, long networkOfferingId, String tags, List services); - List getPhysicalNetworkInfo(long dcId, - HypervisorType hypervisorType); - - boolean canAddDefaultSecurityGroup(); - - List listNetworkOfferingServices(long networkOfferingId); - - boolean areServicesEnabledInZone(long zoneId, long networkOfferingId, String tags, List services); - public Map> getIpToServices(List publicIps, boolean rulesRevoked, boolean includingFirewall); - + public Map> getProviderToIpList(Network network, Map> ipToServices); - + public boolean checkIpForService(IPAddressVO ip, Service service); void checkVirtualNetworkCidrOverlap(Long zoneId, String cidr); - void checkCapabilityForProvider(Set providers, Service service, - Capability cap, String capValue); + void checkCapabilityForProvider(Set 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 vm, - Network network, String requestedIp) - throws InsufficientVirtualNetworkCapcityException, - InsufficientAddressCapacityException; + void allocateDirectIp(NicProfile nic, DataCenter dc, + VirtualMachineProfile vm, + Network network, String requestedIp) + throws InsufficientVirtualNetworkCapcityException, + InsufficientAddressCapacityException; } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index e10c9368649..2404d2d6f86 100644 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -272,25 +272,38 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag VMInstanceDao _vmDao; @Inject FirewallManager _firewallMgr; - @Inject + @Inject FirewallRulesDao _firewallDao; @Inject - PortForwardingRulesDao _portForwardingDao; + PortForwardingRulesDao _portForwardingDao; @Inject ResourceLimitService _resourceLimitMgr; - @Inject DomainRouterDao _routerDao; - @Inject DomainManager _domainMgr; - @Inject ProjectManager _projectMgr; - @Inject NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; - @Inject PhysicalNetworkDao _physicalNetworkDao; - @Inject PhysicalNetworkServiceProviderDao _pNSPDao; - @Inject PortForwardingRulesDao _portForwardingRulesDao; - @Inject LoadBalancerDao _lbDao; - @Inject PhysicalNetworkTrafficTypeDao _pNTrafficTypeDao; - @Inject AgentManager _agentMgr; - @Inject HostDao _hostDao; - @Inject NetworkServiceMapDao _ntwkSrvcDao; - @Inject StorageNetworkManager _stnwMgr; + @Inject + DomainRouterDao _routerDao; + @Inject + DomainManager _domainMgr; + @Inject + ProjectManager _projectMgr; + @Inject + NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; + @Inject + PhysicalNetworkDao _physicalNetworkDao; + @Inject + PhysicalNetworkServiceProviderDao _pNSPDao; + @Inject + PortForwardingRulesDao _portForwardingRulesDao; + @Inject + LoadBalancerDao _lbDao; + @Inject + PhysicalNetworkTrafficTypeDao _pNTrafficTypeDao; + @Inject + AgentManager _agentMgr; + @Inject + HostDao _hostDao; + @Inject + NetworkServiceMapDao _ntwkSrvcDao; + @Inject + StorageNetworkManager _stnwMgr; private final HashMap _systemNetworks = new HashMap(5); @@ -311,31 +324,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag private Map _configs; - HashMap _lastNetworkIdsToFree = new HashMap(); private static HashMap> s_serviceToImplementedProvidersMap = new HashMap>(); private static HashMap s_providerToNetworkElementMap = new HashMap(); - public NetworkElement getElementImplementingProvider(String providerName){ + public NetworkElement getElementImplementingProvider(String providerName) { String elementName = s_providerToNetworkElementMap.get(providerName); NetworkElement element = _networkElements.get(elementName); return element; } @Override - public List getElementServices(Provider provider){ + public List getElementServices(Provider provider) { NetworkElement element = getElementImplementingProvider(provider.getName()); - if(element == null){ + if (element == null) { throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); } return new ArrayList(element.getCapabilities().keySet()); } @Override - public boolean canElementEnableIndividualServices(Provider provider){ + public boolean canElementEnableIndividualServices(Provider provider) { NetworkElement element = getElementImplementingProvider(provider.getName()); - if(element == null){ + if (element == null) { throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); } return element.canEnableIndividualServices(); @@ -368,7 +380,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } sc.setParameters("dc", dcId); - + DataCenter zone = _configMgr.getZone(dcId); // for direct network take ip addresses only from the vlans belonging to the network @@ -378,7 +390,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } sc.setJoinParameters("vlan", "type", vlanUse); - if (requestedIp != null) { sc.addAnd("address", SearchCriteria.Op.EQ, requestedIp); errorMessage.append(": requested ip " + requestedIp + " is not available"); @@ -426,8 +437,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag long macAddress = NetUtils.createSequenceBasedMacAddress(addr.getMacAddress()); - - return new PublicIp(addr, _vlanDao.findById(addr.getVlanId()), macAddress); } @@ -490,7 +499,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check that the maximum number of public IPs for the given accountId will not be exceeded try { - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.public_ip); + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.public_ip); } catch (ResourceAllocationException ex) { s_logger.warn("Failed to allocate resource of type " + ex.getResourceType() + " for account " + owner); throw new AccountLimitException("Maximum number of public IP addresses for account: " + owner.getAccountName() + " has been exceeded."); @@ -544,7 +553,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag /** * Returns the target account for an api command - * + * * @param accountName * - non-null if the account name was passed in in the command * @param domainId @@ -598,7 +607,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag markPublicIpAsAllocated(addr); } else if (addr.getState() == IpAddress.State.Releasing) { - // Cleanup all the resources for ip address if there are any, and only then un-assign ip in the system + // Cleanup all the resources for ip address if there are any, and only then un-assign ip in the +// system if (cleanupIpResources(addr.getId(), Account.ACCOUNT_ID_SYSTEM, _accountMgr.getSystemAccount())) { _ipAddressDao.unassignIpAddress(addr.getId()); } else { @@ -625,7 +635,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return map; } - + private Map> getServiceProvidersMap(long networkId) { Map> map = new HashMap>(); List nsms = _ntwkSrvcDao.getServicesInNetwork(networkId); @@ -639,7 +649,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return map; } - + /* Get a list of IPs, classify them by service */ @Override public Map> getIpToServices(List publicIps, boolean rulesRevoked, boolean includingFirewall) { @@ -664,8 +674,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag services.add(Service.StaticNat); } ipToServices.put(ip, services); - - //if IP in allocating state then it will not have any rules attached so skip IPAssoc to network service provider + + // if IP in allocating state then it will not have any rules attached so skip IPAssoc to network service +// provider if (ip.getState() == State.Allocating) { continue; } @@ -673,18 +684,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // check if any active rules are applied on the public IP Set purposes = getPublicIpPurposeInRules(ip, false, includingFirewall); if (purposes == null || purposes.isEmpty()) { - // since no active rules are there check if any rules are applied on the public IP but are in revoking state + // since no active rules are there check if any rules are applied on the public IP but are in +// revoking state purposes = getPublicIpPurposeInRules(ip, true, includingFirewall); if (purposes == null || purposes.isEmpty()) { // IP is not being used for any purpose so skip IPAssoc to network service provider continue; } else { if (rulesRevoked) { - // no active rules/revoked rules are associated with this public IP, so remove the association with the provider + // no active rules/revoked rules are associated with this public IP, so remove the +// association with the provider ip.setState(State.Releasing); } else { if (ip.getState() == State.Releasing) { - // rules are not revoked yet, so don't let the network service provider revoke the IP association + // rules are not revoked yet, so don't let the network service provider revoke the IP +// association // mark IP is allocated so that IP association will not be removed from the provider ip.setState(State.Allocated); } @@ -714,7 +728,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return ipToServices; } - + public boolean canIpUsedForNonConserveService(PublicIp ip, Service service) { // If it's non-conserve mode, then the new ip should not be used by any other services List ipList = new ArrayList(); @@ -729,12 +743,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (services.size() != 1) { throw new InvalidParameterException("There are multiple services used ip " + ip.getAddress() + "."); } - if (service != null && !((Service)services.toArray()[0] == service || service.equals(Service.Firewall))) { - throw new InvalidParameterException("The IP " + ip.getAddress() + " is already used as " + ((Service)services.toArray()[0]).getName() + " rather than " + service.getName()); + if (service != null && !((Service) services.toArray()[0] == service || service.equals(Service.Firewall))) { + throw new InvalidParameterException("The IP " + ip.getAddress() + " is already used as " + ((Service) services.toArray()[0]).getName() + " rather than " + service.getName()); } return true; } - + protected boolean canIpsUsedForNonConserve(List publicIps) { boolean result = true; for (PublicIp ip : publicIps) { @@ -745,7 +759,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return result; } - + public boolean canIpsUseOffering(List publicIps, long offeringId) { Map> ipToServices = getIpToServices(publicIps, false, true); Map> serviceToProviders = getNetworkOfferingServiceProvidersMap(offeringId); @@ -757,12 +771,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (curProviders == null || curProviders.isEmpty()) { continue; } - Provider curProvider = (Provider)curProviders.toArray()[0]; + Provider curProvider = (Provider) curProviders.toArray()[0]; if (provider == null) { provider = curProvider; continue; } - //We don't support multiple providers for one service now + // We don't support multiple providers for one service now if (!provider.equals(curProvider)) { throw new InvalidParameterException("There would be multiple providers for IP " + ip.getAddress() + " with the new network offering!"); } @@ -770,7 +784,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return true; } - + public boolean canIpUsedForService(PublicIp publicIp, Service service) { List ipList = new ArrayList(); ipList.add(publicIp); @@ -779,22 +793,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (services == null || services.isEmpty()) { return true; } - //We only support one provider for one service now + // We only support one provider for one service now Map> serviceToProviders = getServiceProvidersMap(publicIp.getAssociatedWithNetworkId()); - Set oldProviders = serviceToProviders.get((Service)services.toArray()[0]); - Provider oldProvider = (Provider)oldProviders.toArray()[0]; - //Since IP already has service to bind with, the oldProvider can't be null + Set oldProviders = serviceToProviders.get((Service) services.toArray()[0]); + Provider oldProvider = (Provider) oldProviders.toArray()[0]; + // Since IP already has service to bind with, the oldProvider can't be null Set newProviders = serviceToProviders.get(service); if (newProviders == null || newProviders.isEmpty()) { throw new InvalidParameterException("There is no new provider for IP " + publicIp.getAddress() + " of service " + service.getName() + "!"); } - Provider newProvider = (Provider)newProviders.toArray()[0]; + Provider newProvider = (Provider) newProviders.toArray()[0]; if (!oldProvider.equals(newProvider)) { throw new InvalidParameterException("There would be multiple providers for IP " + publicIp.getAddress() + "!"); } return true; } - + /* Return a mapping between provider in the network and the IP they should applied */ @Override public Map> getProviderToIpList(Network network, Map> ipToServices) { @@ -818,14 +832,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag serviceToIps.put(service, ips); } } - //TODO Check different provider for same IP + // TODO Check different provider for same IP Map> providerToServices = getProviderServicesMap(network.getId()); Map> providerToIpList = new HashMap>(); - for (Provider provider: providerToServices.keySet()) { + for (Provider provider : providerToServices.keySet()) { Set services = providerToServices.get(provider); ArrayList ipList = new ArrayList(); Set ipSet = new HashSet(); - for (Service service: services) { + for (Service service : services) { Set serviceIps = serviceToIps.get(service); if (serviceIps == null || serviceIps.isEmpty()) { continue; @@ -842,13 +856,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return providerToIpList; } - + protected boolean applyIpAssociations(Network network, boolean rulesRevoked, boolean continueOnError, List publicIps) throws ResourceUnavailableException { boolean success = true; - + Map> ipToServices = getIpToServices(publicIps, rulesRevoked, false); Map> providerToIpList = getProviderToIpList(network, ipToServices); - + for (Provider provider : providerToIpList.keySet()) { try { ArrayList ips = providerToIpList.get(provider); @@ -858,15 +872,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag IpDeployer deployer = null; NetworkElement element = getElementImplementingProvider(provider.getName()); if (element instanceof SourceNatServiceProvider) { - deployer = ((SourceNatServiceProvider)element).getIpDeployer(network); - } else if (element instanceof StaticNatServiceProvider) { - deployer = ((StaticNatServiceProvider)element).getIpDeployer(network); - } else if (element instanceof LoadBalancingServiceProvider) { - deployer = ((LoadBalancingServiceProvider)element).getIpDeployer(network); - } else if (element instanceof PortForwardingServiceProvider) { - deployer = ((PortForwardingServiceProvider)element).getIpDeployer(network); - } else if (element instanceof RemoteAccessVPNServiceProvider) { - deployer = ((RemoteAccessVPNServiceProvider)element).getIpDeployer(network); + deployer = ((SourceNatServiceProvider) element).getIpDeployer(network); + } else if (element instanceof StaticNatServiceProvider) { + deployer = ((StaticNatServiceProvider) element).getIpDeployer(network); + } else if (element instanceof LoadBalancingServiceProvider) { + deployer = ((LoadBalancingServiceProvider) element).getIpDeployer(network); + } else if (element instanceof PortForwardingServiceProvider) { + deployer = ((PortForwardingServiceProvider) element).getIpDeployer(network); + } else if (element instanceof RemoteAccessVPNServiceProvider) { + deployer = ((RemoteAccessVPNServiceProvider) element).getIpDeployer(network); } else { throw new CloudRuntimeException("Fail to get ip deployer for element: " + element); } @@ -899,7 +913,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { rules = _firewallDao.listByIpAndNotRevoked(ip.getId()); } - + if (rules == null || rules.isEmpty()) { return null; } @@ -925,42 +939,44 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public IpAddress allocateIP(long networkId, Account ipOwner, boolean isElastic) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = UserContext.current().getCaller(); long userId = UserContext.current().getCallerUserId(); - + long ownerId = ipOwner.getId(); Network network = _networksDao.findById(networkId); if (network == null) { throw new InvalidParameterValueException("Network id is invalid: " + networkId); } - - //check permissions + + // check permissions _accountMgr.checkAccess(caller, null, false, ipOwner); _accountMgr.checkAccess(ipOwner, AccessType.UseNetwork, false, network); - + DataCenter zone = _configMgr.getZone(network.getDataCenterId()); - - //allow associating IP addresses to guest network only + + // allow associating IP addresses to guest network only if (network.getTrafficType() != TrafficType.Guest) { - throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + TrafficType.Guest); - } - - //In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled - if (zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) { - throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " + Service.SourceNat.getName() + " enabled"); + throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + TrafficType.Guest); } - // Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network, and it + // In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled + if (zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) { + throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " + + Service.SourceNat.getName() + " enabled"); + } + + // Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network, +// and it // belongs to the system if (zone.getNetworkType() != NetworkType.Basic && network.getAccountId() != ipOwner.getId()) { throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); } - + VlanType vlanType = VlanType.VirtualNetwork; boolean assign = false; if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId()); } - + PublicIp ip = null; Transaction txn = Transaction.currentTxn(); @@ -987,7 +1003,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.start(); - NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); boolean sharedSourceNat = offering.getSharedSourceNat(); if (!sharedSourceNat) { @@ -1058,7 +1074,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Failed to associate ip address " + ip); _ipAddressDao.markAsUnavailable(ip.getId()); if (!applyIpAssociations(network, true)) { - // if fail to apply ip assciations again, unassign ip address without updating resource count and + // if fail to apply ip assciations again, unassign ip address without updating resource +// count and // generating usage event as there is no need to keep it in the db _ipAddressDao.unassignIpAddress(ip.getId()); } @@ -1112,7 +1129,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return success; } - @Override @DB + @Override + @DB public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; @@ -1139,7 +1157,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering); _systemNetworks.put(NetworkOfferingVO.SystemStorageNetwork, storageNetworkOffering); - //populate providers + // populate providers Map> defaultSharedNetworkOfferingProviders = new HashMap>(); Set defaultProviders = new HashSet(); @@ -1174,29 +1192,33 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); - //diff between offering #1 and #2 - securityGroup is enabled for the first, and disabled for the third + // diff between offering #1 and #2 - securityGroup is enabled for the first, and disabled for the third NetworkOfferingVO offering = null; if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOfferingWithSGService) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOfferingWithSGService, "Offering for Shared Security group enabled networks", TrafficType.Guest, null, true, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOfferingWithSGService, "Offering for Shared Security group enabled networks", TrafficType.Guest, + null, true, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, null, true, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, null, true, Availability.Optional, + null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, "Offering for Isolated networks with Source Nat service enabled", TrafficType.Guest, null, false, Availability.Required, null, defaultIsolatedSourceNatEnabledNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, false); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, "Offering for Isolated networks with Source Nat service enabled", + TrafficType.Guest, null, false, Availability.Required, null, defaultIsolatedSourceNatEnabledNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, false); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); - } + } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, null, true, Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, true); + offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, null, + true, Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } @@ -1267,24 +1289,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public boolean start() { - //populate s_serviceToImplementedProvidersMap & s_providerToNetworkElementMap with current _networkElements - //Need to do this in start() since _networkElements are not completely configured until then. + // populate s_serviceToImplementedProvidersMap & s_providerToNetworkElementMap with current _networkElements + // Need to do this in start() since _networkElements are not completely configured until then. for (NetworkElement element : _networkElements) { Map> capabilities = element.getCapabilities(); Provider implementedProvider = element.getProvider(); - if(implementedProvider != null){ - if(s_providerToNetworkElementMap.containsKey(implementedProvider.getName())){ - s_logger.error("Cannot start NetworkManager: Provider <-> NetworkElement must be a one-to-one map, multiple NetworkElements found for Provider: "+implementedProvider.getName()); + if (implementedProvider != null) { + if (s_providerToNetworkElementMap.containsKey(implementedProvider.getName())) { + s_logger.error("Cannot start NetworkManager: Provider <-> NetworkElement must be a one-to-one map, multiple NetworkElements found for Provider: " + implementedProvider.getName()); return false; } s_providerToNetworkElementMap.put(implementedProvider.getName(), element.getName()); } - if(capabilities != null && implementedProvider != null){ - for(Service service : capabilities.keySet()){ - if(s_serviceToImplementedProvidersMap.containsKey(service)){ + if (capabilities != null && implementedProvider != null) { + for (Service service : capabilities.keySet()) { + if (s_serviceToImplementedProvidersMap.containsKey(service)) { List providers = s_serviceToImplementedProvidersMap.get(service); providers.add(implementedProvider); - }else{ + } else { List providers = new ArrayList(); providers.add(implementedProvider); s_serviceToImplementedProvidersMap.put(service, providers); @@ -1338,7 +1360,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } try { - if (predefined == null || (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && predefined.getBroadcastDomainType() != BroadcastDomainType.Vlan)) { + if (predefined == null + || (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && predefined.getBroadcastDomainType() != BroadcastDomainType.Vlan)) { List configs = _networksDao.listBy(owner.getId(), offering.getId(), plan.getDataCenterId()); if (configs.size() > 0) { if (s_logger.isDebugEnabled()) { @@ -1352,7 +1375,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } else if (predefined != null && predefined.getCidr() != null && predefined.getBroadcastUri() == null) { - //don't allow to have 2 networks with the same cidr in the same zone for the account + // don't allow to have 2 networks with the same cidr in the same zone for the account List configs = _networksDao.listBy(owner.getId(), plan.getDataCenterId(), predefined.getCidr()); if (configs.size() > 0) { if (s_logger.isDebugEnabled()) { @@ -1390,7 +1413,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (related == -1) { related = id; } - + Transaction txn = Transaction.currentTxn(); txn.start(); @@ -1401,7 +1424,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (domainId != null && aclType == ACLType.Domain) { _networksDao.addDomainToNetwork(id, domainId, subdomainAccess); } - + txn.commit(); } @@ -1495,7 +1518,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag nics.add(vo); Integer networkRate = getNetworkRate(config.getId(), vm.getId()); - vm.addNic(new NicProfile(vo, network.first(), vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network.first()), getNetworkTag(vm.getHypervisorType(), network.first()))); + vm.addNic(new NicProfile(vo, network.first(), vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network.first()), getNetworkTag(vm.getHypervisorType(), + network.first()))); } if (nics.size() != networks.size()) { @@ -1601,7 +1625,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB public Pair implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + InsufficientCapacityException { Transaction.currentTxn(); Pair implemented = new Pair(null, null); @@ -1638,8 +1662,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setPhysicalNetworkId(result.getPhysicalNetworkId()); _networksDao.update(networkId, network); - //implement network elements and re-apply all the network rules - implementNetworkElementsAndResources(dest, context, network, offering); + // implement network elements and re-apply all the network rules + implementNetworkElementsAndResources(dest, context, network, offering); network.setState(Network.State.Implemented); network.setRestartRequired(false); @@ -1660,7 +1684,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag private void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, NetworkVO network, NetworkOfferingVO offering) throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { - // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a Shared source NAT rule, + // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a +// Shared source NAT rule, // associate a source NAT IP (if one isn't already associated with the network) boolean sharedSourceNat = offering.getSharedSourceNat(); @@ -1671,11 +1696,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (ips.isEmpty()) { s_logger.debug("Creating a source nat ip for " + network); Account owner = _accountMgr.getAccount(network.getAccountId()); - assignSourceNatIpAddress(owner, network, context.getCaller().getId()); + assignSourceNatIpAddress(owner, network, context.getCaller().getId()); } } - //get providers to implement + // get providers to implement List providersToImplement = getNetworkProviders(network.getId()); for (NetworkElement element : _networkElements) { if (providersToImplement.contains(element.getProvider())) { @@ -1707,13 +1732,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (areServicesSupportedInNetwork(network.getId(), Service.Dhcp) && isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, element.getProvider()) && (element instanceof DhcpServiceProvider)) { - DhcpServiceProvider sp = (DhcpServiceProvider)element; + DhcpServiceProvider sp = (DhcpServiceProvider) element; sp.addDhcpEntry(network, profile, vmProfile, dest, context); } if (areServicesSupportedInNetwork(network.getId(), Service.UserData) && isProviderSupportServiceInNetwork(network.getId(), Service.UserData, element.getProvider()) && (element instanceof UserDataServiceProvider)) { - UserDataServiceProvider sp = (UserDataServiceProvider)element; + UserDataServiceProvider sp = (UserDataServiceProvider) element; sp.addPasswordAndUserdata(network, profile, vmProfile, dest, context); } } @@ -1734,10 +1759,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public void prepare(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException { + ConcurrentOperationException, ResourceUnavailableException { List nics = _nicDao.listByVmId(vmProfile.getId()); - // we have to implement default nics first - to ensure that default network elements start up first in multiple nics + // we have to implement default nics first - to ensure that default network elements start up first in multiple +// nics // case) // (need for setting DNS on Dhcp to domR's Ip4 address) Collections.sort(nics, new Comparator() { @@ -1876,7 +1902,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB @ActionEvent(eventType = EventTypes.EVENT_NET_IP_RELEASE, eventDescription = "disassociating Ip", async = true) - public boolean disassociateIpAddress(long ipAddressId) throws InsufficientAddressCapacityException{ + public boolean disassociateIpAddress(long ipAddressId) throws InsufficientAddressCapacityException { Long userId = UserContext.current().getCallerUserId(); Account caller = UserContext.current().getCaller(); @@ -1891,7 +1917,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return true; } - //verify permissions + // verify permissions if (ipVO.getAllocatedToAccountId() != null) { _accountMgr.checkAccess(caller, null, true, ipVO); } @@ -1911,29 +1937,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (_accountVlanMapDao.findAccountVlanMap(ipVO.getAllocatedToAccountId(), ipVO.getVlanId()) != null) { throw new InvalidParameterValueException("Ip address id=" + ipAddressId + " belongs to Account wide IP pool and cannot be disassociated"); } - - //don't allow releasing elastic ip address + + // don't allow releasing elastic ip address if (ipVO.getElastic()) { - throw new InvalidParameterValueException("Can't release elastic IP address " + ipVO); + throw new InvalidParameterValueException("Can't release elastic IP address " + ipVO); } boolean success = releasePublicIpAddress(ipAddressId, userId, caller); if (success) { - Network guestNetwork = getNetwork(ipVO.getAssociatedWithNetworkId()); - NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); - Long vmId = ipVO.getAssociatedWithVmId(); - if (offering.getElasticIp() && vmId != null) { - _rulesMgr.enableElasticIpAndStaticNatForVm(_userVmDao.findById(vmId), true); - return true; - } - return true; + Network guestNetwork = getNetwork(ipVO.getAssociatedWithNetworkId()); + NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); + Long vmId = ipVO.getAssociatedWithVmId(); + if (offering.getElasticIp() && vmId != null) { + _rulesMgr.enableElasticIpAndStaticNatForVm(_userVmDao.findById(vmId), true); + return true; + } + return true; } else { - s_logger.warn("Failed to release public ip address id=" + ipAddressId); - return false; + s_logger.warn("Failed to release public ip address id=" + ipAddressId); + return false; } } - @Deprecated // No one is using this method. + @Deprecated + // No one is using this method. public AccountVO getNetworkOwner(long networkId) { SearchCriteria sc = AccountsUsingNetworkSearch.create(); sc.setJoinParameters("nc", "config", networkId); @@ -1942,7 +1969,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return accounts.size() != 0 ? accounts.get(0) : null; } - @Deprecated // No one is using this method. + @Deprecated + // No one is using this method. public List getNetworksforOffering(long offeringId, long dataCenterId, long accountId) { return _networksDao.getNetworksForOffering(offeringId, dataCenterId, accountId); } @@ -2001,7 +2029,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _nicDao.expunge(nic.getId()); } } - + private String getCidrAddress(String cidr) { String[] cidrPair = cidr.split("\\/"); return cidrPair[0]; @@ -2020,7 +2048,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (cidr == null) { return; } - List networks = _networksDao.listByZone((long)zoneId); + List networks = _networksDao.listByZone((long) zoneId); Map networkToCidr = new HashMap(); for (NetworkVO network : networks) { if (network.getGuestType() != GuestType.Isolated) { @@ -2033,26 +2061,26 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkToCidr == null || networkToCidr.isEmpty()) { return; } - + String currCidrAddress = getCidrAddress(cidr); int currCidrSize = getCidrSize(cidr); - + for (long networkId : networkToCidr.keySet()) { String ntwkCidr = networkToCidr.get(networkId); String ntwkCidrAddress = getCidrAddress(ntwkCidr); int ntwkCidrSize = getCidrSize(ntwkCidr); - + long cidrSizeToUse = currCidrSize < ntwkCidrSize ? currCidrSize : ntwkCidrSize; - + String ntwkCidrSubnet = NetUtils.getCidrSubNet(ntwkCidrAddress, cidrSizeToUse); String cidrSubnet = NetUtils.getCidrSubNet(currCidrAddress, cidrSizeToUse); - + if (cidrSubnet.equals(ntwkCidrSubnet)) { throw new InvalidParameterValueException("Warning: The existing network " + networkId + " have conflict CIDR subnets with new network!"); } } } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network") @@ -2080,7 +2108,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkOffering == null || networkOffering.isSystemOnly()) { throw new InvalidParameterValueException("Unable to find network offeirng by id " + networkOfferingId); } - //validate physical network and zone + // validate physical network and zone // Check if physical network exists PhysicalNetwork pNtwk = null; if (physicalNetworkId != null) { @@ -2099,47 +2127,47 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId()); } - //Only domain and account ACL types are supported in Acton. + // Only domain and account ACL types are supported in Acton. ACLType aclType = null; if (aclTypeStr != null) { if (aclTypeStr.equalsIgnoreCase(ACLType.Account.toString())) { aclType = ACLType.Account; - } else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())){ + } else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) { aclType = ACLType.Domain; } else { throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types"); } - //In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account + // In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account if (networkOffering.getGuestType() == GuestType.Isolated) { - if (aclType != ACLType.Account) { - throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + Network.GuestType.Isolated); - } - } else if (networkOffering.getGuestType() == GuestType.Shared) { - if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) { - throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + Network.GuestType.Shared); - } - } + if (aclType != ACLType.Account) { + throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + Network.GuestType.Isolated); + } + } else if (networkOffering.getGuestType() == GuestType.Shared) { + if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) { + throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + Network.GuestType.Shared); + } + } } else { - if (networkOffering.getGuestType() == GuestType.Isolated) { - aclType = ACLType.Account; - } else if (networkOffering.getGuestType() == GuestType.Shared) { - aclType = ACLType.Domain; - } + if (networkOffering.getGuestType() == GuestType.Isolated) { + aclType = ACLType.Account; + } else if (networkOffering.getGuestType() == GuestType.Shared) { + aclType = ACLType.Domain; + } } - - //Only Admin can create Shared networks + + // Only Admin can create Shared networks if (networkOffering.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getType())) { - throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared); + throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared); } // Check if the network is domain specific if (aclType == ACLType.Domain) { - //only Admin can create domain with aclType=Domain + // only Admin can create domain with aclType=Domain if (!_accountMgr.isAdmin(caller.getType())) { throw new PermissionDeniedException("Only admin can create networks with aclType=Domain"); } - //only shared networks can be Domain specific + // only shared networks can be Domain specific if (networkOffering.getGuestType() != GuestType.Shared) { throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain); } @@ -2147,7 +2175,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (domainId != null) { if (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != Network.GuestType.Shared) { throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type " + Network.GuestType.Shared); - } + } DomainVO domain = _domainDao.findById(domainId); if (domain == null) { @@ -2156,7 +2184,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _accountMgr.checkAccess(caller, domain); } isDomainSpecific = true; - + } else if (subdomainAccess != null) { throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain"); } @@ -2168,40 +2196,42 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } UserContext.current().setAccountId(owner.getAccountId()); - - //VALIDATE IP INFO + + // VALIDATE IP INFO // if end ip is not specified, default it to startIp if (startIP != null) { - if (!NetUtils.isValidIp(startIP)){ - throw new InvalidParameterValueException("Invalid format for the startIp parameter"); - } - if (endIP == null){ + if (!NetUtils.isValidIp(startIP)) { + throw new InvalidParameterValueException("Invalid format for the startIp parameter"); + } + if (endIP == null) { endIP = startIP; - } else if (!NetUtils.isValidIp(endIP)) { - throw new InvalidParameterValueException("Invalid format for the endIp parameter"); - } + } else if (!NetUtils.isValidIp(endIP)) { + throw new InvalidParameterValueException("Invalid format for the endIp parameter"); + } } - + if (startIP != null && endIP != null) { - if (!(gateway != null && netmask != null)) { + if (!(gateway != null && netmask != null)) { throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in"); - } + } } String cidr = null; if (gateway != null && netmask != null) { - if (!NetUtils.isValidIp(gateway)) { - throw new InvalidParameterValueException("Invalid gateway"); - } - if (!NetUtils.isValidNetmask(netmask)) { - throw new InvalidParameterValueException("Invalid netmask"); - } - + if (!NetUtils.isValidIp(gateway)) { + throw new InvalidParameterValueException("Invalid gateway"); + } + if (!NetUtils.isValidNetmask(netmask)) { + throw new InvalidParameterValueException("Invalid netmask"); + } + cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); } // Regular user can create Guest Isolated Source Nat enabled network only - if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != Network.GuestType.Isolated && areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))) { + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL + && (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != Network.GuestType.Isolated + && areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and network type " + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled"); } @@ -2221,26 +2251,26 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit); } } - + if (cidr != null && networkOfferingIsConfiguredForExternalNetworking(networkOfferingId)) { throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external firewall!"); } - + if (cidr != null) { checkVirtualNetworkCidrOverlap(zoneId, cidr); } - //Vlan is created in 2 cases - works in Advance zone only: - //1) GuestType is Shared - //2) GuestType is Isolated, but SourceNat service is disabled - boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced - && ((networkOffering.getGuestType() == Network.GuestType.Shared) - || (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat)))); - - //Can add vlan range only to the network which allows it + // Vlan is created in 2 cases - works in Advance zone only: + // 1) GuestType is Shared + // 2) GuestType is Isolated, but SourceNat service is disabled + boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced + && ((networkOffering.getGuestType() == Network.GuestType.Shared) + || (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat)))); + + // Can add vlan range only to the network which allows it if (createVlan && !networkOffering.getSpecifyIpRanges()) { - throw new InvalidParameterValueException("Network offering " + networkOffering + " doesn't support adding multiple ip ranges"); + throw new InvalidParameterValueException("Network offering " + networkOffering + " doesn't support adding multiple ip ranges"); } - + Transaction txn = Transaction.currentTxn(); txn.start(); @@ -2253,14 +2283,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag subdomainAccess = true; } } - - //default owner to system if network has aclType=Domain + + // default owner to system if network has aclType=Domain if (aclType == ACLType.Domain) { - owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM); + owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM); } Network network = createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, false, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess); - + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && createVlan) { // Create vlan ip range _configMgr.createVlanAndPublicIpRange(userId, pNtwk.getDataCenterId(), null, startIP, endIP, gateway, netmask, false, vlanId, null, network.getId(), physicalNetworkId); @@ -2277,37 +2307,38 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Long domainId, PhysicalNetwork pNtwk, long zoneId, ACLType aclType, Boolean subdomainAccess) throws ConcurrentOperationException, InsufficientCapacityException { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); - //this method supports only guest network creation + // this method supports only guest network creation if (networkOffering.getTrafficType() != TrafficType.Guest) { s_logger.warn("Only guest networks can be created using this method"); return null; } - //Validate network offering + // Validate network offering if (networkOffering.getState() != NetworkOffering.State.Enabled) { throw new InvalidParameterValueException("Can't use network offering id=" + networkOfferingId + " as its state is not " + NetworkOffering.State.Enabled); } - //Validate physical network + // Validate physical network if (pNtwk.getState() != PhysicalNetwork.State.Enabled) { throw new InvalidParameterValueException("Physical network id " + pNtwk.getId() + " is in incorrect state: " + pNtwk.getState()); } - //Validate zone + // Validate zone DataCenterVO zone = _dcDao.findById(zoneId); if (zone.getNetworkType() == NetworkType.Basic) { - //Only one guest network is supported in Basic zone + // Only one guest network is supported in Basic zone List guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest); if (!guestNetworks.isEmpty()) { throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic); } - //if zone is basic, only Shared network offerings w/o source nat service are allowed + // if zone is basic, only Shared network offerings w/o source nat service are allowed if (!(networkOffering.getGuestType() == GuestType.Shared && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))) { - throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + " service are allowed"); + throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + + " service are allowed"); } - //In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true + // In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true if (aclType == null || aclType != ACLType.Domain) { throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone"); } @@ -2332,7 +2363,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else if (zone.getNetworkType() == NetworkType.Advanced) { if (zone.isSecurityGroupEnabled()) { - //Only Account specific Isolated network with sourceNat service disabled are allowed in security group enabled zone + // Only Account specific Isolated network with sourceNat service disabled are allowed in security group +// enabled zone boolean allowCreation = (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat)); if (!allowCreation) { throw new InvalidParameterValueException("Only Account specific Isolated network with sourceNat service disabled are allowed in security group enabled zone"); @@ -2341,13 +2373,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // VlanId can be specified only when network offering supports it - boolean vlanSpecified = (vlanId != null); + boolean vlanSpecified = (vlanId != null); if (vlanSpecified != networkOffering.getSpecifyVlan()) { - if (vlanSpecified) { + if (vlanSpecified) { throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false"); - } else { + } else { throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true"); - } + } } // Don't allow to create network with vlan that already exists in the system @@ -2368,14 +2400,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } else { if (networkDomain == null) { - //1) Get networkDomain from the corresponding account/domain/zone - if (aclType == ACLType.Domain) { + // 1) Get networkDomain from the corresponding account/domain/zone + if (aclType == ACLType.Domain) { networkDomain = getDomainNetworkDomain(domainId, zoneId); - } else if (aclType == ACLType.Account){ + } else if (aclType == ACLType.Account) { networkDomain = getAccountNetworkDomain(owner.getId(), zoneId); - } + } - //2) If null, generate networkDomain using domain suffix from the global config variables + // 2) If null, generate networkDomain using domain suffix from the global config variables if (networkDomain == null) { networkDomain = "cs" + Long.toHexString(owner.getId()) + _networkDomain; } @@ -2391,14 +2423,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - // In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x limitation, remove after we introduce support for multiple ip ranges + // In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x +// limitation, remove after we introduce support for multiple ip ranges // with different Cidrs for the same Shared network - boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced && networkOffering.getTrafficType() == TrafficType.Guest && (networkOffering.getGuestType() == GuestType.Shared || (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))); + boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced && networkOffering.getTrafficType() == TrafficType.Guest + && (networkOffering.getGuestType() == GuestType.Shared || (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))); if (cidr == null && cidrRequired) { - throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of type " + Network.GuestType.Shared + " and network of type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled"); - } + throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of type " + Network.GuestType.Shared + " and network of type " + GuestType.Isolated + " with service " + + Service.SourceNat.getName() + " disabled"); + } - //No cidr can be specified in Basic zone + // No cidr can be specified in Basic zone if (zone.getNetworkType() == NetworkType.Basic && cidr != null) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic); } @@ -2444,7 +2479,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networks.size() > 1) { throw new InvalidParameterValueException("Cannot determine a guest network to deploy in, please specify one"); } - if (networks.size() > 0 && networks.get(0).getGuestType()== Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) { + if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) { network = networks.get(0); } else { // For shared network @@ -2474,13 +2509,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String path = null; Long physicalNetworkId = cmd.getPhysicalNetworkId(); List supportedServicesStr = cmd.getSupportedServices(); - Boolean restartRequired= cmd.getRestartRequired(); + Boolean restartRequired = cmd.getRestartRequired(); boolean listAll = cmd.listAll(); boolean isRecursive = cmd.isRecursive(); Boolean specifyIpRanges = cmd.getSpecifyIpRanges(); - //1) default is system to false if not specified - //2) reset parameter to false if it's specified by the regular user + // 1) default is system to false if not specified + // 2) reset parameter to false if it's specified by the regular user if ((isSystem == null || caller.getType() == Account.ACCOUNT_TYPE_NORMAL) && id == null) { isSystem = false; } @@ -2512,18 +2547,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag permittedAccounts.add(caller.getId()); domainId = caller.getDomainId(); } - + if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { - domainId = caller.getDomainId(); + domainId = caller.getDomainId(); } - //set project information + // set project information boolean skipProjectNetworks = true; if (projectId != null) { - if (projectId == -1) { + if (projectId == -1) { permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId())); - } else { - permittedAccounts.clear(); + } else { + permittedAccounts.clear(); Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); @@ -2532,13 +2567,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Account " + caller + " can't access project id=" + projectId); } permittedAccounts.add(project.getProjectAccountId()); - } - skipProjectNetworks = false; + } + skipProjectNetworks = false; } path = _domainDao.findById(caller.getDomainId()).getPath(); if (listAll) { - isRecursive = true; + isRecursive = true; } Filter searchFilter = new Filter(NetworkVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -2562,28 +2597,36 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + if (skipProjectNetworks) { - SearchBuilder accountSearch = _accountDao.createSearchBuilder(); - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + SearchBuilder accountSearch = _accountDao.createSearchBuilder(); + accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); + sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); } List networksToReturn = new ArrayList(); if (isSystem == null || !isSystem) { - //Get domain level networks + // Get domain level networks if (domainId != null) { - networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, domainId)); - } - + networksToReturn + .addAll(listDomainLevelNetworks( + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, + domainId)); + } + if (!permittedAccounts.isEmpty()) { - networksToReturn.addAll(listAccountSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, permittedAccounts)); - } else if (domainId == null || listAll){ - networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, path, isRecursive)); - } + networksToReturn.addAll(listAccountSpecificNetworks( + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, + permittedAccounts)); + } else if (domainId == null || listAll) { + networksToReturn.addAll(listAccountSpecificNetworksByDomainPath( + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, path, + isRecursive)); + } } else { - networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter); + networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, specifyIpRanges), + searchFilter); } if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) { @@ -2612,7 +2655,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String guestIpType, String trafficType, Long physicalNetworkId, String aclType, boolean skipProjectNetworks, Boolean restartRequired, Boolean specifyIpRanges) { + private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String guestIpType, String trafficType, Long physicalNetworkId, + String aclType, boolean skipProjectNetworks, Boolean restartRequired, Boolean specifyIpRanges) { SearchCriteria sc = sb.create(); if (isSystem != null) { @@ -2648,15 +2692,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (physicalNetworkId != null) { sc.addAnd("physicalNetworkId", SearchCriteria.Op.EQ, physicalNetworkId); } - + if (skipProjectNetworks) { - sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); + sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); } - + if (restartRequired != null) { sc.addAnd("restartRequired", SearchCriteria.Op.EQ, restartRequired); } - + if (specifyIpRanges != null) { sc.addAnd("specifyIpRanges", SearchCriteria.Op.EQ, specifyIpRanges); } @@ -2664,7 +2708,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return sc; } - private List listDomainLevelNetworks(SearchCriteria sc, Filter searchFilter, long domainId) { List networkIds = new ArrayList(); Set allowedDomains = _domainMgr.getDomainParentIds(domainId); @@ -2706,11 +2749,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag accountSC.addAnd("aclType", SearchCriteria.Op.EQ, ACLType.Account.toString()); if (path != null) { - if (isRecursive) { + if (isRecursive) { sc.setJoinParameters("domainSearch", "path", path + "%"); - } else { + } else { sc.setJoinParameters("domainSearch", "path", path); - } + } } return _networksDao.search(sc, searchFilter); @@ -2728,7 +2771,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("unable to find network " + networkId); } - //don't allow to delete system network + // don't allow to delete system network if (isNetworkSystem(network)) { throw new InvalidParameterValueException("Network " + network + " is system and can't be removed"); } @@ -2790,28 +2833,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } private boolean shutdownNetworkElementsAndResources(ReservationContext context, boolean cleanupElements, NetworkVO network) { - //1) Cleanup all the rules for the network. If it fails, just log the failure and proceed with shutting down the elements + // 1) Cleanup all the rules for the network. If it fails, just log the failure and proceed with shutting down +// the elements boolean cleanupResult = true; try { cleanupResult = shutdownNetworkResources(network.getId(), context.getAccount(), context.getCaller().getId()); } catch (Exception ex) { s_logger.warn("shutdownNetworkRules failed during the network " + network + " shutdown due to ", ex); } finally { - //just warn the administrator that the network elements failed to shutdown + // just warn the administrator that the network elements failed to shutdown if (!cleanupResult) { s_logger.warn("Failed to cleanup network id=" + network.getId() + " resources as a part of shutdownNetwork"); } - } + } - //2) Shutdown all the network elements - //get providers to shutdown + // 2) Shutdown all the network elements + // get providers to shutdown List providersToShutdown = getNetworkProviders(network.getId()); boolean success = true; for (NetworkElement element : _networkElements) { if (providersToShutdown.contains(element.getProvider())) { try { if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { - s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network " + getPhysicalNetworkId(network)); + s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network " + + getPhysicalNetworkId(network)); success = false; } if (s_logger.isDebugEnabled()) { @@ -2880,13 +2925,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } - //get providers to destroy + // get providers to destroy List providersToDestroy = getNetworkProviders(network.getId()); for (NetworkElement element : _networkElements) { if (providersToDestroy.contains(element.getProvider())) { try { if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { - s_logger.warn("Unable to complete destroy of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network " + getPhysicalNetworkId(network)); + s_logger.warn("Unable to complete destroy of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network " + + getPhysicalNetworkId(network)); success = false; } @@ -2968,6 +3014,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return true; } + @Override /* The rules here is only the same kind of rule, e.g. all load balancing rules or all port forwarding rules */ public boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException { @@ -2979,7 +3026,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean success = true; Network network = _networksDao.findById(rules.get(0).getNetworkId()); Purpose purpose = rules.get(0).getPurpose(); - + // get the list of public ip's owned by the network List userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null); List publicIps = new ArrayList(); @@ -2995,39 +3042,39 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag applyIpAssociations(network, false, continueOnError, publicIps); for (NetworkElement ne : _networkElements) { - Provider provider = Network.Provider.getProvider(ne.getName()); - if (provider == null) { - if (ne.getName().equalsIgnoreCase("Ovs") || ne.getName().equalsIgnoreCase("BareMetal")) { - continue; - } - throw new CloudRuntimeException("Unable to identify the provider by name " + ne.getName()); - } + Provider provider = Network.Provider.getProvider(ne.getName()); + if (provider == null) { + if (ne.getName().equalsIgnoreCase("Ovs") || ne.getName().equalsIgnoreCase("BareMetal")) { + continue; + } + throw new CloudRuntimeException("Unable to identify the provider by name " + ne.getName()); + } try { boolean handled; switch (purpose) { case LoadBalancing: - boolean isLbProvider = isProviderSupportServiceInNetwork(network.getId(), Service.Lb, provider); + boolean isLbProvider = isProviderSupportServiceInNetwork(network.getId(), Service.Lb, provider); if (!(ne instanceof LoadBalancingServiceProvider && isLbProvider)) { continue; } - handled = ((LoadBalancingServiceProvider)ne).applyLBRules(network, (List)rules); + handled = ((LoadBalancingServiceProvider) ne).applyLBRules(network, (List) rules); break; case PortForwarding: - boolean isPfProvider = isProviderSupportServiceInNetwork(network.getId(), Service.PortForwarding, provider); + boolean isPfProvider = isProviderSupportServiceInNetwork(network.getId(), Service.PortForwarding, provider); if (!(ne instanceof PortForwardingServiceProvider && isPfProvider)) { continue; } - handled = ((PortForwardingServiceProvider)ne).applyPFRules(network, (List)rules); + handled = ((PortForwardingServiceProvider) ne).applyPFRules(network, (List) rules); break; case StaticNat: /* It's firewall rule for static nat, not static nat rule */ /* Fall through */ case Firewall: - boolean isFirewallProvider = isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, provider); + boolean isFirewallProvider = isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, provider); if (!(ne instanceof FirewallServiceProvider && isFirewallProvider)) { continue; } - handled = ((FirewallServiceProvider)ne).applyFWRules(network, rules); + handled = ((FirewallServiceProvider) ne).applyFWRules(network, rules); break; default: s_logger.debug("Unable to handle network rules for purpose: " + purpose.toString()); @@ -3123,11 +3170,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (!(network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) { throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + Network.State.Setup); } - - //don't allow clenaup=true for the network in Basic zone + + // don't allow clenaup=true for the network in Basic zone DataCenter zone = _configMgr.getZone(network.getDataCenterId()); if (zone.getNetworkType() == NetworkType.Basic && cleanup) { - throw new InvalidParameterValueException("Cleanup can't be true when restart network in Basic zone"); + throw new InvalidParameterValueException("Cleanup can't be true when restart network in Basic zone"); } _accountMgr.checkAccess(callerAccount, null, true, network); @@ -3170,13 +3217,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Restarting network " + networkId + "..."); ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); - + if (cleanup) { if (network.getGuestType() != GuestType.Isolated) { s_logger.warn("Only support clean up network for isolated network!"); return false; } - //shutdown the network + // shutdown the network s_logger.debug("Shutting down the network id=" + networkId + " as a part of network restart"); if (!shutdownNetworkElementsAndResources(context, true, network)) { @@ -3188,7 +3235,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Skip the shutting down of network id=" + networkId); } - //implement the network elements and rules again + // implement the network elements and rules again DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); s_logger.debug("Implementing the network " + network + " elements and resources as a part of network restart"); @@ -3205,14 +3252,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return true; } - private void setRestartRequired(NetworkVO network, boolean restartRequired) { - s_logger.debug("Marking network " + network + " with restartRequired=" + restartRequired); - network.setRestartRequired(restartRequired); - _networksDao.update(network.getId(), network); - } + private void setRestartRequired(NetworkVO network, boolean restartRequired) { + s_logger.debug("Marking network " + network + " with restartRequired=" + restartRequired); + network.setRestartRequired(restartRequired); + _networksDao.update(network.getId(), network); + } - - //This method re-programs the rules/ips for existing network + // This method re-programs the rules/ips for existing network protected boolean reprogramNetworkRules(long networkId, Account caller, NetworkVO network) throws ResourceUnavailableException { boolean success = true; // associate all ip addresses @@ -3271,19 +3317,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _networksDao.getActiveNicsIn(networkId); } - @Override public Map> getNetworkCapabilities(long networkId) { Map> networkCapabilities = new HashMap>(); - //list all services of this networkOffering + // list all services of this networkOffering List servicesMap = _ntwkSrvcDao.getServicesInNetwork(networkId); - for(NetworkServiceMapVO instance : servicesMap ){ + for (NetworkServiceMapVO instance : servicesMap) { Service service = Service.getService(instance.getService()); NetworkElement element = getElementImplementingProvider(instance.getProvider()); - if(element != null){ - Map> elementCapabilities = element.getCapabilities();; + if (element != null) { + Map> elementCapabilities = element.getCapabilities(); + ; if (elementCapabilities != null) { networkCapabilities.put(service, elementCapabilities.get(service)); } @@ -3302,12 +3348,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Map serviceCapabilities = new HashMap(); - //get the Provider for this Service for this offering + // get the Provider for this Service for this offering String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(networkId, service); NetworkElement element = getElementImplementingProvider(provider); - if(element != null){ - Map> elementCapabilities = element.getCapabilities();; + if (element != null) { + Map> elementCapabilities = element.getCapabilities(); + ; if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider); @@ -3327,19 +3374,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Map serviceCapabilities = new HashMap(); - //get the Provider for this Service for this offering + // get the Provider for this Service for this offering List providers = _ntwkOfferingSrvcDao.listProvidersForServiceForNetworkOffering(offering.getId(), service); if (providers.isEmpty()) { - throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering); + throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering); } - - //FIXME - in post 3.0 we are going to support multiple providers for the same service per network offering, so we have to calculate capabilities for all of them + + // FIXME - in post 3.0 we are going to support multiple providers for the same service per network offering, so +// we have to calculate capabilities for all of them String provider = providers.get(0); - //FIXME we return the capabilities of the first provider of the service - what if we have multiple providers for same Service? + // FIXME we return the capabilities of the first provider of the service - what if we have multiple providers +// for same Service? NetworkElement element = getElementImplementingProvider(provider); - if(element != null){ - Map> elementCapabilities = element.getCapabilities();; + if (element != null) { + Map> elementCapabilities = element.getCapabilities(); + ; if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider); @@ -3439,7 +3489,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return guestNic.getIp4Address(); } - private Nic getNicInNetworkIncludingRemoved(long vmId, long networkId) { return _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(networkId, vmId); } @@ -3447,7 +3496,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB public boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network network) throws InsufficientCapacityException, ConcurrentOperationException, - ResourceUnavailableException { + ResourceUnavailableException { Account owner = _accountMgr.getActiveAccountById(accountId); boolean createNetwork = false; @@ -3468,7 +3517,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (createNetwork) { List offerings = _configMgr.listNetworkOfferings(TrafficType.Guest, false); PhysicalNetwork physicalNetwork = translateZoneIdToPhysicalNetwork(zoneId); - network = createGuestNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, owner, false, null, physicalNetwork, zoneId, ACLType.Account, null); + network = createGuestNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, owner, false, null, physicalNetwork, zoneId, + ACLType.Account, null); if (network == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); @@ -3571,14 +3621,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List elements = new ArrayList(); for (NetworkElement element : _networkElements) { if (element instanceof UserDataServiceProvider) { - UserDataServiceProvider e = (UserDataServiceProvider)element; + UserDataServiceProvider e = (UserDataServiceProvider) element; elements.add(e); } } return elements; } - @Override public boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkId) { boolean netscalerInNetwork = isProviderForNetwork(Network.Provider.Netscaler, networkId); @@ -3590,7 +3639,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { return false; } - } + } public boolean networkOfferingIsConfiguredForExternalNetworking(long networkOfferingId) { boolean netscalerInNetworkOffering = isProviderForNetworkOffering(Network.Provider.Netscaler, networkOfferingId); @@ -3602,7 +3651,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { return false; } - } + } @Override public boolean areServicesSupportedByNetworkOffering(long networkOfferingId, Service... services) { @@ -3617,7 +3666,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag private boolean cleanupIpResources(long ipId, long userId, Account caller) { boolean success = true; - //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 public IP id=" + ipId + " release..."); if (!_firewallMgr.revokeFirewallRulesForIp(ipId, userId, caller)) { @@ -3629,7 +3678,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag success = false; } - //Revoke all PF/Static nat rules for the ip + // Revoke all PF/Static nat rules for the ip try { s_logger.debug("Revoking all " + Purpose.PortForwarding + "/" + Purpose.StaticNat + " rules as a part of public IP id=" + ipId + " release..."); if (!_rulesMgr.revokeAllPFAndStaticNatRulesForIp(ipId, userId, caller)) { @@ -3649,7 +3698,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // remote access vpn can be enabled only for static nat ip, so this part should never be executed under normal // conditions - // only when ip address failed to be cleaned up as a part of account destroy and was marked as Releasing, this part of + // only when ip address failed to be cleaned up as a part of account destroy and was marked as Releasing, this +// part of // the code would be triggered s_logger.debug("Cleaning up remote access vpns as a part of public IP id=" + ipId + " release..."); try { @@ -3781,7 +3831,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - @Override @DB + @Override + @DB @ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true) public Network updateGuestNetwork(long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, Long networkOfferingId) { boolean restartNetwork = false; @@ -3791,24 +3842,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (network == null) { throw new InvalidParameterValueException("Network id=" + networkId + "doesn't exist in the system"); } - - //don't allow to update network in Destroy state + + // don't allow to update network in Destroy state if (network.getState() == Network.State.Destroy) { - throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy); + throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy); } - + // Don't allow to update system network NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId()); if (offering.isSystemOnly()) { throw new InvalidParameterValueException("Can't update system networks"); } - - //allow to upgrade only Guest networks - if (network.getTrafficType() != Networks.TrafficType.Guest) { - throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest); - } - _accountMgr.checkAccess(callerAccount, null, true, network); + // allow to upgrade only Guest networks + if (network.getTrafficType() != Networks.TrafficType.Guest) { + throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest); + } + + _accountMgr.checkAccess(callerAccount, null, true, network); if (name != null) { network.setName(name); @@ -3817,14 +3868,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (displayText != null) { network.setDisplayText(displayText); } - - //network offering and domain suffix can be updated for Isolated networks only in 3.0 + + // network offering and domain suffix can be updated for Isolated networks only in 3.0 if ((networkOfferingId != null || domainSuffix != null) && network.getGuestType() != GuestType.Isolated) { - throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only"); + throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only"); } boolean networkOfferingChanged = false; - + long oldNetworkOfferingId = network.getNetworkOfferingId(); if (networkOfferingId != null) { @@ -3833,7 +3884,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Unable to find network offering by id " + networkOfferingId); } - //network offering should be in Enabled state + // network offering should be in Enabled state if (networkOffering.getState() != NetworkOffering.State.Enabled) { throw new InvalidParameterValueException("Network offering " + networkOffering + " is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it"); } @@ -3842,7 +3893,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (network.isSpecifiedCidr() && networkOfferingIsConfiguredForExternalNetworking(networkOfferingId)) { throw new InvalidParameterValueException("Network offering " + networkOffering + " contained external network elements, can't be upgraded from a CIDR specify network!"); } - //check if the network is upgradable + // check if the network is upgradable if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) { throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNetworkOfferingId + " to " + networkOfferingId + "; check logs for more information"); } @@ -3852,10 +3903,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } Map newSvcProviders = new HashMap(); if (networkOfferingChanged) { - newSvcProviders = finalizeServicesAndProvidersForNetwork(_configMgr.getNetworkOffering(networkOfferingId), network.getPhysicalNetworkId()); + newSvcProviders = finalizeServicesAndProvidersForNetwork(_configMgr.getNetworkOffering(networkOfferingId), network.getPhysicalNetworkId()); } - //don't allow to modify network domain if the service is not supported + // don't allow to modify network domain if the service is not supported if (domainSuffix != null) { // validate network domain if (!NetUtils.verifyDomainName(domainSuffix)) { @@ -3876,78 +3927,79 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } network.setNetworkDomain(domainSuffix); - //have to restart the network + // have to restart the network restartNetwork = true; } ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); - //1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate states - Shutdown and Implementing + // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate +// states - Shutdown and Implementing boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated); - if (restartNetwork) { - if (validStateToShutdown) { - s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update"); + if (restartNetwork) { + if (validStateToShutdown) { + s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update"); if (!shutdownNetworkElementsAndResources(context, true, network)) { s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network); throw new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of network update: " + network); - } - } else { + } + } else { throw new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of network update: " + network + "; network is in wrong state: " + network.getState()); - } + } } - //2) Only after all the elements and rules are shutdown properly, update the network VO - //get updated network + // 2) Only after all the elements and rules are shutdown properly, update the network VO + // get updated network Network.State networkState = _networksDao.findById(networkId).getState(); - boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated); - if (restartNetwork && !validStateToImplement) { + boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated); + if (restartNetwork && !validStateToImplement) { throw new CloudRuntimeException("Failed to implement the network elements and resources as a part of network update: " + network + "; network is in wrong state: " + networkState); - } - + } + if (networkOfferingId != null) { - if(networkOfferingChanged){ - Transaction txn = Transaction.currentTxn(); + if (networkOfferingChanged) { + Transaction txn = Transaction.currentTxn(); txn.start(); - network.setNetworkOfferingId(networkOfferingId); - _networksDao.update(networkId, network, newSvcProviders); - //get all nics using this network - //log remove usage events for old offering - //log assign usage events for new offering + network.setNetworkOfferingId(networkOfferingId); + _networksDao.update(networkId, network, newSvcProviders); + // get all nics using this network + // log remove usage events for old offering + // log assign usage events for new offering List nics = _nicDao.listByNetworkId(networkId); - for(NicVO nic : nics){ - long vmId = nic.getInstanceId(); - VMInstanceVO vm = _vmDao.findById(vmId); - if(vm == null){ - s_logger.error("Vm for nic "+nic.getId()+" not found with Vm Id:"+vmId); - continue; - } + for (NicVO nic : nics) { + long vmId = nic.getInstanceId(); + VMInstanceVO vm = _vmDao.findById(vmId); + if (vm == null) { + s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId); + continue; + } long isDefault = (nic.isDefaultNic()) ? 1 : 0; UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), null, oldNetworkOfferingId, null, 0L); - _usageEventDao.persist(usageEvent); + _usageEventDao.persist(usageEvent); usageEvent = new UsageEventVO(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm.getHostName(), networkOfferingId, null, isDefault); _usageEventDao.persist(usageEvent); - } - txn.commit(); - } else { - network.setNetworkOfferingId(networkOfferingId); - _networksDao.update(networkId, network, finalizeServicesAndProvidersForNetwork(_configMgr.getNetworkOffering(networkOfferingId), network.getPhysicalNetworkId())); - } + } + txn.commit(); + } else { + network.setNetworkOfferingId(networkOfferingId); + _networksDao.update(networkId, network, finalizeServicesAndProvidersForNetwork(_configMgr.getNetworkOffering(networkOfferingId), network.getPhysicalNetworkId())); + } } else { - _networksDao.update(networkId, network); + _networksDao.update(networkId, network); } - //3) Implement the elements and rules again + // 3) Implement the elements and rules again if (restartNetwork) { - if (network.getState() != Network.State.Allocated) { - DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); - s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update"); + if (network.getState() != Network.State.Allocated) { + DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null); + s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update"); try { implementNetworkElementsAndResources(dest, context, network, _networkOfferingDao.findById(network.getNetworkOfferingId())); } catch (Exception ex) { s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex); throw new CloudRuntimeException("Failed to implement network " + network + " elements and resources as a part of network update"); } - } + } } return getNetwork(network.getId()); @@ -3962,17 +4014,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Network network = getNetwork(networkId); NetworkOffering ntwkOff = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); - // For default userVm Default network and domR guest/public network, get rate information from the service offering; for other situations get information + // For default userVm Default network and domR guest/public network, get rate information from the service +// offering; for other situations get information // from the network offering boolean isUserVmsDefaultNetwork = false; boolean isDomRGuestOrPublicNetwork = false; if (vm != null) { - Nic nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vmId); + Nic nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vmId); if (vm.getType() == Type.User && nic != null && nic.isDefaultNic()) { - isUserVmsDefaultNetwork = true; + isUserVmsDefaultNetwork = true; } else if (vm.getType() == Type.DomainRouter && ntwkOff != null && (ntwkOff.getTrafficType() == TrafficType.Public || ntwkOff.getTrafficType() == TrafficType.Guest)) { isDomRGuestOrPublicNetwork = true; - } + } } if (isUserVmsDefaultNetwork || isDomRGuestOrPublicNetwork) { return _configMgr.getServiceOfferingNetworkRate(vm.getServiceOfferingId()); @@ -4014,7 +4067,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Long[] array = allPossibleIps.toArray(new Long[allPossibleIps.size()]); if (requestedIp != null) { - //check that requested ip has the same cidr + // check that requested ip has the same cidr boolean isSameCidr = NetUtils.sameSubnetCIDR(requestedIp, NetUtils.long2Ip(array[0]), Integer.parseInt(cidr[1])); if (!isSameCidr) { s_logger.warn("Requested ip address " + requestedIp + " doesn't belong to the network " + network + " cidr"); @@ -4031,7 +4084,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return result; } - private String getZoneNetworkDomain(long zoneId) { return _dcDao.findById(zoneId).getDomain(); } @@ -4049,7 +4101,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String networkDomain = _accountDao.findById(accountId).getNetworkDomain(); if (networkDomain == null) { - //get domain level network domain + // get domain level network domain return getDomainNetworkDomain(_accountDao.findById(accountId).getDomainId(), zoneId); } @@ -4076,7 +4128,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag long startIPLong1 = NetUtils.ip2Long(startIP1); if (startIPLong1 < startIPLong) { - startIP = startIP1; + startIP = startIP1; } } @@ -4088,7 +4140,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Network network = _networksDao.findById(staticNats.get(0).getNetworkId()); boolean success = true; - if (staticNats == null || staticNats.size() == 0) { + if (staticNats == null || staticNats.size() == 0) { s_logger.debug("There are no static nat rules for the network elements"); return true; } @@ -4103,11 +4155,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - // static NAT rules can not programmed unless IP is associated with network service provider, so run IP association for + // static NAT rules can not programmed unless IP is associated with network service provider, so run IP +// association for // the network so as to ensure IP is associated before applying rules (in add state) applyIpAssociations(network, false, continueOnError, publicIps); - - //get provider + + // get provider String staticNatProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.StaticNat); for (NetworkElement ne : _networkElements) { @@ -4116,7 +4169,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag continue; } - boolean handled = ((StaticNatServiceProvider)ne).applyStaticNats(network, staticNats); + boolean handled = ((StaticNatServiceProvider) ne).applyStaticNats(network, staticNats); s_logger.debug("Static Nat for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); } catch (ResourceUnavailableException e) { if (!continueOnError) { @@ -4188,7 +4241,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public boolean isProviderSupportServiceInNetwork(long networkId, Service service, Provider provider){ + public boolean isProviderSupportServiceInNetwork(long networkId, Service service, Provider provider) { return _ntwkSrvcDao.canProviderSupportServiceInNetwork(networkId, service, provider); } @@ -4196,54 +4249,54 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkOffering oldNetworkOffering = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId); NetworkOffering newNetworkOffering = _networkOfferingDao.findById(newNetworkOfferingId); - //can upgrade only Isolated networks + // can upgrade only Isolated networks if (oldNetworkOffering.getGuestType() != GuestType.Isolated) { throw new InvalidParameterValueException("NetworkOfferingId can be upgraded only for the network of type " + GuestType.Isolated); } - //security group service should be the same + // security group service should be the same if (areServicesSupportedByNetworkOffering(oldNetworkOfferingId, Service.SecurityGroup) != areServicesSupportedByNetworkOffering(newNetworkOfferingId, Service.SecurityGroup)) { s_logger.debug("Offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different securityGroupProperty, can't upgrade"); return false; } - //Type of the network should be the same - if (oldNetworkOffering.getGuestType() != newNetworkOffering.getGuestType()){ - s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " are of different types, can't upgrade"); + // Type of the network should be the same + if (oldNetworkOffering.getGuestType() != newNetworkOffering.getGuestType()) { + s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " are of different types, can't upgrade"); return false; } - //tags should be the same + // tags should be the same if (newNetworkOffering.getTags() != null) { if (oldNetworkOffering.getTags() == null) { - s_logger.debug("New network offering id=" + newNetworkOfferingId + " has tags and old network offering id=" + oldNetworkOfferingId + " doesn't, can't upgrade"); + s_logger.debug("New network offering id=" + newNetworkOfferingId + " has tags and old network offering id=" + oldNetworkOfferingId + " doesn't, can't upgrade"); return false; } if (!oldNetworkOffering.getTags().equalsIgnoreCase(newNetworkOffering.getTags())) { - s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different tags, can't upgrade"); + s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different tags, can't upgrade"); return false; } } - //Traffic types should be the same + // Traffic types should be the same if (oldNetworkOffering.getTrafficType() != newNetworkOffering.getTrafficType()) { - s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different traffic types, can't upgrade"); + s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different traffic types, can't upgrade"); return false; } - - //specify vlan should be the same + + // specify vlan should be the same if (oldNetworkOffering.getSpecifyVlan() != newNetworkOffering.getSpecifyVlan()) { - s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different values for specifyVlan, can't upgrade"); + s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different values for specifyVlan, can't upgrade"); return false; } - - //specify ipRanges should be the same + + // specify ipRanges should be the same if (oldNetworkOffering.getSpecifyIpRanges() != newNetworkOffering.getSpecifyIpRanges()) { - s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different values for specifyIpRangess, can't upgrade"); + s_logger.debug("Network offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different values for specifyIpRangess, can't upgrade"); return false; } - - //Check all ips + + // Check all ips List userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null); List publicIps = new ArrayList(); if (userIps != null && !userIps.isEmpty()) { @@ -4257,13 +4310,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } } - + return canIpsUseOffering(publicIps, newNetworkOfferingId); } - protected boolean canUpgradeProviders(long oldNetworkOfferingId, long newNetworkOfferingId) { - //list of services and providers should be the same + // list of services and providers should be the same Map> newServices = getNetworkOfferingServiceProvidersMap(newNetworkOfferingId); Map> oldServices = getNetworkOfferingServiceProvidersMap(oldNetworkOfferingId); @@ -4274,22 +4326,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (Service service : oldServices.keySet()) { - //1)check that all old services are present in the new network offering + // 1)check that all old services are present in the new network offering if (!newServices.containsKey(service)) { s_logger.debug("New service offering doesn't have " + service + " service present in the old service offering, downgrade is not allowed"); return false; - } + } Set newProviders = newServices.get(service); Set oldProviders = oldServices.get(service); - //2) Can upgrade only from internal provider to external provider. Any other combinations are not allowed + // 2) Can upgrade only from internal provider to external provider. Any other combinations are not allowed for (Provider oldProvider : oldProviders) { if (newProviders.contains(oldProvider)) { s_logger.trace("New list of providers contains provider " + oldProvider); continue; } - //iterate through new providers and check that the old provider can upgrade + // iterate through new providers and check that the old provider can upgrade for (Provider newProvider : newProviders) { if (!(!oldProvider.isExternal() && newProvider.isExternal())) { s_logger.debug("Can't downgrade from network offering " + oldNetworkOfferingId + " to the new networkOffering " + newNetworkOfferingId); @@ -4305,8 +4357,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @DB @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true) public PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRangeStr, Long domainId, List tags, String name) { - - // Check if zone exists + + // Check if zone exists if (zoneId == null) { throw new InvalidParameterValueException("Please specify a valid zone."); } @@ -4315,16 +4367,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (zone == null) { throw new InvalidParameterValueException("Please specify a valid zone."); } - + if (Grouping.AllocationState.Enabled == zone.getAllocationState()) { throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId); } - + NetworkType zoneType = zone.getNetworkType(); - if(zoneType == NetworkType.Basic){ - if(!_physicalNetworkDao.listByZone(zoneId).isEmpty()){ - throw new CloudRuntimeException("Cannot add the physical network to basic zone id: "+zoneId+", there is a physical network already existing in this basic Zone"); + if (zoneType == NetworkType.Basic) { + if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) { + throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic Zone"); } } if (tags != null && tags.size() > 1) { @@ -4338,10 +4390,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag int vnetStart = 0; int vnetEnd = 0; if (vnetRange != null) { - //Verify zone type + // Verify zone type if (zoneType == NetworkType.Basic || (zoneType == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { - throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: "+ zone.isSecurityGroupEnabled()); + throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); } String[] tokens = vnetRange.split("-"); @@ -4369,19 +4421,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } catch (IllegalArgumentException ex) { throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}"); } - - //in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic + + // in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) { - throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only"); + throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only"); } else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) { - throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only"); + throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only"); } } - if(broadcastDomainRange == null){ - if(zoneType == NetworkType.Basic){ + if (broadcastDomainRange == null) { + if (zoneType == NetworkType.Basic) { broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.POD; - }else{ + } else { broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.ZONE; } } @@ -4400,11 +4452,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vnetRange != null) { _dcDao.addVnet(zone.getId(), pNetwork.getId(), vnetStart, vnetEnd); } - - //add VirtualRouter as the default network service provider + + // add VirtualRouter as the default network service provider addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId()); - - //add security group provider to the physical network + + // add security group provider to the physical network addDefaultSecurityGroupProviderToPhysicalNetwork(pNetwork.getId()); txn.commit(); @@ -4416,7 +4468,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name){ + public List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { Filter searchFilter = new Filter(PhysicalNetworkVO.class, "id", Boolean.TRUE, startIndex, pageSize); SearchCriteria sc = _physicalNetworkDao.createSearchCriteria(); @@ -4427,12 +4479,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (zoneId != null) { sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); } - + if (name != null) { - sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); + sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - - return _physicalNetworkDao.search(sc, searchFilter); + + return _physicalNetworkDao.search(sc, searchFilter); } @Override @@ -4451,14 +4503,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (zone == null) { throw new InvalidParameterValueException("Zone with id=" + network.getDataCenterId() + " doesn't exist in the system"); } - if(newVnetRangeString != null){ + if (newVnetRangeString != null) { if (zone.getNetworkType() == NetworkType.Basic || (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { - throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: "+ zone.isSecurityGroupEnabled()); + throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: " + + zone.isSecurityGroupEnabled()); } } - if (tags != null && tags.size() > 1) { throw new InvalidParameterException("Unable to support more than one tag on network yet"); } @@ -4472,7 +4524,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - if(state != null){ + if (state != null) { network.setState(networkState); } @@ -4480,13 +4532,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setTags(tags); } - if(networkSpeed != null){ + if (networkSpeed != null) { network.setSpeed(networkSpeed); } // Vnet range can be extended only boolean replaceVnet = false; - ArrayList> vnetsToAdd = new ArrayList>(2); + ArrayList> vnetsToAdd = new ArrayList>(2); if (newVnetRangeString != null) { Integer newStartVnet = 0; @@ -4515,14 +4567,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (newStartVnet > newEndVnet) { throw new InvalidParameterValueException("Vnet range has to be between 0-4096 and start range should be lesser than or equal to stop range"); - } + } if (physicalNetworkHasAllocatedVnets(network.getDataCenterId(), network.getId())) { String[] existingRange = network.getVnet().split("-"); int existingStartVnet = Integer.parseInt(existingRange[0]); int existingEndVnet = Integer.parseInt(existingRange[1]); - //check if vnet is being extended + // check if vnet is being extended if (!(newStartVnet.intValue() > existingStartVnet && newEndVnet.intValue() < existingEndVnet)) { throw new InvalidParameterValueException("Can't shrink existing vnet range as it the range has vnets allocated. Only extending existing vnet is supported"); } @@ -4545,16 +4597,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setVnet(newVnetRangeString); } - _physicalNetworkDao.update(id, network); if (replaceVnet) { - s_logger.debug("Deleting existing vnet range for the physicalNetwork id= "+id +" and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); + s_logger.debug("Deleting existing vnet range for the physicalNetwork id= " + id + " and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); _dcDao.deleteVnet(network.getId()); } for (Pair vnetToAdd : vnetsToAdd) { - s_logger.debug("Adding vnet range " + vnetToAdd.first() + "-" + vnetToAdd.second() + " for the physicalNetwork id= "+id +" and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); + s_logger.debug("Adding vnet range " + vnetToAdd.first() + "-" + vnetToAdd.second() + " for the physicalNetwork id= " + id + " and zone id=" + network.getDataCenterId() + + " as a part of updatePhysicalNetwork call"); _dcDao.addVnet(network.getDataCenterId(), network.getId(), vnetToAdd.first(), vnetToAdd.second()); } @@ -4578,7 +4630,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag checkIfPhysicalNetworkIsDeletable(physicalNetworkId); - // delete vlans for this zone List vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId); for (VlanVO vlan : vlans) { @@ -4593,19 +4644,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - //delete vnets + // delete vnets _dcDao.deleteVnet(physicalNetworkId); - //delete service providers + // delete service providers _pNSPDao.deleteProviders(physicalNetworkId); - - //delete traffic types + + // delete traffic types _pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId); - boolean success = _physicalNetworkDao.remove(physicalNetworkId); - return success; } @@ -4625,11 +4674,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networks.add(2, "there are networks associated to this physical network"); tablesToCheck.add(networks); - /*List privateIP = new ArrayList(); - privateIP.add(0, "op_dc_ip_address_alloc"); - privateIP.add(1, "data_center_id"); - privateIP.add(2, "there are private IP addresses allocated for this zone"); - tablesToCheck.add(privateIP);*/ + /* + * List privateIP = new ArrayList(); + * privateIP.add(0, "op_dc_ip_address_alloc"); + * privateIP.add(1, "data_center_id"); + * privateIP.add(2, "there are private IP addresses allocated for this zone"); + * tablesToCheck.add(privateIP); + */ List publicIP = new ArrayList(); publicIP.add(0, "user_ip_address"); @@ -4637,8 +4688,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag publicIP.add(2, "there are public IP addresses allocated for this physical network"); tablesToCheck.add(publicIP); - - for (List table : tablesToCheck) { String tableName = table.get(0); String column = table.get(1); @@ -4677,69 +4726,69 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - } + } @Override - public List listNetworkServices(String providerName){ + public List listNetworkServices(String providerName) { Provider provider = null; - if(providerName != null){ + if (providerName != null) { provider = Network.Provider.getProvider(providerName); - if(provider == null){ + if (provider == null) { throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName); } } - if(provider != null){ + if (provider != null) { NetworkElement element = getElementImplementingProvider(providerName); - if(element == null){ + if (element == null) { throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'"); } return new ArrayList(element.getCapabilities().keySet()); - }else{ + } else { return Service.listAllServices(); } } @Override - public List listSupportedNetworkServiceProviders(String serviceName){ + public List listSupportedNetworkServiceProviders(String serviceName) { Network.Service service = null; - if(serviceName != null){ + if (serviceName != null) { service = Network.Service.getService(serviceName); - if(service == null){ + if (service == null) { throw new InvalidParameterValueException("Invalid Network Service=" + serviceName); } } Set supportedProviders = new HashSet(); - if(service != null){ + if (service != null) { supportedProviders.addAll(s_serviceToImplementedProvidersMap.get(service)); - }else{ - for(List pList : s_serviceToImplementedProvidersMap.values()){ + } else { + for (List pList : s_serviceToImplementedProvidersMap.values()) { supportedProviders.addAll(pList); } } return new ArrayList(supportedProviders); } - + @Override public Provider getDefaultUniqueProviderForService(String serviceName) { - List providers = listSupportedNetworkServiceProviders(serviceName); - if (providers.isEmpty()) { - throw new CloudRuntimeException("No providers supporting service " + serviceName + " found in cloudStack"); - } - if (providers.size() > 1) { - throw new CloudRuntimeException("More than 1 provider supporting service " + serviceName + " found in cloudStack"); - } - - return providers.get(0); + List providers = listSupportedNetworkServiceProviders(serviceName); + if (providers.isEmpty()) { + throw new CloudRuntimeException("No providers supporting service " + serviceName + " found in cloudStack"); + } + if (providers.size() > 1) { + throw new CloudRuntimeException("More than 1 provider supporting service " + serviceName + " found in cloudStack"); + } + + return providers.get(0); } @Override @DB - @ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", create = true) + @ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", create = true) public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId, List enabledServices) { // verify input parameters @@ -4749,51 +4798,51 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // verify input parameters - if(destinationPhysicalNetworkId != null){ + if (destinationPhysicalNetworkId != null) { PhysicalNetworkVO destNetwork = _physicalNetworkDao.findById(destinationPhysicalNetworkId); if (destNetwork == null) { throw new InvalidParameterValueException("Destination Physical Network id=" + destinationPhysicalNetworkId + "doesn't exist in the system"); } } - if(providerName != null){ + if (providerName != null) { Provider provider = Network.Provider.getProvider(providerName); - if(provider == null){ + if (provider == null) { throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName); } } - - if(_pNSPDao.findByServiceProvider(physicalNetworkId, providerName) != null){ - throw new CloudRuntimeException("The '"+ providerName +"' provider already exists on physical network : "+physicalNetworkId); + + if (_pNSPDao.findByServiceProvider(physicalNetworkId, providerName) != null) { + throw new CloudRuntimeException("The '" + providerName + "' provider already exists on physical network : " + physicalNetworkId); } - //check if services can be turned off + // check if services can be turned off NetworkElement element = getElementImplementingProvider(providerName); - if(element == null){ + if (element == null) { throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'"); } List services = new ArrayList(); - if(enabledServices != null){ - if(!element.canEnableIndividualServices()){ - if(enabledServices.size() != element.getCapabilities().keySet().size()){ + if (enabledServices != null) { + if (!element.canEnableIndividualServices()) { + if (enabledServices.size() != element.getCapabilities().keySet().size()) { throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + providerName + "'"); } } - //validate Services + // validate Services boolean addGatewayService = false; - for(String serviceName : enabledServices){ + for (String serviceName : enabledServices) { Network.Service service = Network.Service.getService(serviceName); - if (service == null || service == Service.Gateway){ + if (service == null || service == Service.Gateway) { throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName); } else if (service == Service.SourceNat) { addGatewayService = true; } - //check if the service is provided by this Provider - if(!element.getCapabilities().containsKey(service)){ - throw new InvalidParameterValueException(providerName+" Provider cannot provide this Service specified=" + serviceName); + // check if the service is provided by this Provider + if (!element.getCapabilities().containsKey(service)) { + throw new InvalidParameterValueException(providerName + " Provider cannot provide this Service specified=" + serviceName); } services.add(service); } @@ -4801,9 +4850,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (addGatewayService) { services.add(Service.Gateway); } - }else{ - //enable all the default services supported by this element. - services = new ArrayList(element.getCapabilities().keySet()); + } else { + // enable all the default services supported by this element. + services = new ArrayList(element.getCapabilities().keySet()); } Transaction txn = Transaction.currentTxn(); @@ -4811,10 +4860,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.start(); // Create the new physical network in the database PhysicalNetworkServiceProviderVO nsp = new PhysicalNetworkServiceProviderVO(physicalNetworkId, providerName); - //set enabled services + // set enabled services nsp.setEnabledServices(services); - if(destinationPhysicalNetworkId != null){ + if (destinationPhysicalNetworkId != null) { nsp.setDestinationPhysicalNetworkId(destinationPhysicalNetworkId); } nsp = _pNSPDao.persist(nsp); @@ -4830,21 +4879,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { - + Filter searchFilter = new Filter(PhysicalNetworkServiceProviderVO.class, "id", false, startIndex, pageSize); SearchBuilder sb = _pNSPDao.createSearchBuilder(); SearchCriteria sc = sb.create(); - + if (physicalNetworkId != null) { sc.addAnd("physicalNetworkId", Op.EQ, physicalNetworkId); } - + if (name != null) { - sc.addAnd("providerName", Op.EQ, name); + sc.addAnd("providerName", Op.EQ, name); } - + if (state != null) { - sc.addAnd("state", Op.EQ, state); + sc.addAnd("state", Op.EQ, state); } return _pNSPDao.search(sc, searchFilter); @@ -4852,15 +4901,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_UPDATE, eventDescription = "Updating physical network ServiceProvider", async = true) - public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, String stateStr, List enabledServices){ + public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, String stateStr, List enabledServices) { PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); - if(provider == null){ + if (provider == null) { throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system"); } NetworkElement element = getElementImplementingProvider(provider.getProviderName()); - if(element == null){ + if (element == null) { throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'"); } @@ -4875,52 +4924,52 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean update = false; - if(state != null){ - if(state == PhysicalNetworkServiceProvider.State.Shutdown){ + if (state != null) { + if (state == PhysicalNetworkServiceProvider.State.Shutdown) { throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported"); } - if(s_logger.isDebugEnabled()){ - s_logger.debug("updating state of the service provider id=" + id + " on physical network: "+provider.getPhysicalNetworkId() + " to state: "+stateStr); + if (s_logger.isDebugEnabled()) { + s_logger.debug("updating state of the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId() + " to state: " + stateStr); } - switch(state) { + switch (state) { case Enabled: - if(element != null && element.isReady(provider)){ + if (element != null && element.isReady(provider)) { provider.setState(PhysicalNetworkServiceProvider.State.Enabled); update = true; - }else{ - throw new CloudRuntimeException("Provider is not ready, cannot Enable the provider, please configure the provider first"); + } else { + throw new CloudRuntimeException("Provider is not ready, cannot Enable the provider, please configure the provider first"); } break; case Disabled: - //do we need to do anything for the provider instances before disabling? + // do we need to do anything for the provider instances before disabling? provider.setState(PhysicalNetworkServiceProvider.State.Disabled); update = true; break; } } - if(enabledServices != null){ - //check if services can be turned of - if(!element.canEnableIndividualServices()){ + if (enabledServices != null) { + // check if services can be turned of + if (!element.canEnableIndividualServices()) { throw new InvalidParameterValueException("Cannot update set of Services for this Service Provider '" + provider.getProviderName() + "'"); } - //validate Services + // validate Services List services = new ArrayList(); - for(String serviceName : enabledServices){ + for (String serviceName : enabledServices) { Network.Service service = Network.Service.getService(serviceName); - if(service == null){ + if (service == null) { throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName); } services.add(service); } - //set enabled services + // set enabled services provider.setEnabledServices(services); update = true; } - if(update){ + if (update) { _pNSPDao.update(id, provider); } return provider; @@ -4931,29 +4980,29 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean deleteNetworkServiceProvider(Long id) throws ConcurrentOperationException, ResourceUnavailableException { PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); - if(provider == null){ + if (provider == null) { throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system"); } - //check if there are networks using this provider + // check if there are networks using this provider List networks = _networksDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), provider.getProviderName()); - if(networks != null && !networks.isEmpty()){ + if (networks != null && !networks.isEmpty()) { throw new CloudRuntimeException("Provider is not deletable because there are active networks using this provider, please upgrade these networks to new network offerings"); } User callerUser = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId()); - //shutdown the provider instances + // shutdown the provider instances ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); - if(s_logger.isDebugEnabled()){ - s_logger.debug("Shutting down the service provider id=" + id + " on physical network: "+provider.getPhysicalNetworkId()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Shutting down the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId()); } NetworkElement element = getElementImplementingProvider(provider.getProviderName()); - if(element == null){ + if (element == null) { throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'"); } - if(element != null && element.shutdownProviderInstances(provider, context)){ + if (element != null && element.shutdownProviderInstances(provider, context)) { provider.setState(PhysicalNetworkServiceProvider.State.Shutdown); } @@ -4961,7 +5010,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public PhysicalNetwork getPhysicalNetwork(Long physicalNetworkId){ + public PhysicalNetwork getPhysicalNetwork(Long physicalNetworkId) { return _physicalNetworkDao.findById(physicalNetworkId); } @@ -4982,7 +5031,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return getPhysicalNetworkServiceProvider(providerId); } - @Override public long findPhysicalNetworkId(long zoneId, String tag) { List pNtwks = _physicalNetworkDao.listByZone(zoneId); @@ -5033,7 +5081,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean securityGroupSupportedByOriginalOff = areServicesSupportedByNetworkOffering(originalOffering.getId(), Service.SecurityGroup); - //security group supported property should be the same + // security group supported property should be the same List offerings = _networkOfferingDao.getOfferingIdsToUpgradeFrom(originalOffering); @@ -5046,7 +5094,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return offeringsToReturn; } - private boolean cleanupNetworkResources(long networkId, Account caller, long callerUserId) { boolean success = true; Network network = getNetwork(networkId); @@ -5074,7 +5121,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Failed to cleanup LB rules as a part of network id=" + networkId + " cleanup"); } - //revoke all firewall rules for the network + // revoke all firewall rules for the network try { if (_firewallMgr.revokeAllFirewallRulesForNetwork(networkId, callerUserId, caller)) { s_logger.debug("Successfully cleaned up firewallRules rules for network id=" + networkId); @@ -5107,9 +5154,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return success; } - private boolean shutdownNetworkResources(long networkId, Account caller, long callerUserId) { - //This method cleans up network rules on the backend w/o touching them in the DB + // This method cleans up network rules on the backend w/o touching them in the DB boolean success = true; // Mark all PF rules as revoked and apply them on the backend (not in the DB) @@ -5172,7 +5218,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag lb.setState(FirewallRule.State.Revoke); List dstList = _lbMgr.getExistingDestinations(lb.getId()); List policyList = _lbMgr.getStickinessPolicies(lb.getId()); - //mark all destination with revoke state + // mark all destination with revoke state for (LbDestination dst : dstList) { s_logger.trace("Marking lb destination " + dst + " with Revoke state"); dst.setRevoked(true); @@ -5192,7 +5238,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag success = false; } - //revoke all firewall rules for the network w/o applying them on the DB + // revoke all firewall rules for the network w/o applying them on the DB List firewallRules = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.Firewall); if (s_logger.isDebugEnabled()) { s_logger.debug("Releasing " + firewallRules.size() + " firewall rules for network id=" + networkId + " as a part of shutdownNetworkRules"); @@ -5219,7 +5265,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List publicIpsToRelease = new ArrayList(); if (userIps != null && !userIps.isEmpty()) { for (IPAddressVO userIp : userIps) { - userIp.setState(State.Releasing); + userIp.setState(State.Releasing); PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(userIp.getMacAddress())); publicIpsToRelease.add(publicIp); } @@ -5239,14 +5285,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public boolean isSecurityGroupSupportedInNetwork(Network network) { - if (network.getTrafficType() != TrafficType.Guest) { - s_logger.trace("Security group can be enabled for Guest networks only; and network " + network + " has a diff traffic type"); - return false; - } - + if (network.getTrafficType() != TrafficType.Guest) { + s_logger.trace("Security group can be enabled for Guest networks only; and network " + network + " has a diff traffic type"); + return false; + } + Long physicalNetworkId = network.getPhysicalNetworkId(); - //physical network id can be null in Guest Network in Basic zone, so locate the physical network + // physical network id can be null in Guest Network in Basic zone, so locate the physical network if (physicalNetworkId == null) { physicalNetworkId = findPhysicalNetworkId(network.getDataCenterId(), null); } @@ -5256,7 +5302,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB - @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", create = true) + @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", create = true) public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficTypeStr, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan) { // verify input parameters @@ -5265,7 +5311,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system"); } - Networks.TrafficType trafficType = null; if (trafficTypeStr != null && !trafficTypeStr.isEmpty()) { try { @@ -5275,35 +5320,39 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - if(_pNTrafficTypeDao.isTrafficTypeSupported(physicalNetworkId, trafficType)){ - throw new CloudRuntimeException("This physical network already supports the traffic type: "+trafficType); + if (_pNTrafficTypeDao.isTrafficTypeSupported(physicalNetworkId, trafficType)) { + throw new CloudRuntimeException("This physical network already supports the traffic type: " + trafficType); } - //For Storage, Control, Management, Public check if the zone has any other physical network with this traffictype already present - //If yes, we cant add these traffics to one more physical network in the zone. + // For Storage, Control, Management, Public check if the zone has any other physical network with this +// traffictype already present + // If yes, we cant add these traffics to one more physical network in the zone. - if(TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType) || TrafficType.Storage.equals(trafficType)){ - if(!_physicalNetworkDao.listByZoneAndTrafficType(network.getDataCenterId(), trafficType).isEmpty()){ - throw new CloudRuntimeException("Fail to add the traffic type to physical network because Zone already has a physical network with this traffic type: "+trafficType); + if (TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType) || TrafficType.Storage.equals(trafficType)) { + if (!_physicalNetworkDao.listByZoneAndTrafficType(network.getDataCenterId(), trafficType).isEmpty()) { + throw new CloudRuntimeException("Fail to add the traffic type to physical network because Zone already has a physical network with this traffic type: " + trafficType); } } - + if (TrafficType.Storage.equals(trafficType)) { - List ssvms = _stnwMgr.getSSVMWithNoStorageNetwork(network.getDataCenterId()); - if (!ssvms.isEmpty()) { - StringBuilder sb = new StringBuilder("Cannot add " + trafficType + " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)"); - sb.append("SSVMs:"); - for (SecondaryStorageVmVO ssvm : ssvms) { - sb.append(ssvm.getInstanceName()).append(":").append(ssvm.getState()); - } - throw new CloudRuntimeException(sb.toString()); - } + List ssvms = _stnwMgr.getSSVMWithNoStorageNetwork(network.getDataCenterId()); + if (!ssvms.isEmpty()) { + StringBuilder sb = new StringBuilder( + "Cannot add " + + trafficType + + " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)"); + sb.append("SSVMs:"); + for (SecondaryStorageVmVO ssvm : ssvms) { + sb.append(ssvm.getInstanceName()).append(":").append(ssvm.getState()); + } + throw new CloudRuntimeException(sb.toString()); + } } Transaction txn = Transaction.currentTxn(); try { txn.start(); // Create the new traffic type in the database - if(xenLabel == null){ + if (xenLabel == null) { xenLabel = getDefaultXenNetworkLabel(trafficType); } PhysicalNetworkTrafficTypeVO pNetworktrafficType = new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vmwareLabel, simulatorLabel, vlan); @@ -5318,26 +5367,31 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } - private String getDefaultXenNetworkLabel(TrafficType trafficType){ + private String getDefaultXenNetworkLabel(TrafficType trafficType) { String xenLabel = null; - switch(trafficType){ - case Public: xenLabel = _configDao.getValue(Config.XenPublicNetwork.key()); + switch (trafficType) { + case Public: + xenLabel = _configDao.getValue(Config.XenPublicNetwork.key()); break; - case Guest: xenLabel = _configDao.getValue(Config.XenGuestNetwork.key()); + case Guest: + xenLabel = _configDao.getValue(Config.XenGuestNetwork.key()); break; - case Storage: xenLabel = _configDao.getValue(Config.XenStorageNetwork1.key()); + case Storage: + xenLabel = _configDao.getValue(Config.XenStorageNetwork1.key()); break; - case Management: xenLabel = _configDao.getValue(Config.XenPrivateNetwork.key()); + case Management: + xenLabel = _configDao.getValue(Config.XenPrivateNetwork.key()); break; - case Control: xenLabel = "cloud_link_local_network"; + case Control: + xenLabel = "cloud_link_local_network"; break; } return xenLabel; } @Override - @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", async = true) - public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id){ + @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", async = true) + public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id) { return _pNTrafficTypeDao.findById(id); } @@ -5347,17 +5401,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); - if(trafficType == null){ + if (trafficType == null) { throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system"); } - if(xenLabel != null){ + if (xenLabel != null) { trafficType.setXenNetworkLabel(xenLabel); } - if(kvmLabel != null){ + if (kvmLabel != null) { trafficType.setKvmNetworkLabel(kvmLabel); } - if(vmwareLabel != null){ + if (vmwareLabel != null) { trafficType.setVmwareNetworkLabel(vmwareLabel); } _pNTrafficTypeDao.update(id, trafficType); @@ -5370,20 +5424,20 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean deletePhysicalNetworkTrafficType(Long id) { PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); - if(trafficType == null){ + if (trafficType == null) { throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system"); } - //check if there are any networks associated to this physical network with this traffic type - if(TrafficType.Guest.equals(trafficType.getTrafficType())){ - if(!_networksDao.listByPhysicalNetworkTrafficType(trafficType.getPhysicalNetworkId(), trafficType.getTrafficType()).isEmpty()){ - throw new CloudRuntimeException("The Traffic Type is not deletable because there are existing networks with this traffic type:"+trafficType.getTrafficType()); + // check if there are any networks associated to this physical network with this traffic type + if (TrafficType.Guest.equals(trafficType.getTrafficType())) { + if (!_networksDao.listByPhysicalNetworkTrafficType(trafficType.getPhysicalNetworkId(), trafficType.getTrafficType()).isEmpty()) { + throw new CloudRuntimeException("The Traffic Type is not deletable because there are existing networks with this traffic type:" + trafficType.getTrafficType()); } } else if (TrafficType.Storage.equals(trafficType.getTrafficType())) { - PhysicalNetworkVO pn = _physicalNetworkDao.findById(trafficType.getPhysicalNetworkId()); - if (_stnwMgr.isAnyStorageIpInUseInZone(pn.getDataCenterId())) { - throw new CloudRuntimeException("The Traffic Type is not deletable because there are still some storage network ip addresses in use:"+trafficType.getTrafficType()); - } + PhysicalNetworkVO pn = _physicalNetworkDao.findById(trafficType.getPhysicalNetworkId()); + if (_stnwMgr.isAnyStorageIpInUseInZone(pn.getDataCenterId())) { + throw new CloudRuntimeException("The Traffic Type is not deletable because there are still some storage network ip addresses in use:" + trafficType.getTrafficType()); + } } return _pNTrafficTypeDao.remove(id); } @@ -5398,18 +5452,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _pNTrafficTypeDao.listBy(physicalNetworkId); } - @Override public PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType) { List networkList = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType); if (networkList.isEmpty()) { - throw new InvalidParameterValueException("Unable to find the default physical network with traffic=" + trafficType +" in zone id=" + zoneId); + throw new InvalidParameterValueException("Unable to find the default physical network with traffic=" + trafficType + " in zone id=" + zoneId); } if (networkList.size() > 1) { - throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " with traffic type="+trafficType); + throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " with traffic type=" + trafficType); } return networkList.get(0); @@ -5429,40 +5482,40 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) { return null; } - + @Override public List getPhysicalNetworkInfo(long dcId, HypervisorType hypervisorType) { - List networkInfoList = new ArrayList(); - List physicalNtwkList = _physicalNetworkDao.listByZone(dcId); - for(PhysicalNetworkVO pNtwk : physicalNtwkList){ - String publicName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Public, hypervisorType); - String privateName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Management, hypervisorType); - String guestName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Guest, hypervisorType); - String storageName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Storage, hypervisorType); - //String controlName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Control, hypervisorType); - PhysicalNetworkSetupInfo info = new PhysicalNetworkSetupInfo(); - info.setPhysicalNetworkId(pNtwk.getId()); - info.setGuestNetworkName(guestName); - info.setPrivateNetworkName(privateName); - info.setPublicNetworkName(publicName); - info.setStorageNetworkName(storageName); - PhysicalNetworkTrafficTypeVO mgmtTraffic = _pNTrafficTypeDao.findBy(pNtwk.getId(), TrafficType.Management); - if(mgmtTraffic != null){ - String vlan = mgmtTraffic.getVlan(); - info.setMgmtVlan(vlan); - } - networkInfoList.add(info); - } - return networkInfoList; + List networkInfoList = new ArrayList(); + List physicalNtwkList = _physicalNetworkDao.listByZone(dcId); + for (PhysicalNetworkVO pNtwk : physicalNtwkList) { + String publicName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Public, hypervisorType); + String privateName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Management, hypervisorType); + String guestName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Guest, hypervisorType); + String storageName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Storage, hypervisorType); + // String controlName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Control, hypervisorType); + PhysicalNetworkSetupInfo info = new PhysicalNetworkSetupInfo(); + info.setPhysicalNetworkId(pNtwk.getId()); + info.setGuestNetworkName(guestName); + info.setPrivateNetworkName(privateName); + info.setPublicNetworkName(publicName); + info.setStorageNetworkName(storageName); + PhysicalNetworkTrafficTypeVO mgmtTraffic = _pNTrafficTypeDao.findBy(pNtwk.getId(), TrafficType.Management); + if (mgmtTraffic != null) { + String vlan = mgmtTraffic.getVlan(); + info.setMgmtVlan(vlan); + } + networkInfoList.add(info); + } + return networkInfoList; } @Override public void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) throws ConnectionException { - if (!(cmd instanceof StartupRoutingCommand )) { + if (!(cmd instanceof StartupRoutingCommand)) { return; - } + } long hostId = host.getId(); - StartupRoutingCommand startup = (StartupRoutingCommand)cmd; + StartupRoutingCommand startup = (StartupRoutingCommand) cmd; String dataCenter = startup.getDataCenter(); @@ -5479,22 +5532,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new IllegalArgumentException("Host " + startup.getPrivateIpAddress() + " sent incorrect data center: " + dataCenter); } dcId = dc.getId(); - HypervisorType hypervisorType = startup.getHypervisorType(); + HypervisorType hypervisorType = startup.getHypervisorType(); - if(s_logger.isDebugEnabled()){ - s_logger.debug("Host's hypervisorType is: "+hypervisorType); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Host's hypervisorType is: " + hypervisorType); } - + List networkInfoList = new ArrayList(); - //list all physicalnetworks in the zone & for each get the network names + // list all physicalnetworks in the zone & for each get the network names List physicalNtwkList = _physicalNetworkDao.listByZone(dcId); - for(PhysicalNetworkVO pNtwk : physicalNtwkList){ + for (PhysicalNetworkVO pNtwk : physicalNtwkList) { String publicName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Public, hypervisorType); String privateName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Management, hypervisorType); String guestName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Guest, hypervisorType); String storageName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Storage, hypervisorType); - //String controlName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Control, hypervisorType); + // String controlName = _pNTrafficTypeDao.getNetworkTag(pNtwk.getId(), TrafficType.Control, hypervisorType); PhysicalNetworkSetupInfo info = new PhysicalNetworkSetupInfo(); info.setPhysicalNetworkId(pNtwk.getId()); info.setGuestNetworkName(guestName); @@ -5502,15 +5555,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag info.setPublicNetworkName(publicName); info.setStorageNetworkName(storageName); PhysicalNetworkTrafficTypeVO mgmtTraffic = _pNTrafficTypeDao.findBy(pNtwk.getId(), TrafficType.Management); - if(mgmtTraffic != null){ + if (mgmtTraffic != null) { String vlan = mgmtTraffic.getVlan(); info.setMgmtVlan(vlan); } networkInfoList.add(info); } - //send the names to the agent - if(s_logger.isDebugEnabled()){ + // send the names to the agent + if (s_logger.isDebugEnabled()) { s_logger.debug("Sending CheckNetworkCommand to check the Network is setup correctly on Agent"); } CheckNetworkCommand nwCmd = new CheckNetworkCommand(networkInfoList); @@ -5518,20 +5571,20 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag CheckNetworkAnswer answer = (CheckNetworkAnswer) _agentMgr.easySend(hostId, nwCmd); if (answer == null) { - s_logger.warn("Unable to get an answer to the CheckNetworkCommand from agent:" +host.getId()); - throw new ConnectionException(true, "Unable to get an answer to the CheckNetworkCommand from agent: "+host.getId()); + s_logger.warn("Unable to get an answer to the CheckNetworkCommand from agent:" + host.getId()); + throw new ConnectionException(true, "Unable to get an answer to the CheckNetworkCommand from agent: " + host.getId()); } if (!answer.getResult()) { - s_logger.warn("Unable to setup agent " + hostId + " due to " + ((answer != null)?answer.getDetails():"return null")); + s_logger.warn("Unable to setup agent " + hostId + " due to " + ((answer != null) ? answer.getDetails() : "return null")); String msg = "Incorrect Network setup on agent, Reinitialize agent after network names are setup, details : " + answer.getDetails(); _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, host.getPodId(), msg, msg); throw new ConnectionException(true, msg); - }else{ - if ( answer.needReconnect() ) { + } else { + if (answer.needReconnect()) { throw new ConnectionException(false, "Reinitialize agent after network setup."); } - if(s_logger.isDebugEnabled()){ + if (s_logger.isDebugEnabled()) { s_logger.debug("Network setup is correct on Agent"); } return; @@ -5556,16 +5609,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public boolean processTimeout(long agentId, long seq) { return false; - } + } private boolean isProviderEnabled(PhysicalNetworkServiceProvider provider) { - if (provider == null || provider.getState() != PhysicalNetworkServiceProvider.State.Enabled) { //TODO: check for other states: Shutdown? + if (provider == null || provider.getState() != PhysicalNetworkServiceProvider.State.Enabled) { // TODO: check +// for other states: Shutdown? return false; } return true; } - @Override + @Override public boolean isProviderEnabledInPhysicalNetwork(long physicalNetowrkId, String providerName) { PhysicalNetworkServiceProviderVO ntwkSvcProvider = _pNSPDao.findByServiceProvider(physicalNetowrkId, providerName); if (ntwkSvcProvider == null) { @@ -5576,13 +5630,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } private boolean isServiceEnabledInNetwork(long physicalNetworkId, long networkId, Service service) { - //check if the service is supported in the network + // check if the service is supported in the network if (!areServicesSupportedInNetwork(networkId, service)) { s_logger.debug("Service " + service.getName() + " is not supported in the network id=" + networkId); return false; } - //get provider for the service and check if all of them are supported + // get provider for the service and check if all of them are supported String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(networkId, service); if (!isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) { s_logger.debug("Provider " + provider + " is not enabled in physical network id=" + physicalNetworkId); @@ -5592,21 +5646,20 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return true; } - @Override public String getNetworkTag(HypervisorType hType, Network network) { - //no network tag for control traffic type - if (network.getTrafficType() == TrafficType.Control) { - return null; - } - - Long physicalNetworkId = null; - if (network.getTrafficType() != TrafficType.Guest) { - physicalNetworkId = getNonGuestNetworkPhysicalNetworkId(network); - } else { - NetworkOffering offering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); - physicalNetworkId = findPhysicalNetworkId(network.getDataCenterId(), offering.getTags()); - } + // no network tag for control traffic type + if (network.getTrafficType() == TrafficType.Control) { + return null; + } + + Long physicalNetworkId = null; + if (network.getTrafficType() != TrafficType.Guest) { + physicalNetworkId = getNonGuestNetworkPhysicalNetworkId(network); + } else { + NetworkOffering offering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); + physicalNetworkId = findPhysicalNetworkId(network.getDataCenterId(), offering.getTags()); + } if (physicalNetworkId == null) { assert (false) : "Can't get the physical network"; @@ -5617,12 +5670,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _pNTrafficTypeDao.getNetworkTag(physicalNetworkId, network.getTrafficType(), hType); } - protected Long getNonGuestNetworkPhysicalNetworkId(Network network) { - //no physical network for control traffic type - if (network.getTrafficType() == TrafficType.Control) { - return null; - } - + protected Long getNonGuestNetworkPhysicalNetworkId(Network network) { + // no physical network for control traffic type + if (network.getTrafficType() == TrafficType.Control) { + return null; + } + Long physicalNetworkId = network.getPhysicalNetworkId(); if (physicalNetworkId == null) { @@ -5630,8 +5683,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (pNtwks.size() == 1) { physicalNetworkId = pNtwks.get(0).getId(); } else { - //locate physicalNetwork with supported traffic type - //We can make this assumptions based on the fact that Public/Management/Control traffic types are supported only in one physical network in the zone in 3.0 + // locate physicalNetwork with supported traffic type + // We can make this assumptions based on the fact that Public/Management/Control traffic types are +// supported only in one physical network in the zone in 3.0 for (PhysicalNetworkVO pNtwk : pNtwks) { if (_pNTrafficTypeDao.isTrafficTypeSupported(pNtwk.getId(), network.getTrafficType())) { physicalNetworkId = pNtwk.getId(); @@ -5640,9 +5694,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - return physicalNetworkId; - } - + return physicalNetworkId; + } @Override public NetworkVO getExclusiveGuestNetwork(long zoneId) { @@ -5663,9 +5716,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public PhysicalNetworkServiceProvider addDefaultVirtualRouterToPhysicalNetwork(long physicalNetworkId) { PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VirtualRouter.getName(), null, null); - //add instance of the provider - VirtualRouterElement element = (VirtualRouterElement)getElementImplementingProvider(Network.Provider.VirtualRouter.getName()); - if(element == null){ + // add instance of the provider + VirtualRouterElement element = (VirtualRouterElement) getElementImplementingProvider(Network.Provider.VirtualRouter.getName()); + if (element == null) { throw new CloudRuntimeException("Unable to find the Network Element implementing the VirtualRouter Provider"); } element.addElement(nsp.getId()); @@ -5677,7 +5730,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public PhysicalNetworkServiceProvider addDefaultSecurityGroupProviderToPhysicalNetwork(long physicalNetworkId) { PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.SecurityGroupProvider.getName(), null, null); - + return nsp; } @@ -5700,32 +5753,33 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NetworkOfferingServiceMapVO serviceMap : servicesMap) { if (svcProviders.containsKey(serviceMap.getService())) { - //FIXME - right now we pick up the first provider from the list, need to add more logic based on provider load, etc + // FIXME - right now we pick up the first provider from the list, need to add more logic based on +// provider load, etc continue; } String service = serviceMap.getService(); String provider = serviceMap.getProvider(); - + if (provider == null) { - provider = getDefaultUniqueProviderForService(service).getName(); + provider = getDefaultUniqueProviderForService(service).getName(); } - //check that provider is supported + // check that provider is supported if (checkPhysicalNetwork) { if (!_pNSPDao.isServiceProviderEnabled(physicalNetworkId, provider, service)) { throw new UnsupportedServiceException("Provider " + provider + " is either not enabled or doesn't support service " + service + " in physical network id=" + physicalNetworkId); } } - svcProviders.put(service, provider); + svcProviders.put(service, provider); List l = providerSvcs.get(provider); if (l == null) { providerSvcs.put(provider, l = new ArrayList()); } l.add(service); } - + for (String provider : providerSvcs.keySet()) { NetworkElement element = getElementImplementingProvider(provider); List services = providerSvcs.get(provider); @@ -5733,16 +5787,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new UnsupportedServiceException("Provider " + provider + " doesn't support services combination: " + services); } } - + return svcProviders; } @Override public Long getPhysicalNetworkId(Network network) { - if (network.getTrafficType() != TrafficType.Guest) { - return getNonGuestNetworkPhysicalNetworkId(network); - } - + if (network.getTrafficType() != TrafficType.Guest) { + return getNonGuestNetworkPhysicalNetworkId(network); + } + Long physicalNetworkId = network.getPhysicalNetworkId(); NetworkOffering offering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); if (physicalNetworkId == null) { @@ -5768,73 +5822,74 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public boolean isProviderForNetwork(Provider provider, long networkId) { - if (_ntwkSrvcDao.isProviderForNetwork(networkId, provider) != null) { - return true; - } else { - return false; - } + if (_ntwkSrvcDao.isProviderForNetwork(networkId, provider) != null) { + return true; + } else { + return false; + } } - + @Override public boolean isProviderForNetworkOffering(Provider provider, long networkOfferingId) { - if (_ntwkOfferingSrvcDao.isProviderForNetworkOffering(networkOfferingId, provider)) { - return true; - } else { - return false; - } + if (_ntwkOfferingSrvcDao.isProviderForNetworkOffering(networkOfferingId, provider)) { + return true; + } else { + return false; + } } - + @Override - public void canProviderSupportServices(Map> providersMap) { - for (Provider provider : providersMap.keySet()) { - //check if services can be turned off + public void canProviderSupportServices(Map> providersMap) { + for (Provider provider : providersMap.keySet()) { + // check if services can be turned off NetworkElement element = getElementImplementingProvider(provider.getName()); - if(element == null){ + if (element == null) { throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); } - + Set enabledServices = providersMap.get(provider); - if(enabledServices != null && !enabledServices.isEmpty()){ - if(!element.canEnableIndividualServices()){ - Set requiredServices = element.getCapabilities().keySet(); - if (requiredServices.contains(Network.Service.Gateway)) { - requiredServices.remove(Network.Service.Gateway); - } - - //Remove firewall from the list of services-to-compare - if (requiredServices.contains(Network.Service.Firewall)) { - requiredServices.remove(Network.Service.Firewall); - } - - if (enabledServices.contains(Network.Service.Firewall)) { - enabledServices.remove(Network.Service.Firewall); - } - - //exclude gateway service - if(enabledServices.size() != requiredServices.size()){ - StringBuilder servicesSet = new StringBuilder(); - - for (Service requiredService: requiredServices) { - //skip gateway service as we don't allow setting it via API - if (requiredService == Service.Gateway) { - continue; - } - servicesSet.append(requiredService.getName() + ", "); - } - servicesSet.delete(servicesSet.toString().length() -2, servicesSet.toString().length()); - - throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services: " + servicesSet.toString() + " for Service Provider " + provider.getName()); + if (enabledServices != null && !enabledServices.isEmpty()) { + if (!element.canEnableIndividualServices()) { + Set requiredServices = element.getCapabilities().keySet(); + if (requiredServices.contains(Network.Service.Gateway)) { + requiredServices.remove(Network.Service.Gateway); + } + + // Remove firewall from the list of services-to-compare + if (requiredServices.contains(Network.Service.Firewall)) { + requiredServices.remove(Network.Service.Firewall); + } + + if (enabledServices.contains(Network.Service.Firewall)) { + enabledServices.remove(Network.Service.Firewall); + } + + // exclude gateway service + if (enabledServices.size() != requiredServices.size()) { + StringBuilder servicesSet = new StringBuilder(); + + for (Service requiredService : requiredServices) { + // skip gateway service as we don't allow setting it via API + if (requiredService == Service.Gateway) { + continue; + } + servicesSet.append(requiredService.getName() + ", "); + } + servicesSet.delete(servicesSet.toString().length() - 2, servicesSet.toString().length()); + + throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services: " + servicesSet.toString() + " for Service Provider " + + provider.getName()); } } - for(Service service : enabledServices){ - //check if the service is provided by this Provider - if(!element.getCapabilities().containsKey(service)){ + for (Service service : enabledServices) { + // check if the service is provided by this Provider + if (!element.getCapabilities().containsKey(service)) { throw new UnsupportedServiceException(provider.getName() + " Provider cannot provide service " + service.getName()); } } - } - } + } + } } @Override @@ -5842,36 +5897,36 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String defaultAdding = _configDao.getValue(Config.SecurityGroupDefaultAdding.key()); return (defaultAdding != null && defaultAdding.equalsIgnoreCase("true")); } - + @Override public List listNetworkOfferingServices(long networkOfferingId) { - List services = new ArrayList(); - List servicesStr = _ntwkOfferingSrvcDao.listServicesForNetworkOffering(networkOfferingId); - for (String serviceStr : servicesStr) { - services.add(Service.getService(serviceStr)); - } - - return services; + List services = new ArrayList(); + List servicesStr = _ntwkOfferingSrvcDao.listServicesForNetworkOffering(networkOfferingId); + for (String serviceStr : servicesStr) { + services.add(Service.getService(serviceStr)); + } + + return services; } - + @Override public boolean areServicesEnabledInZone(long zoneId, long networkOfferingId, String tags, List services) { - long physicalNtwkId = findPhysicalNetworkId(zoneId, tags); - boolean result = true; - List checkedProvider = new ArrayList(); - for (Service service : services) { - //get all the providers, and check if each provider is enabled - List providerNames = _ntwkOfferingSrvcDao.listProvidersForServiceForNetworkOffering(networkOfferingId, service); - for (String providerName : providerNames) { - if (!checkedProvider.contains(providerName)) { - result = result && isProviderEnabledInPhysicalNetwork(physicalNtwkId, providerName); - } - } - } - - return result; + long physicalNtwkId = findPhysicalNetworkId(zoneId, tags); + boolean result = true; + List checkedProvider = new ArrayList(); + for (Service service : services) { + // get all the providers, and check if each provider is enabled + List providerNames = _ntwkOfferingSrvcDao.listProvidersForServiceForNetworkOffering(networkOfferingId, service); + for (String providerName : providerNames) { + if (!checkedProvider.contains(providerName)) { + result = result && isProviderEnabledInPhysicalNetwork(physicalNtwkId, providerName); + } + } + } + + return result; } - + @Override public boolean checkIpForService(IPAddressVO userIp, Service service) { Long networkId = userIp.getAssociatedWithNetworkId(); @@ -5889,138 +5944,140 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return true; } - - @Override - public List> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd) { - String type = cmd.getTrafficType(); - List> results = new ArrayList>(); - if (type != null) { - for (NetworkGuru guru : _networkGurus) { - if (guru.isMyTrafficType(TrafficType.getTrafficType(type))) { - results.add(new Pair(TrafficType.getTrafficType(type), guru.getName())); - break; - } - } - } else { - for (NetworkGuru guru : _networkGurus) { - TrafficType[] allTypes = guru.getSupportedTrafficType(); - for (TrafficType t : allTypes) { - results.add(new Pair(t, guru.getName())); - } - } - } - - return results; - } - - @Override - public void checkCapabilityForProvider(Set providers, Service service, Capability cap, String capValue) { - for (Provider provider : providers) { - NetworkElement element = getElementImplementingProvider(provider.getName()); - if(element != null){ - Map> elementCapabilities = element.getCapabilities(); - if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { - throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider.getName()); - } - Map serviceCapabilities = elementCapabilities.get(service); - if (serviceCapabilities == null || serviceCapabilities.isEmpty()) { - throw new UnsupportedServiceException("Service " + service.getName() + " doesn't have capabilites for element=" + element.getName() + " implementing Provider=" + provider.getName()); - } - String value = serviceCapabilities.get(cap); - if (value == null || value.isEmpty()) { - throw new UnsupportedServiceException("Service " + service.getName() + " doesn't have capability " + cap.getName() + " for element=" + element.getName() + " implementing Provider=" + provider.getName()); - } + @Override + public List> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd) { + String type = cmd.getTrafficType(); + List> results = new ArrayList>(); + if (type != null) { + for (NetworkGuru guru : _networkGurus) { + if (guru.isMyTrafficType(TrafficType.getTrafficType(type))) { + results.add(new Pair(TrafficType.getTrafficType(type), guru.getName())); + break; + } + } + } else { + for (NetworkGuru guru : _networkGurus) { + TrafficType[] allTypes = guru.getSupportedTrafficType(); + for (TrafficType t : allTypes) { + results.add(new Pair(t, guru.getName())); + } + } + } - capValue = capValue.toLowerCase(); - - if (!value.contains(capValue)) { - throw new UnsupportedServiceException("Service " + service.getName() + " doesn't support value " + capValue + " for capability " + cap.getName() + " for element=" + element.getName() + " implementing Provider=" + provider.getName()); - } - } else { - throw new UnsupportedServiceException("Unable to find network element for provider " + provider.getName()); - } - } - } - - public IpAddress assignElasticIp(long networkId, Account owner, boolean forElasticLb, boolean forElasticIp) throws InsufficientAddressCapacityException{ - Network guestNetwork = getNetwork(networkId); - NetworkOffering off = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); - IpAddress ip = null; - if ((off.getElasticLb() && forElasticLb) || (off.getElasticIp() && forElasticIp)) { - - try { - s_logger.debug("Allocating elastic IP address for load balancer rule..."); - //allocate ip - ip = allocateIP(networkId, owner, true); - //apply ip associations - ip = associateIP(ip.getId()); - } catch (ResourceAllocationException ex) { - throw new CloudRuntimeException("Failed to allocate elastic ip due to ", ex); - } catch (ConcurrentOperationException ex) { - throw new CloudRuntimeException("Failed to allocate elastic lb ip due to ", ex); - } catch (ResourceUnavailableException ex) { - throw new CloudRuntimeException("Failed to allocate elastic lb ip due to ", ex); - } - - if (ip == null) { - throw new CloudRuntimeException("Failed to allocate elastic ip"); - } - } - - return ip; - } - - @Override - public boolean handleElasticIpRelease(IpAddress ip) { - boolean success = true; - Long networkId = ip.getAssociatedWithNetworkId(); - if (networkId != null) { - if (ip.getElastic()) { - UserContext ctx = UserContext.current(); - if (!releasePublicIpAddress(ip.getId(), ctx.getCallerUserId(), ctx.getCaller())) { - s_logger.warn("Unable to release elastic ip address id=" + ip.getId()); - success = false; - } else { - s_logger.warn("Successfully released elastic ip address id=" + ip.getId()); - } - } - } - return success; - } - - @Override - public void checkNetworkPermissions(Account owner, Network network) { - // Perform account permission check - if (network.getGuestType() != Network.GuestType.Shared) { - List networkMap = _networksDao.listBy(owner.getId(), network.getId()); - if (networkMap == null || networkMap.isEmpty()) { - throw new PermissionDeniedException("Unable to use network with id= " + network.getId() + ", permission denied"); - } - } else { - if (!isNetworkAvailableInDomain(network.getId(), owner.getDomainId())) { - throw new PermissionDeniedException("Shared network id=" + network.getId() + " is not available in domain id=" + owner.getDomainId()); - } - } - } - - public void allocateDirectIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network, String requestedIp) throws InsufficientVirtualNetworkCapcityException, - InsufficientAddressCapacityException { - if (nic.getIp4Address() == null) { - PublicIp ip = assignPublicIpAddress(dc.getId(), null, vm.getOwner(), VlanType.DirectAttached, network.getId(), requestedIp, false); - nic.setIp4Address(ip.getAddress().toString()); - nic.setGateway(ip.getGateway()); - nic.setNetmask(ip.getNetmask()); - nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag())); - nic.setBroadcastType(BroadcastDomainType.Vlan); - nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag())); - nic.setFormat(AddressFormat.Ip4); - nic.setReservationId(String.valueOf(ip.getVlanTag())); - nic.setMacAddress(ip.getMacAddress()); - } - - nic.setDns1(dc.getDns1()); - nic.setDns2(dc.getDns2()); + return results; } - + + @Override + public void checkCapabilityForProvider(Set providers, Service service, Capability cap, String capValue) { + for (Provider provider : providers) { + NetworkElement element = getElementImplementingProvider(provider.getName()); + if (element != null) { + Map> elementCapabilities = element.getCapabilities(); + if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { + throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider.getName()); + } + Map serviceCapabilities = elementCapabilities.get(service); + if (serviceCapabilities == null || serviceCapabilities.isEmpty()) { + throw new UnsupportedServiceException("Service " + service.getName() + " doesn't have capabilites for element=" + element.getName() + " implementing Provider=" + provider.getName()); + } + + String value = serviceCapabilities.get(cap); + if (value == null || value.isEmpty()) { + throw new UnsupportedServiceException("Service " + service.getName() + " doesn't have capability " + cap.getName() + " for element=" + element.getName() + " implementing Provider=" + + provider.getName()); + } + + capValue = capValue.toLowerCase(); + + if (!value.contains(capValue)) { + throw new UnsupportedServiceException("Service " + service.getName() + " doesn't support value " + capValue + " for capability " + cap.getName() + " for element=" + element.getName() + + " implementing Provider=" + provider.getName()); + } + } else { + throw new UnsupportedServiceException("Unable to find network element for provider " + provider.getName()); + } + } + } + + public IpAddress assignElasticIp(long networkId, Account owner, boolean forElasticLb, boolean forElasticIp) throws InsufficientAddressCapacityException { + Network guestNetwork = getNetwork(networkId); + NetworkOffering off = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); + IpAddress ip = null; + if ((off.getElasticLb() && forElasticLb) || (off.getElasticIp() && forElasticIp)) { + + try { + s_logger.debug("Allocating elastic IP address for load balancer rule..."); + // allocate ip + ip = allocateIP(networkId, owner, true); + // apply ip associations + ip = associateIP(ip.getId()); + } catch (ResourceAllocationException ex) { + throw new CloudRuntimeException("Failed to allocate elastic ip due to ", ex); + } catch (ConcurrentOperationException ex) { + throw new CloudRuntimeException("Failed to allocate elastic lb ip due to ", ex); + } catch (ResourceUnavailableException ex) { + throw new CloudRuntimeException("Failed to allocate elastic lb ip due to ", ex); + } + + if (ip == null) { + throw new CloudRuntimeException("Failed to allocate elastic ip"); + } + } + + return ip; + } + + @Override + public boolean handleElasticIpRelease(IpAddress ip) { + boolean success = true; + Long networkId = ip.getAssociatedWithNetworkId(); + if (networkId != null) { + if (ip.getElastic()) { + UserContext ctx = UserContext.current(); + if (!releasePublicIpAddress(ip.getId(), ctx.getCallerUserId(), ctx.getCaller())) { + s_logger.warn("Unable to release elastic ip address id=" + ip.getId()); + success = false; + } else { + s_logger.warn("Successfully released elastic ip address id=" + ip.getId()); + } + } + } + return success; + } + + @Override + public void checkNetworkPermissions(Account owner, Network network) { + // Perform account permission check + if (network.getGuestType() != Network.GuestType.Shared) { + List networkMap = _networksDao.listBy(owner.getId(), network.getId()); + if (networkMap == null || networkMap.isEmpty()) { + throw new PermissionDeniedException("Unable to use network with id= " + network.getId() + ", permission denied"); + } + } else { + if (!isNetworkAvailableInDomain(network.getId(), owner.getDomainId())) { + throw new PermissionDeniedException("Shared network id=" + network.getId() + " is not available in domain id=" + owner.getDomainId()); + } + } + } + + public void allocateDirectIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network, String requestedIp) throws InsufficientVirtualNetworkCapcityException, + InsufficientAddressCapacityException { + if (nic.getIp4Address() == null) { + PublicIp ip = assignPublicIpAddress(dc.getId(), null, vm.getOwner(), VlanType.DirectAttached, network.getId(), requestedIp, false); + nic.setIp4Address(ip.getAddress().toString()); + nic.setGateway(ip.getGateway()); + nic.setNetmask(ip.getNetmask()); + nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag())); + nic.setBroadcastType(BroadcastDomainType.Vlan); + nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag())); + nic.setFormat(AddressFormat.Ip4); + nic.setReservationId(String.valueOf(ip.getVlanTag())); + nic.setMacAddress(ip.getMacAddress()); + } + + nic.setDns1(dc.getDns1()); + nic.setDns2(dc.getDns2()); + } + } diff --git a/server/src/com/cloud/network/dao/FirewallRulesDao.java b/server/src/com/cloud/network/dao/FirewallRulesDao.java index be865b6bc53..fcb73b6b844 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDao.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDao.java @@ -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 { - + List listByIpAndPurposeAndNotRevoked(long ipAddressId, FirewallRule.Purpose purpose); - + List 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 listByIpAndPurpose(long ipAddressId, FirewallRule.Purpose purpose); - + List listByNetworkAndPurpose(long networkId, FirewallRule.Purpose purpose); - + List listStaticNatByVmId(long vmId); - + List listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose); FirewallRuleVO findByRelatedId(long ruleId); - List listSystemRules(); - + List listSystemRules(); + List listByIp(long ipAddressId); - + List listByIpAndNotRevoked(long ipAddressId); - + long countRulesByIpId(long sourceIpId); -} + +} diff --git a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java index f8001e87a94..cc9dca0242e 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java @@ -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 implements FirewallRulesDao { - + +@Local(value = FirewallRulesDao.class) +@DB(txn = false) +public class FirewallRulesDaoImpl extends GenericDaoBase implements FirewallRulesDao { + protected final SearchBuilder AllFieldsSearch; protected final SearchBuilder NotRevokedSearch; protected final SearchBuilder ReleaseSearch; protected SearchBuilder VmSearch; protected final SearchBuilder SystemRuleSearch; protected final GenericSearchBuilder 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 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 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 listSystemRules() { - SearchCriteria sc = SystemRuleSearch.create(); - sc.setParameters("type", FirewallRuleType.System.toString()); - return listBy(sc); + SearchCriteria 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 sc = ReleaseSearch.create(); @@ -108,17 +109,17 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i sc.setParameters("ipId", ipId); sc.setParameters("purpose", purpose); sc.setParameters("ports", ports); - + int results = remove(sc); return results == ports.length; } - + @Override public List listByIpAndPurpose(long ipId, FirewallRule.Purpose purpose) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("ipId", ipId); sc.setParameters("purpose", purpose); - + return listBy(sc); } @@ -127,123 +128,122 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i SearchCriteria 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 listByNetworkAndPurposeAndNotRevoked(long networkId, FirewallRule.Purpose purpose) { SearchCriteria 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 listByNetworkAndPurpose(long networkId, FirewallRule.Purpose purpose) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("purpose", purpose); sc.setParameters("networkId", networkId); - + return listBy(sc); } - + @Override public boolean setStateToAdd(FirewallRuleVO rule) { SearchCriteria 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 listStaticNatByVmId(long vmId) { + public List listStaticNatByVmId(long vmId) { IPAddressDao _ipDao = ComponentLocator.getLocator("management-server").getDao(IPAddressDao.class); - - if (VmSearch == null) { + + if (VmSearch == null) { SearchBuilder 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 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 cidrList) { if (cidrList == null) { return; } _firewallRulesCidrsDao.persist(firewallRule.getId(), cidrList); } - @Override public List listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose) { SearchCriteria 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 sc = AllFieldsSearch.create(); sc.setParameters("related", ruleId); sc.setParameters("purpose", Purpose.Firewall); - + return findOneBy(sc); } @@ -251,23 +251,24 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i public List listByIp(long ipId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("ipId", ipId); - + return listBy(sc); } - + @Override public List listByIpAndNotRevoked(long ipId) { SearchCriteria sc = NotRevokedSearch.create(); sc.setParameters("ipId", ipId); sc.setParameters("state", State.Revoke); - + return listBy(sc); } - + @Override public long countRulesByIpId(long sourceIpId) { - SearchCriteria sc = RulesByIpCount.create(); + SearchCriteria sc = RulesByIpCount.create(); sc.setParameters("ipAddressId", sourceIpId); return customSearch(sc, null).get(0); } -} + +} diff --git a/server/src/com/cloud/network/dao/LoadBalancerDao.java b/server/src/com/cloud/network/dao/LoadBalancerDao.java index 4bc9992f3f2..71dab1585d4 100644 --- a/server/src/com/cloud/network/dao/LoadBalancerDao.java +++ b/server/src/com/cloud/network/dao/LoadBalancerDao.java @@ -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 { - List listInstancesByLoadBalancer(long loadBalancerId); - List listByIpAddress(long ipAddressId); + +public interface LoadBalancerDao extends GenericDao { + List listInstancesByLoadBalancer(long loadBalancerId); + + List listByIpAddress(long ipAddressId); + LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort); + LoadBalancerVO findByAccountAndName(Long accountId, String name); + List listByNetworkId(long networkId); - List listInTransitionStateByNetworkId(long networkId); -} + + List listInTransitionStateByNetworkId(long networkId); + +} diff --git a/server/src/com/cloud/network/dao/LoadBalancerDaoImpl.java b/server/src/com/cloud/network/dao/LoadBalancerDaoImpl.java index afb6ac2d76f..fcfa8825dd3 100644 --- a/server/src/com/cloud/network/dao/LoadBalancerDaoImpl.java +++ b/server/src/com/cloud/network/dao/LoadBalancerDaoImpl.java @@ -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 implements LoadBalancerDao { + +@Local(value = { LoadBalancerDao.class }) +public class LoadBalancerDaoImpl extends GenericDaoBase 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 ListByIp; - private final SearchBuilder 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 ListByIp; + private final SearchBuilder IpAndPublicPortSearch; private final SearchBuilder AccountAndNameSearch; protected final SearchBuilder 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 listInstancesByLoadBalancer(long loadBalancerId) { - Transaction txn = Transaction.currentTxn(); - String sql = LIST_INSTANCES_BY_LOAD_BALANCER; - PreparedStatement pstmt = null; - List instanceList = new ArrayList(); - 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 listByIpAddress(long ipAddressId) { - SearchCriteria sc = ListByIp.create(); - sc.setParameters("ipAddressId", ipAddressId); - return listBy(sc); } - + + @Override + public List listInstancesByLoadBalancer(long loadBalancerId) { + Transaction txn = Transaction.currentTxn(); + String sql = LIST_INSTANCES_BY_LOAD_BALANCER; + PreparedStatement pstmt = null; + List instanceList = new ArrayList(); + 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 listByIpAddress(long ipAddressId) { + SearchCriteria sc = ListByIp.create(); + sc.setParameters("ipAddressId", ipAddressId); + return listBy(sc); + } + @Override public List listByNetworkId(long networkId) { SearchCriteria sc = ListByIp.create(); sc.setParameters("networkId", networkId); return listBy(sc); - } - - @Override - public LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort) { - SearchCriteria sc = IpAndPublicPortSearch.create(); - sc.setParameters("ipAddressId", ipAddressId); - sc.setParameters("publicPort", publicPort); - return findOneBy(sc); + } + + @Override + public LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort) { + SearchCriteria sc = IpAndPublicPortSearch.create(); + sc.setParameters("ipAddressId", ipAddressId); + sc.setParameters("publicPort", publicPort); + return findOneBy(sc); } @Override @@ -126,12 +126,13 @@ public class LoadBalancerDaoImpl extends GenericDaoBase im sc.setParameters("name", name); return findOneBy(sc); } - + @Override public List listInTransitionStateByNetworkId(long networkId) { - SearchCriteria sc = TransitionStateSearch.create(); - sc.setParameters("networkId", networkId); - sc.setParameters("state", State.Add.toString(), State.Revoke.toString()); - return listBy(sc); - } -} + SearchCriteria sc = TransitionStateSearch.create(); + sc.setParameters("networkId", networkId); + sc.setParameters("state", State.Add.toString(), State.Revoke.toString()); + return listBy(sc); + } + +} diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index bfa66d37352..28e0f103ace 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -46,7 +46,7 @@ public interface NetworkDao extends GenericDao { @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 { List listByPhysicalNetworkAndProvider(long physicalNetworkId, String providerName); - void persistNetworkServiceProviders(long networkId, Map serviceProviderMap); - - boolean update(Long networkId, NetworkVO network, Map serviceProviderMap); - - List listByZoneAndTrafficType(long zoneId, TrafficType trafficType); + void persistNetworkServiceProviders(long networkId, Map serviceProviderMap); + + boolean update(Long networkId, NetworkVO network, Map serviceProviderMap); + + List listByZoneAndTrafficType(long zoneId, TrafficType trafficType); + } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 181738983ec..00f12634abb 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -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 implements NetworkDao { final SearchBuilder AllFieldsSearch; final SearchBuilder AccountSearch; @@ -60,7 +61,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N final GenericSearchBuilder CountByOfferingId; final SearchBuilder PhysicalNetworkSearch; final SearchBuilder 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 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 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 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 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 implements N return listBy(sc); } - @Override @DB + @Override + @DB public NetworkVO persist(NetworkVO network, boolean gc, Map 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 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 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 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 implements N sc.setParameters("physicalNetworkId", physicalNetworkId); return listBy(sc); } - + @Override - public List listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType){ + public List listByPhysicalNetworkTrafficType(long physicalNetworkId, TrafficType trafficType) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("trafficType", trafficType); sc.setParameters("physicalNetworkId", physicalNetworkId); @@ -375,7 +375,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N return listBy(sc); } - + @Override public List listBy(long accountId, long dataCenterId, Network.GuestType type, TrafficType trafficType) { SearchCriteria sc = AllFieldsSearch.create(); @@ -383,16 +383,17 @@ public class NetworkDaoImpl extends GenericDaoBase implements N sc.setParameters("account", accountId); sc.setParameters("guestType", type); sc.setParameters("trafficType", trafficType); - + return listBy(sc, null); } - + @Override public List listByZoneAndTrafficType(long zoneId, TrafficType trafficType) { - SearchCriteria sc = AllFieldsSearch.create(); + SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("datacenter", zoneId); sc.setParameters("trafficType", trafficType); - + return listBy(sc, null); } + } diff --git a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java index 0c4d851cb0b..9918946a4d4 100644 --- a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java +++ b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java @@ -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> 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 vmProfile, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile 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 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> getCapabilities() { return capabilities; } - + private static Map> setCapabilities() { Map> capabilities = new HashMap>(); - + 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 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 = (VirtualMachineProfile)vm; + VirtualMachineProfile uservm = (VirtualMachineProfile) 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 services) { return true; } + } diff --git a/server/src/com/cloud/network/element/ExternalDhcpElement.java b/server/src/com/cloud/network/element/ExternalDhcpElement.java index 64f4f04e5b0..19c147db461 100644 --- a/server/src/com/cloud/network/element/ExternalDhcpElement.java +++ b/server/src/com/cloud/network/element/ExternalDhcpElement.java @@ -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> 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> 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> setCapabilities() { - //No external dhcp support for Acton release + // No external dhcp support for Acton release Map> capabilities = new HashMap>(); -// capabilities.put(Service.Dhcp, null); +// capabilities.put(Service.Dhcp, null); return capabilities; } - - @Override - public Map> getCapabilities() { - return capabilities; - } - @Override - public Provider getProvider() { - return Provider.ExternalDhcpServer; - } + @Override + public Map> 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 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 vm, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException { - return true; - } + @Override + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile 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 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 services) { return true; diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 6a9a65fa969..924daa6510a 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -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 vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { + public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, + InsufficientNetworkCapacityException, ResourceUnavailableException { return true; } @Override - public boolean release(Network config, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) { + public boolean release(Network config, NicProfile nic, VirtualMachineProfile 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 rules) throws ResourceUnavailableException { if (!canHandle(config)) { return false; } - - return applyLoadBalancerRules(config, rules); + + return applyLoadBalancerRules(config, rules); } - + @Override public Map> getCapabilities() { - Map> capabilities = new HashMap>(); - - // Set capabilities for LB service - Map lbCapabilities = new HashMap(); - - // Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules - lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn"); + Map> capabilities = new HashMap>(); - // specifies that F5 BIG IP network element can provide shared mode only - lbCapabilities.put(Capability.SupportedLBIsolation, "shared"); + // Set capabilities for LB service + Map lbCapabilities = new HashMap(); - // 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 methodList = new ArrayList(); - 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 methodList = new ArrayList(); + 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 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 lbDevices = new ArrayList (); + List lbDevices = new ArrayList(); 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 services) { return true; @@ -459,7 +471,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan @Override public boolean applyIps(Network network, List ipAddress, Set 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; } diff --git a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index d779a98624e..77f7f41f4dc 100644 --- a/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/server/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -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> 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 vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { + public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile 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 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 users) throws ResourceUnavailableException{ + public String[] applyVpnUsers(RemoteAccessVpn vpn, List 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> setCapabilities() { Map> capabilities = new HashMap>(); - + // Set capabilities for Firewall service - Map firewallCapabilities = new HashMap(); - firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp"); + Map firewallCapabilities = new HashMap(); + 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 vpnCapabilities = new HashMap(); -// 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 vpnCapabilities = new HashMap(); +// vpnCapabilities.put(Capability.SupportedVpnTypes, "ipsec"); +// capabilities.put(Service.Vpn, vpnCapabilities); + capabilities.put(Service.Gateway, null); - + Map sourceNatCapabilities = new HashMap(); - // 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 rules) throws ResourceUnavailableException { if (!canHandle(network, Service.PortForwarding)) { return false; } - + return applyFirewallRules(network, rules); } @Override public boolean isReady(PhysicalNetworkServiceProvider provider) { - + List 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 listExternalFirewalls(ListExternalFirewallsCmd cmd) { List firewallHosts = new ArrayList(); 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 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 fwDevices = new ArrayList (); + List fwDevices = new ArrayList(); 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 services) { return true; @@ -524,9 +543,9 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan return this; } - @Override - public boolean applyIps(Network network, List ipAddress, Set service) throws ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean applyIps(Network network, List ipAddress, Set service) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } } \ No newline at end of file diff --git a/server/src/com/cloud/network/element/NetscalerElement.java b/server/src/com/cloud/network/element/NetscalerElement.java index 913dfcd5962..e3150e68edd 100644 --- a/server/src/com/cloud/network/element/NetscalerElement.java +++ b/server/src/com/cloud/network/element/NetscalerElement.java @@ -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 vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { + public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, + InsufficientNetworkCapacityException, ResourceUnavailableException { return true; } @Override - public boolean release(Network config, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) { + public boolean release(Network config, NicProfile nic, VirtualMachineProfile 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 rules) throws ResourceUnavailableException { if (!canHandle(config, Service.Lb)) { @@ -210,62 +221,61 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl @Override public Map> getCapabilities() { - Map> capabilities = new HashMap>(); - - // Set capabilities for LB service - Map lbCapabilities = new HashMap(); - - // Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules - lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn"); + Map> capabilities = new HashMap>(); - // specifies that Netscaler network element can provided both shared and isolation modes - lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared"); + // Set capabilities for LB service + Map lbCapabilities = new HashMap(); - // 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 methodList = new ArrayList(); - 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 staticNatCapabilities = new HashMap(); - staticNatCapabilities.put(Capability.ElasticIp, "true"); - capabilities.put(Service.StaticNat, staticNatCapabilities); - - - //TODO - Murali, please put correct capabilities here - Map firewallCapabilities = new HashMap(); - 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 methodList = new ArrayList(); + 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 staticNatCapabilities = new HashMap(); + staticNatCapabilities.put(Capability.ElasticIp, "true"); + capabilities.put(Service.StaticNat, staticNatCapabilities); + + // TODO - Murali, please put correct capabilities here + Map firewallCapabilities = new HashMap(); + 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 lbDevices = new ArrayList (); + List lbDevices = new ArrayList(); 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 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 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; } } + } \ No newline at end of file diff --git a/server/src/com/cloud/network/element/OvsElement.java b/server/src/com/cloud/network/element/OvsElement.java index 97baddecb37..72c07c91b54 100644 --- a/server/src/com/cloud/network/element/OvsElement.java +++ b/server/src/com/cloud/network/element/OvsElement.java @@ -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> getCapabilities() { - return null; - } + @Override + public boolean destroy(Network network) + throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } - @Override - public Provider getProvider() { - return null; - } + @Override + public Map> 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 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 vm, - ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { + @Override + public boolean prepare(Network network, NicProfile nic, + VirtualMachineProfile 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 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 services) { return true; diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 8604180f4b8..41e65465f85 100644 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -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> 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 vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (vm.getType() != VirtualMachine.Type.User) { + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile 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 = (VirtualMachineProfile)vm; + VirtualMachineProfile uservm = (VirtualMachineProfile) vm; List 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 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 users) throws ResourceUnavailableException{ + public String[] applyVpnUsers(RemoteAccessVpn vpn, List users) throws ResourceUnavailableException { Network network = _networksDao.findById(vpn.getNetworkId()); - + if (canHandle(network, Service.Vpn)) { - List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); + List 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 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 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 routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); + List 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> getCapabilities() { return capabilities; } - + private static String getHAProxyStickinessCapability() { LbStickinessMethod method; - List methodList = new ArrayList(1); - - method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is loadbalancer cookie based stickiness method."); + List methodList = new ArrayList(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> setCapabilities() { Map> capabilities = new HashMap>(); - - //Set capabilities for LB service + + // Set capabilities for LB service Map lbCapabilities = new HashMap(); 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 firewallCapabilities = new HashMap(); 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 vpnCapabilities = new HashMap(); vpnCapabilities.put(Capability.SupportedVpnTypes, "pptp,l2tp,ipsec"); capabilities.put(Service.Vpn, vpnCapabilities); - + Map dnsCapabilities = new HashMap(); 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 sourceNatCapabilities = new HashMap(); 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 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 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 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 vm) throws ResourceUnavailableException{ - if (!canHandle(network, null)) { - return false; - } + public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException { + if (!canHandle(network, null)) { + return false; + } List 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 = (VirtualMachineProfile)vm; - + VirtualMachineProfile uservm = (VirtualMachineProfile) 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 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 = (VirtualMachineProfile)vm; + VirtualMachineProfile uservm = (VirtualMachineProfile) 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 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 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 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 = (VirtualMachineProfile)vm; + VirtualMachineProfile uservm = (VirtualMachineProfile) 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 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 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 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 sc = SearchCriteria2.create(VirtualRouterProviderVO.class); if (id != null) { sc.addAnd(sc.getEntity().getId(), Op.EQ, id); diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index 7c54b1cf934..5e4f8a090b9 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -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 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 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 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 listFirewallRules(ListFirewallRulesCmd cmd) { Long ipId = cmd.getIpAddressId(); Long id = cmd.getId(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -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 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 ruleCidrList = rule.getSourceCidrList(); List newRuleCidrList = newRule.getSourceCidrList(); - + if (ruleCidrList == null || newRuleCidrList == null) { continue; } - + Collection similar = new HashSet(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 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 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 rules = _firewallDao.listByIpAndPurpose(ipId, Purpose.Firewall); return applyFirewallRules(rules, false, caller); } - - + @Override public boolean applyFirewallRules(List 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 rules = new ArrayList(); @@ -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 rules = _firewallDao.listByIpPurposeAndProtocolAndNotRevoked(ipAddrId, startPort, endPort, protocol, Purpose.Firewall); if (!rules.isEmpty()) { return rules.get(0); } - + List oneCidr = new ArrayList(); 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 rules = new ArrayList(); @@ -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 pfRules = _pfRulesDao.listByVm(vmId); List staticNatRules = _firewallDao.listStaticNatByVmId(vm.getId()); List firewallRules = new ArrayList(); - - //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 ipsToReprogram = new HashSet(); 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 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 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; + } + } diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index 3ecb60da8f7..2ca817fd703 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -183,7 +183,7 @@ public class LoadBalancingRulesManagerImpl 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 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 methodParamList = method.getParamList(); + List methodParamList = method.getParamList(); Map tempParamList = new HashMap(); /* @@ -246,15 +246,15 @@ public class LoadBalancingRulesManagerImpl 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 stickinessPolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(cmd.getLbRuleId(), false); + List 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 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 policyList = new ArrayList(); policyList.add(new LbStickinessPolicy(cmd.getStickinessMethodName(), lbpolicy.getParams())); @@ -295,11 +295,11 @@ public class LoadBalancingRulesManagerImpl 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 lbs = _lbDao.listInTransitionStateByNetworkId(lb.getNetworkId()); return applyLoadBalancerRules(lbs, true); } @@ -768,7 +766,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa List dstList = getExistingDestinations(lb.getId()); List 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 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 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 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 implements LoadBalancingRulesMa } return true; } - + @Override public List getStickinessPolicies(long lbId) { List stickinessPolicies = new ArrayList(); List 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 getExistingDestinations(long lbId) { List dstList = new ArrayList(); @@ -927,7 +925,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa return true; } - @Override + @Override public boolean stop() { return true; } @@ -946,12 +944,12 @@ public class LoadBalancingRulesManagerImpl 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 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 implements LoadBalancingRulesMa return loadBalancerInstances; } + @Override - public List getStickinessMethods(long networkid) + public List 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>() {}.getType(); - List result = gson.fromJson(capability,listType); + java.lang.reflect.Type listType = new TypeToken>() { + }.getType(); + List result = gson.fromJson(capability, listType); return result; } @@ -1056,14 +1057,14 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa if (loadBalancer == null) { return null; } - + _accountMgr.checkAccess(caller, null, true, loadBalancer); - + List sDbpolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(cmd.getLbRuleId()); - + return sDbpolicies; } - + @Override public List searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) { Long ipId = cmd.getPublicIpId(); @@ -1072,7 +1073,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa String name = cmd.getLoadBalancerRuleName(); String keyword = cmd.getKeyword(); Long instanceId = cmd.getVirtualMachineId(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -1080,12 +1081,12 @@ public class LoadBalancingRulesManagerImpl 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 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 implements LoadBalancingRulesMa SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + if (keyword != null) { SearchCriteria ssc = _lbDao.createSearchCriteria(); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); diff --git a/server/src/com/cloud/network/rules/FirewallManager.java b/server/src/com/cloud/network/rules/FirewallManager.java index bdc5500aa88..541b5cd671f 100644 --- a/server/src/com/cloud/network/rules/FirewallManager.java +++ b/server/src/com/cloud/network/rules/FirewallManager.java @@ -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 rules, boolean continueOnError, boolean updateRulesInDB) throws ResourceUnavailableException; boolean applyFirewallRules(List 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 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 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); + } diff --git a/server/src/com/cloud/network/rules/RulesManager.java b/server/src/com/cloud/network/rules/RulesManager.java index 4c5b3537786..eee213785b2 100644 --- a/server/src/com/cloud/network/rules/RulesManager.java +++ b/server/src/com/cloud/network/rules/RulesManager.java @@ -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 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 listPortForwardingRulesForApplication(long ipId); - + List gatherPortForwardingRulesForApplication(List 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 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 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; } diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index d303cb12b8d..3a86aa70d50 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -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 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 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 getSourceCidrs(long ruleId){ + public List getSourceCidrs(long ruleId) { return _firewallCidrsDao.getSourceCidrs(ruleId); } @Override public boolean applyPortForwardingRules(long ipId, boolean continueOnError, Account caller) { List 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 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 staticNats = new ArrayList(); 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 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 permittedAccounts = new ArrayList(); 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 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 ipSearch = _ipAddressDao.createSearchBuilder(); ipSearch.and("associatedWithVmId", ipSearch.entity().getAssociatedWithVmId(), Op.EQ); @@ -809,7 +805,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { SearchCriteria 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 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 staticNats = new ArrayList(); 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 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 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); + } + } + } } - + } diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index 6c23bfb354d..f6393936e16 100755 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -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; + } + } diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java index 4fdb8e85e8a..66731d4aa0d 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDao.java @@ -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 { /** * 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 listSystemNetworkOfferings(); - + List listByAvailability(Availability availability, boolean isSystem); - + List getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering); - + List listByTrafficTypeGuestTypeAndState(NetworkOffering.State state, TrafficType trafficType, Network.GuestType type); - + } diff --git a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java index 56e86e48b50..f1c0d5e46c3 100644 --- a/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java +++ b/server/src/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java @@ -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 implements NetworkOfferingDao { final SearchBuilder NameSearch; final SearchBuilder SystemOfferingSearch; final SearchBuilder AvailabilitySearch; final SearchBuilder AllFieldsSearch; private final GenericSearchBuilder 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 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 listSystemNetworkOfferings() { SearchCriteria sc = SystemOfferingSearch.create(); sc.setParameters("system", true); return this.listIncludingRemovedBy(sc, null); } - + @Override public List listByAvailability(Availability availability, boolean isSystem) { SearchCriteria sc = AvailabilitySearch.create(); @@ -122,11 +122,12 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase getOfferingIdsToUpgradeFrom(NetworkOffering originalOffering) { SearchCriteria 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 listByTrafficTypeGuestTypeAndState(NetworkOffering.State state, TrafficType trafficType, Network.GuestType type) { SearchCriteria sc = AllFieldsSearch.create(); @@ -163,4 +164,5 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase ResourceCountSearch; ScheduledExecutorService _rcExecutor; - long _resourceCountCheckInterval=0; - Map accountResourceLimitMap = new EnumMap(ResourceType.class); - Map projectResourceLimitMap = new EnumMap(ResourceType.class); - + long _resourceCountCheckInterval = 0; + Map accountResourceLimitMap = new EnumMap(ResourceType.class); + Map projectResourceLimitMap = new EnumMap(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 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 rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(account.getId(), ResourceOwnerType.Account, type); SearchCriteria 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 searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal) { - Account caller = UserContext.current().getCaller(); - List limits = new ArrayList(); - 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 limits = new ArrayList(); + 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 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 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 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 accountLimitStr = new ArrayList(); - List domainLimitStr = new ArrayList(); - 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 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 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 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 accountLimitStr = new ArrayList(); + List domainLimitStr = new ArrayList(); + 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 recalculateResourceCount(Long accountId, Long domainId, Integer typeId) throws InvalidParameterValueException, CloudRuntimeException, PermissionDeniedException{ + public List recalculateResourceCount(Long accountId, Long domainId, Integer typeId) throws InvalidParameterValueException, CloudRuntimeException, PermissionDeniedException { Account callerAccount = UserContext.current().getCaller(); - long count=0; + long count = 0; List counts = new ArrayList(); List resourceTypes = new ArrayList(); @@ -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 rowsToLock = _resourceCountDao.listAllRowsToUpdate(accountId, ResourceOwnerType.Account, type); - - //Lock rows first + + // Lock rows first SearchCriteria sc = ResourceCountSearch.create(); sc.setParameters("id", rowsToLock.toArray()); - List rowsToUpdate = _resourceCountDao.lockRows(sc, null, true); - + List 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 rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(domainId, ResourceOwnerType.Domain, type); SearchCriteria sc = ResourceCountSearch.create(); sc.setParameters("id", rowIdsToLock.toArray()); @@ -649,18 +648,18 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager{ List 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 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 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); diff --git a/server/src/com/cloud/server/ConfigurationServer.java b/server/src/com/cloud/server/ConfigurationServer.java index 46bce165a62..b56afe6d29b 100644 --- a/server/src/com/cloud/server/ConfigurationServer.java +++ b/server/src/com/cloud/server/ConfigurationServer.java @@ -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; + } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index c39a8aaa0d5..586e009274d 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -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 categories = Config.getCategories(); for (String category : categories) { @@ -165,16 +166,16 @@ public class ConfigurationServerImpl implements ConfigurationServer { if (!_configDao.isPremium() && category.equals("Premium")) { continue; } - + List 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 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 defaultSharedNetworkOfferingProviders = new HashMap(); defaultSharedNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter); defaultSharedNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter); defaultSharedNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter); - + Map defaultIsolatedNetworkOfferingProviders = defaultSharedNetworkOfferingProviders; - + Map defaultSharedSGNetworkOfferingProviders = new HashMap(); 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 defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap(); 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 netscalerServiceProviders = new HashMap(); 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 zones = _dataCenterDao.listAll(); long id = 1; - + HashMap guruNames = new HashMap(); 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 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 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 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 domains = _domainDao.listAllIncludingRemoved(); List domainResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Domain); List accountResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Account); - + List accountSupportedResourceTypes = new ArrayList(); List domainSupportedResourceTypes = new ArrayList(); - + 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 getServicesAndProvidersForNetwork(long networkOfferingId) { Map svcProviders = new HashMap(); List 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; } diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index ecf63001080..a019d58fc89 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -333,7 +333,6 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag private StateMachine2 _volStateMachine; private int _customDiskOfferingMinSize = 1; private int _customDiskOfferingMaxSize = 1024; - public boolean share(VMInstanceVO vm, List vols, HostVO host, boolean cancelPreviousShare) throws StorageUnavailableException { @@ -364,9 +363,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override public VolumeVO allocateDuplicateVolume(VolumeVO oldVol, Long templateId) { VolumeVO newVol = new VolumeVO(oldVol.getVolumeType(), oldVol.getName(), oldVol.getDataCenterId(), oldVol.getDomainId(), oldVol.getAccountId(), oldVol.getDiskOfferingId(), oldVol.getSize()); - if(templateId != null){ + if (templateId != null) { newVol.setTemplateId(templateId); - }else{ + } else { newVol.setTemplateId(oldVol.getTemplateId()); } newVol.setDeviceId(oldVol.getDeviceId()); @@ -391,12 +390,12 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag public List ListByDataCenterHypervisor(long datacenterId, HypervisorType type) { List pools = _storagePoolDao.listByDataCenterId(datacenterId); List retPools = new ArrayList(); - for (StoragePoolVO pool : pools ) { - if( pool.getStatus() != StoragePoolStatus.Up) { + for (StoragePoolVO pool : pools) { + if (pool.getStatus() != StoragePoolStatus.Up) { continue; } ClusterVO cluster = _clusterDao.findById(pool.getClusterId()); - if( type == cluster.getHypervisorType()) { + if (type == cluster.getHypervisorType()) { retPools.add(pool); } } @@ -409,7 +408,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag List storagePoolHostRefs = _storagePoolHostDao.listByHostId(host.getId()); for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) { StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolHostRef.getPoolId()); - if (storagePool.getPoolType() == StoragePoolType.LVM || storagePool.getPoolType() == StoragePoolType.EXT) { + if (storagePool.getPoolType() == StoragePoolType.LVM || storagePool.getPoolType() == StoragePoolType.EXT) { SearchBuilder volumeSB = _volsDao.createSearchBuilder(); volumeSB.and("poolId", volumeSB.entity().getPoolId(), SearchCriteria.Op.EQ); volumeSB.and("removed", volumeSB.entity().getRemoved(), SearchCriteria.Op.NULL); @@ -521,10 +520,10 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag String volumeFolder = null; try { - stateTransitTo(volume, Volume.Event.CreateRequested); + stateTransitTo(volume, Volume.Event.CreateRequested); } catch (NoTransitionException e) { - s_logger.debug(e.toString()); - return null; + s_logger.debug(e.toString()); + return null; } // Create the Volume object and save it so that we can return it to the user Account account = _accountDao.findById(volume.getAccountId()); @@ -595,26 +594,26 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag createdVolume = _volsDao.findById(volumeId); try { - if (success) { - createdVolume.setPodId(pod.first().getId()); - createdVolume.setPoolId(pool.getId()); - createdVolume.setPoolType(pool.getPoolType()); - createdVolume.setFolder(volumeFolder); - createdVolume.setPath(volumeUUID); - createdVolume.setDomainId(account.getDomainId()); - stateTransitTo(createdVolume, Volume.Event.OperationSucceeded); - } + if (success) { + createdVolume.setPodId(pod.first().getId()); + createdVolume.setPoolId(pool.getId()); + createdVolume.setPoolType(pool.getPoolType()); + createdVolume.setFolder(volumeFolder); + createdVolume.setPath(volumeUUID); + createdVolume.setDomainId(account.getDomainId()); + stateTransitTo(createdVolume, Volume.Event.OperationSucceeded); + } } catch (NoTransitionException e) { - s_logger.debug("Failed to update volume state: " + e.toString()); - return null; + s_logger.debug("Failed to update volume state: " + e.toString()); + return null; } - + return new Pair(createdVolume, details); } - + @Override public boolean stateTransitTo(Volume vol, Volume.Event event) throws NoTransitionException { - return _volStateMachine.transitTo(vol, event, null, _volsDao); + return _volStateMachine.transitTo(vol, event, null, _volsDao); } protected VolumeVO createVolumeFromSnapshot(VolumeVO volume, long snapshotId) { @@ -625,7 +624,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag Pair volumeDetails = createVolumeFromSnapshot(volume, snapshot); if (volumeDetails != null) { - createdVolume = volumeDetails.first(); + createdVolume = volumeDetails.first(); } return createdVolume; } @@ -644,34 +643,34 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (snapshot.getVersion().trim().equals("2.1")) { VolumeVO volume = _volsDao.findByIdIncludingRemoved(volumeId); if (volume == null) { - throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to unable to find orignal volume:" + volumeId + ", try it later "); + throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to unable to find orignal volume:" + volumeId + ", try it later "); } if (volume.getTemplateId() == null) { - _snapshotDao.updateSnapshotVersion(volumeId, "2.1", "2.2"); + _snapshotDao.updateSnapshotVersion(volumeId, "2.1", "2.2"); } else { - VMTemplateVO template = _templateDao.findByIdIncludingRemoved(volume.getTemplateId()); - if (template == null) { - throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to unalbe to find orignal template :" + volume.getTemplateId() + ", try it later "); - } - Long templateId = template.getId(); - Long tmpltAccountId = template.getAccountId(); - if (!_snapshotDao.lockInLockTable(snapshotId.toString(), 10)) { - throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to this snapshot is being used, try it later "); - } - UpgradeSnapshotCommand cmd = new UpgradeSnapshotCommand(null, secondaryStoragePoolUrl, dcId, accountId, volumeId, templateId, tmpltAccountId, null, snapshot.getBackupSnapshotId(), - snapshot.getName(), "2.1"); - Answer answer = null; - try { - answer = sendToPool(pool, cmd); - } catch (StorageUnavailableException e) { - } finally { - _snapshotDao.unlockFromLockTable(snapshotId.toString()); - } - if ((answer != null) && answer.getResult()) { - _snapshotDao.updateSnapshotVersion(volumeId, "2.1", "2.2"); - } else { - return new Pair(null, "Unable to upgrade snapshot from 2.1 to 2.2 for " + snapshot.getId()); - } + VMTemplateVO template = _templateDao.findByIdIncludingRemoved(volume.getTemplateId()); + if (template == null) { + throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to unalbe to find orignal template :" + volume.getTemplateId() + ", try it later "); + } + Long templateId = template.getId(); + Long tmpltAccountId = template.getAccountId(); + if (!_snapshotDao.lockInLockTable(snapshotId.toString(), 10)) { + throw new CloudRuntimeException("failed to upgrade snapshot " + snapshotId + " due to this snapshot is being used, try it later "); + } + UpgradeSnapshotCommand cmd = new UpgradeSnapshotCommand(null, secondaryStoragePoolUrl, dcId, accountId, volumeId, templateId, tmpltAccountId, null, snapshot.getBackupSnapshotId(), + snapshot.getName(), "2.1"); + Answer answer = null; + try { + answer = sendToPool(pool, cmd); + } catch (StorageUnavailableException e) { + } finally { + _snapshotDao.unlockFromLockTable(snapshotId.toString()); + } + if ((answer != null) && answer.getResult()) { + _snapshotDao.updateSnapshotVersion(volumeId, "2.1", "2.2"); + } else { + return new Pair(null, "Unable to upgrade snapshot from 2.1 to 2.2 for " + snapshot.getId()); + } } } String basicErrMsg = "Failed to create volume from " + snapshot.getName() + " on pool " + pool; @@ -689,7 +688,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (answer != null && answer.getResult()) { vdiUUID = answer.getVdi(); } else { - s_logger.error(basicErrMsg + " due to " + ((answer == null)?"null":answer.getDetails())); + s_logger.error(basicErrMsg + " due to " + ((answer == null) ? "null" : answer.getDetails())); throw new CloudRuntimeException(basicErrMsg); } } catch (StorageUnavailableException e) { @@ -711,12 +710,12 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag final HashSet avoidPools = new HashSet(avoids); try { - stateTransitTo(volume, Volume.Event.CreateRequested); - } catch (NoTransitionException e) { - s_logger.debug("Unable to update volume state: " + e.toString()); - return null; - } - + stateTransitTo(volume, Volume.Event.CreateRequested); + } catch (NoTransitionException e) { + s_logger.debug("Unable to update volume state: " + e.toString()); + return null; + } + if (diskOffering != null && diskOffering.isCustomized()) { diskOffering.setDiskSize(size); } @@ -800,7 +799,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } if (created == null) { - return null; + return null; } else { volume.setFolder(pool.getPath()); volume.setPath(created.getPath()); @@ -809,11 +808,11 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag volume.setPoolId(pool.getId()); volume.setPodId(pod.getId()); try { - stateTransitTo(volume, Volume.Event.OperationSucceeded); - } catch (NoTransitionException e) { - s_logger.debug("Unable to update volume state: " + e.toString()); - return null; - } + stateTransitTo(volume, Volume.Event.OperationSucceeded); + } catch (NoTransitionException e) { + s_logger.debug("Unable to update volume state: " + e.toString()); + return null; + } return volume; } } @@ -830,7 +829,8 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } } /* - * Can't find the vm where host resides on(vm is destroyed? or volume is detached from vm), randomly choose a host + * Can't find the vm where host resides on(vm is destroyed? or volume is detached from vm), randomly choose + * a host * to send the cmd */ } @@ -864,7 +864,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (overProvisioningFactorStr != null) { _overProvisioningFactor = new BigDecimal(overProvisioningFactorStr); } - + _retry = NumbersUtil.parseInt(configs.get(Config.StartRetry.key()), 10); _pingInterval = NumbersUtil.parseInt(configs.get("ping.interval"), 60); _hostRetry = NumbersUtil.parseInt(configs.get("host.retry"), 2); @@ -875,21 +875,19 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag String storageCleanupEnabled = configs.get("storage.cleanup.enabled"); _storageCleanupEnabled = (storageCleanupEnabled == null) ? true : Boolean.parseBoolean(storageCleanupEnabled); - + String value = configDao.getValue(Config.CreateVolumeFromSnapshotWait.toString()); _createVolumeFromSnapshotWait = NumbersUtil.parseInt(value, Integer.parseInt(Config.CreateVolumeFromSnapshotWait.getDefaultValue())); - + value = configDao.getValue(Config.CopyVolumeWait.toString()); _copyvolumewait = NumbersUtil.parseInt(value, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue())); - + value = configDao.getValue(Config.StorageTemplateCleanupEnabled.key()); - _templateCleanupEnabled = (value == null ? true : Boolean.parseBoolean(value)); - + _templateCleanupEnabled = (value == null ? true : Boolean.parseBoolean(value)); + String time = configs.get("storage.cleanup.interval"); _storageCleanupInterval = NumbersUtil.parseInt(time, 86400); - - s_logger.info("Storage cleanup enabled: " + _storageCleanupEnabled + ", interval: " + _storageCleanupInterval + ", template cleanup enabled: " + _templateCleanupEnabled); String workers = configs.get("expunge.workers"); @@ -909,7 +907,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag String _customDiskOfferingMaxSizeStr = configDao.getValue(Config.CustomDiskOfferingMaxSize.toString()); _customDiskOfferingMaxSize = NumbersUtil.parseInt(_customDiskOfferingMaxSizeStr, Integer.parseInt(Config.CustomDiskOfferingMaxSize.getDefaultValue())); - + HostTemplateStatesSearch = _vmTemplateHostDao.createSearchBuilder(); HostTemplateStatesSearch.and("id", HostTemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); HostTemplateStatesSearch.and("state", HostTemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); @@ -1031,11 +1029,11 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override public HostVO getSecondaryStorageHost(long zoneId, long tmpltId) { - List hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); - if( hosts == null || hosts.size() == 0) { + List hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); + if (hosts == null || hosts.size() == 0) { return null; } - for( HostVO host : hosts ) { + for (HostVO host : hosts) { VMTemplateHostVO tmpltHost = _vmTemplateHostDao.findByHostTemplate(host.getId(), tmpltId); if (tmpltHost != null && !tmpltHost.getDestroyed() && tmpltHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { return host; @@ -1046,8 +1044,8 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override public VMTemplateHostVO getTemplateHostRef(long zoneId, long tmpltId, boolean readyOnly) { - List hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); - if( hosts == null || hosts.size() == 0) { + List hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); + if (hosts == null || hosts.size() == 0) { return null; } VMTemplateHostVO inProgress = null; @@ -1072,8 +1070,8 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override public HostVO getSecondaryStorageHost(long zoneId) { - List hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); - if( hosts == null || hosts.size() == 0) { + List hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); + if (hosts == null || hosts.size() == 0) { hosts = _ssvmMgr.listLocalSecondaryStorageHostsInOneZone(zoneId); if (hosts.isEmpty()) { return null; @@ -1088,8 +1086,8 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override public List getSecondaryStorageHosts(long zoneId) { - List hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); - if( hosts == null || hosts.size() == 0) { + List hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); + if (hosts == null || hosts.size() == 0) { hosts = _ssvmMgr.listLocalSecondaryStorageHostsInOneZone(zoneId); if (hosts.isEmpty()) { return new ArrayList(); @@ -1131,7 +1129,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } protected StorageManagerImpl() { - _volStateMachine = Volume.State.getStateMachine(); + _volStateMachine = Volume.State.getStateMachine(); } @Override @@ -1193,10 +1191,10 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag throw new InvalidParameterValueException("host or path is null, should be sharedmountpoint://localhost/path"); } } else if (uri.getScheme().equalsIgnoreCase("clvm")) { - String uriPath = uri.getPath(); - if (uriPath == null) { - throw new InvalidParameterValueException("host or path is null, should be clvm://localhost/path"); - } + String uriPath = uri.getPath(); + if (uriPath == null) { + throw new InvalidParameterValueException("host or path is null, should be clvm://localhost/path"); + } } } catch (URISyntaxException e) { throw new InvalidParameterValueException(cmd.getUrl() + " is not a valid uri"); @@ -1239,7 +1237,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } else if (scheme.equalsIgnoreCase("sharedMountPoint")) { pool = new StoragePoolVO(StoragePoolType.SharedMountPoint, storageHost, 0, hostPath); } else if (scheme.equalsIgnoreCase("clvm")) { - pool = new StoragePoolVO(StoragePoolType.CLVM, storageHost, 0, hostPath.replaceFirst("/", "")); + pool = new StoragePoolVO(StoragePoolType.CLVM, storageHost, 0, hostPath.replaceFirst("/", "")); } else if (scheme.equalsIgnoreCase("PreSetup")) { pool = new StoragePoolVO(StoragePoolType.PreSetup, storageHost, 0, hostPath); } else if (scheme.equalsIgnoreCase("iscsi")) { @@ -1333,7 +1331,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag _storagePoolDao.expunge(pool.getId()); return null; } - + boolean success = false; for (HostVO h : allHosts) { success = createStoragePool(h.getId(), pool); @@ -1476,10 +1474,10 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag _storagePoolDao.update(id, sPool); _storagePoolDao.remove(id); deletePoolStats(id); - //Delete op_host_capacity entries + // Delete op_host_capacity entries _capacityDao.removeBy(Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, null, null, null, id); txn.commit(); - + s_logger.debug("Storage pool id=" + id + " is removed successfully"); return true; } else { @@ -1591,8 +1589,6 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override public VolumeVO moveVolume(VolumeVO volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId, HypervisorType dataDiskHyperType) throws ConcurrentOperationException { - - // Find a destination storage pool with the specified criteria DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DiskProfile dskCh = new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSize(), diskOffering.getTagsArray(), @@ -1617,20 +1613,22 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } /* - * Just allocate a volume in the database, don't send the createvolume cmd to hypervisor. The volume will be finally created + * Just allocate a volume in the database, don't send the createvolume cmd to hypervisor. The volume will be finally + * created * only when it's attached to a VM. */ - @Override @DB + @Override + @DB @ActionEvent(eventType = EventTypes.EVENT_VOLUME_CREATE, eventDescription = "creating volume", create = true) public VolumeVO allocVolume(CreateVolumeCmd cmd) throws ResourceAllocationException { // FIXME: some of the scheduled event stuff might be missing here... Account caller = UserContext.current().getCaller(); - + long ownerId = cmd.getEntityOwnerId(); - - //permission check + + // permission check _accountMgr.checkAccess(caller, null, true, _accountMgr.getActiveAccountById(ownerId)); - + // Check that the resource limit for volumes won't be exceeded _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.volume); @@ -1647,9 +1645,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag diskOfferingId = cmd.getDiskOfferingId(); size = cmd.getSize(); - Long sizeInGB = size; - if ( size != null ) { - if ( size > 0 ) { + Long sizeInGB = size; + if (size != null) { + if (size > 0) { size = size * 1024 * 1024 * 1024; // user specify size in GB } else { throw new InvalidParameterValueException("Disk size must be larger than 0"); @@ -1665,12 +1663,12 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } if (diskOffering.isCustomized()) { - if(size == null){ - throw new InvalidParameterValueException("This disk offering requires a custom size specified"); - } - if((sizeInGB < _customDiskOfferingMinSize) || (sizeInGB > _customDiskOfferingMaxSize)){ - throw new InvalidParameterValueException("Volume size: "+sizeInGB+"GB is out of allowed range. Max: "+_customDiskOfferingMaxSize+" Min:"+_customDiskOfferingMinSize); - } + if (size == null) { + throw new InvalidParameterValueException("This disk offering requires a custom size specified"); + } + if ((sizeInGB < _customDiskOfferingMinSize) || (sizeInGB > _customDiskOfferingMaxSize)) { + throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + _customDiskOfferingMaxSize + " Min:" + _customDiskOfferingMinSize); + } } if (!diskOffering.isCustomized() && size != null) { @@ -1700,21 +1698,22 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (snapshotCheck.getStatus() != Snapshot.Status.BackedUp) { throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for volume creation"); } - + diskOfferingId = (cmd.getDiskOfferingId() != null) ? cmd.getDiskOfferingId() : snapshotCheck.getDiskOfferingId(); zoneId = snapshotCheck.getDataCenterId(); size = snapshotCheck.getSize(); // ; disk offering is used for tags purposes - - //check snapshot permissions + + // check snapshot permissions _accountMgr.checkAccess(caller, null, true, snapshotCheck); -/* - // bug #11428. Operation not supported if vmware and snapshots parent volume = ROOT - if(snapshotCheck.getHypervisorType() == HypervisorType.VMware - && _volumeDao.findByIdIncludingRemoved(snapshotCheck.getVolumeId()).getVolumeType() == Type.ROOT){ - throw new UnsupportedServiceException("operation not supported, snapshot with id " + snapshotId + " is created from ROOT volume"); - } -*/ + /* + * // bug #11428. Operation not supported if vmware and snapshots parent volume = ROOT + * if(snapshotCheck.getHypervisorType() == HypervisorType.VMware + * && _volumeDao.findByIdIncludingRemoved(snapshotCheck.getVolumeId()).getVolumeType() == Type.ROOT){ + * throw new UnsupportedServiceException("operation not supported, snapshot with id " + snapshotId + + * " is created from ROOT volume"); + * } + */ } // Verify that zone exists @@ -1754,7 +1753,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); - + VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.Type.DATADISK); volume.setPoolId(null); volume.setDataCenterId(zoneId); @@ -1766,16 +1765,16 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag volume.setInstanceId(null); volume.setUpdated(new Date()); volume.setDomainId((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId()); - + volume = _volsDao.persist(volume); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), diskOfferingId, null, size); _usageEventDao.persist(usageEvent); - + UserContext.current().setEventDetails("Volume Id: " + volume.getId()); // Increment resource count during allocation; if actual creation fails, decrement it _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume); - + txn.commit(); return volume; @@ -1813,14 +1812,14 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @DB public boolean destroyVolume(VolumeVO volume) throws ConcurrentOperationException { try { - if (!stateTransitTo(volume, Volume.Event.DestroyRequested)) { - throw new ConcurrentOperationException("Failed to transit to destroyed state"); - } + if (!stateTransitTo(volume, Volume.Event.DestroyRequested)) { + throw new ConcurrentOperationException("Failed to transit to destroyed state"); + } } catch (NoTransitionException e) { - s_logger.debug("Unable to destoy the volume: " + e.toString()); - return false; + s_logger.debug("Unable to destoy the volume: " + e.toString()); + return false; } - + long volumeId = volume.getId(); // Delete the recurring snapshot policies for this volume. @@ -1839,19 +1838,19 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName()); _usageEventDao.persist(usageEvent); } - + try { - if (!stateTransitTo(volume, Volume.Event.OperationSucceeded)) { - throw new ConcurrentOperationException("Failed to transit state"); - - } - } catch (NoTransitionException e) { - s_logger.debug("Unable to change volume state: " + e.toString()); - return false; - } - + if (!stateTransitTo(volume, Volume.Event.OperationSucceeded)) { + throw new ConcurrentOperationException("Failed to transit state"); + + } + } catch (NoTransitionException e) { + s_logger.debug("Unable to change volume state: " + e.toString()); + return false; + } + return true; - + } @Override @@ -1860,7 +1859,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } @Override - public void createCapacityEntry(StoragePoolVO storagePool, short capacityType ,long allocated) { + public void createCapacityEntry(StoragePoolVO storagePool, short capacityType, long allocated) { SearchCriteria capacitySC = _capacityDao.createSearchCriteria(); List capacities = _capacityDao.search(capacitySC, null); @@ -1870,19 +1869,20 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, capacityType); capacities = _capacityDao.search(capacitySC, null); - + long totalOverProvCapacity; if (storagePool.getPoolType() == StoragePoolType.NetworkFilesystem) { - totalOverProvCapacity = _overProvisioningFactor.multiply(new BigDecimal(storagePool.getCapacityBytes())).longValue();// All this for the inaccuracy of floats for big number multiplication. - }else { + totalOverProvCapacity = _overProvisioningFactor.multiply(new BigDecimal(storagePool.getCapacityBytes())).longValue();// All +// this for the inaccuracy of floats for big number multiplication. + } else { totalOverProvCapacity = storagePool.getCapacityBytes(); } - + if (capacities.size() == 0) { CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), storagePool.getClusterId(), allocated, totalOverProvCapacity, capacityType); _capacityDao.persist(capacity); } else { - CapacityVO capacity = capacities.get(0); + CapacityVO capacity = capacities.get(0); boolean update = false; if (capacity.getTotalCapacity() != totalOverProvCapacity) { capacity.setTotalCapacity(totalOverProvCapacity); @@ -1896,13 +1896,12 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag _capacityDao.update(capacity.getId(), capacity); } } - s_logger.debug("Successfully set Capacity - " + totalOverProvCapacity + " for capacity type - " +capacityType+ " , DataCenterId - " + s_logger.debug("Successfully set Capacity - " + totalOverProvCapacity + " for capacity type - " + capacityType + " , DataCenterId - " + storagePool.getDataCenterId() + ", HostOrPoolId - " + storagePool.getId() + ", PodId " + storagePool.getPodId()); } - @Override - public List getUpHostsInPool(long poolId){ + public List getUpHostsInPool(long poolId) { SearchCriteria sc = UpHostsInPoolSearch.create(); sc.setParameters("pool", poolId); sc.setJoinParameters("hosts", "status", Status.Up); @@ -1925,8 +1924,8 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (hostIdsToAvoid != null) { hostIds.removeAll(hostIdsToAvoid); } - if ( hostIds == null || hostIds.isEmpty() ) { - throw new StorageUnavailableException("Unable to send command to the pool " + pool.getId() + " due to there is no enabled hosts up in this cluster", pool.getId() ); + if (hostIds == null || hostIds.isEmpty()) { + throw new StorageUnavailableException("Unable to send command to the pool " + pool.getId() + " due to there is no enabled hosts up in this cluster", pool.getId()); } for (Long hostId : hostIds) { try { @@ -1963,35 +1962,35 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (scanLock.lock(3)) { try { // Cleanup primary storage pools - if(_templateCleanupEnabled) { - List storagePools = _storagePoolDao.listAll(); - for (StoragePoolVO pool : storagePools) { - try { - - List unusedTemplatesInPool = _tmpltMgr.getUnusedTemplatesInPool(pool); - s_logger.debug("Storage pool garbage collector found " + unusedTemplatesInPool.size() + " templates to clean up in storage pool: " + pool.getName()); - for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) { - if (templatePoolVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { - s_logger.debug("Storage pool garbage collector is skipping templatePoolVO with ID: " + templatePoolVO.getId() + " because it is not completely downloaded."); - continue; - } - - if (!templatePoolVO.getMarkedForGC()) { - templatePoolVO.setMarkedForGC(true); - _vmTemplatePoolDao.update(templatePoolVO.getId(), templatePoolVO); - s_logger.debug("Storage pool garbage collector has marked templatePoolVO with ID: " + templatePoolVO.getId() + " for garbage collection."); - continue; - } - - _tmpltMgr.evictTemplateFromStoragePool(templatePoolVO); - } - } catch (Exception e) { - s_logger.warn("Problem cleaning up primary storage pool " + pool, e); - } - } - } - - cleanupSecondaryStorage(recurring); + if (_templateCleanupEnabled) { + List storagePools = _storagePoolDao.listAll(); + for (StoragePoolVO pool : storagePools) { + try { + + List unusedTemplatesInPool = _tmpltMgr.getUnusedTemplatesInPool(pool); + s_logger.debug("Storage pool garbage collector found " + unusedTemplatesInPool.size() + " templates to clean up in storage pool: " + pool.getName()); + for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) { + if (templatePoolVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { + s_logger.debug("Storage pool garbage collector is skipping templatePoolVO with ID: " + templatePoolVO.getId() + " because it is not completely downloaded."); + continue; + } + + if (!templatePoolVO.getMarkedForGC()) { + templatePoolVO.setMarkedForGC(true); + _vmTemplatePoolDao.update(templatePoolVO.getId(), templatePoolVO); + s_logger.debug("Storage pool garbage collector has marked templatePoolVO with ID: " + templatePoolVO.getId() + " for garbage collection."); + continue; + } + + _tmpltMgr.evictTemplateFromStoragePool(templatePoolVO); + } + } catch (Exception e) { + s_logger.warn("Problem cleaning up primary storage pool " + pool, e); + } + } + } + + cleanupSecondaryStorage(recurring); List vols = _volsDao.listVolumesToBeDestroyed(); for (VolumeVO vol : vols) { @@ -2009,7 +2008,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag scanLock.releaseRef(); } } - + @DB List findAllVolumeIdInSnapshotTable(Long hostId) { String sql = "SELECT volume_id from snapshots WHERE sechost_id=? GROUP BY volume_id"; @@ -2020,7 +2019,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag PreparedStatement pstmt = null; pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setLong(1, hostId); - rs = pstmt.executeQuery(); + rs = pstmt.executeQuery(); while (rs.next()) { list.add(rs.getLong(1)); } @@ -2031,16 +2030,15 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } } - - - List findAllSnapshotForVolume(Long volumeId) { - String sql = "SELECT backup_snap_id FROM snapshots WHERE volume_id=? and backup_snap_id is not NULL"; + + List findAllSnapshotForVolume(Long volumeId) { + String sql = "SELECT backup_snap_id FROM snapshots WHERE volume_id=? and backup_snap_id is not NULL"; try { Transaction txn = Transaction.currentTxn(); ResultSet rs = null; PreparedStatement pstmt = null; pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, volumeId); + pstmt.setLong(1, volumeId); rs = pstmt.executeQuery(); List list = new ArrayList(); while (rs.next()) { @@ -2052,7 +2050,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag return null; } } - + @Override @DB public void cleanupSecondaryStorage(boolean recurring) { @@ -2176,9 +2174,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } List spes = _storagePoolDao.listBy(primaryStorage.getDataCenterId(), primaryStorage.getPodId(), primaryStorage.getClusterId()); - for( StoragePoolVO sp : spes ) { - if( sp.getStatus() == StoragePoolStatus.PrepareForMaintenance ) { - throw new CloudRuntimeException("Only one storage pool in a cluster can be in PrepareForMaintenance mode, " + sp.getId() + " is already in PrepareForMaintenance mode " ); + for (StoragePoolVO sp : spes) { + if (sp.getStatus() == StoragePoolStatus.PrepareForMaintenance) { + throw new CloudRuntimeException("Only one storage pool in a cluster can be in PrepareForMaintenance mode, " + sp.getId() + " is already in PrepareForMaintenance mode "); } } @@ -2186,9 +2184,8 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag throw new InvalidParameterValueException("Primary storage with id " + primaryStorageId + " is not ready for migration, as the status is:" + primaryStorage.getStatus().toString()); } - List hosts = _resourceMgr.listHostsInClusterByStatus(primaryStorage.getClusterId(), Status.Up); - if( hosts == null || hosts.size() == 0 ) { + if (hosts == null || hosts.size() == 0) { primaryStorage.setStatus(StoragePoolStatus.Maintenance); _storagePoolDao.update(primaryStorageId, primaryStorage); return _storagePoolDao.findById(primaryStorageId); @@ -2198,7 +2195,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag _storagePoolDao.update(primaryStorageId, primaryStorage); } // remove heartbeat - for ( HostVO host : hosts ) { + for (HostVO host : hosts) { ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(false, primaryStorage); final Answer answer = _agentMgr.easySend(host.getId(), cmd); if (answer == null || !answer.getResult()) { @@ -2417,11 +2414,11 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag _storagePoolDao.update(primaryStorageId, primaryStorage); txn.commit(); List hosts = _resourceMgr.listHostsInClusterByStatus(primaryStorage.getClusterId(), Status.Up); - if( hosts == null || hosts.size() == 0 ) { + if (hosts == null || hosts.size() == 0) { return _storagePoolDao.findById(primaryStorageId); - } + } // add heartbeat - for ( HostVO host : hosts ) { + for (HostVO host : hosts) { ModifyStoragePoolCommand msPoolCmd = new ModifyStoragePoolCommand(true, primaryStorage); final Answer answer = _agentMgr.easySend(host.getId(), msPoolCmd); if (answer == null || !answer.getResult()) { @@ -2555,37 +2552,37 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DELETE, eventDescription = "deleting volume") public boolean deleteVolume(long volumeId) throws ConcurrentOperationException { Account caller = UserContext.current().getCaller(); - + // Check that the volume ID is valid VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException("Unable to aquire volume with ID: " + volumeId); } - + if (!_snapshotMgr.canOperateOnVolume(volume)) { - throw new InvalidParameterValueException("There are snapshot creating on it, Unable to delete the volume"); + throw new InvalidParameterValueException("There are snapshot creating on it, Unable to delete the volume"); } - - //permission check + + // permission check _accountMgr.checkAccess(caller, null, true, volume); // Check that the volume is not currently attached to any VM if (volume.getInstanceId() != null) { - throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM."); + throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM."); } // Check that the volume is not already destroyed if (volume.getState() != Volume.State.Destroy) { - if (!destroyVolume(volume)) { - return false; - } + if (!destroyVolume(volume)) { + return false; + } } try { - expungeVolume(volume); + expungeVolume(volume); } catch (Exception e) { - s_logger.warn("Failed to expunge volume:", e); - return false; + s_logger.warn("Failed to expunge volume:", e); + return false; } return true; @@ -2594,7 +2591,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag private boolean validateVolumeSizeRange(long size) { if (size < 0 || (size > 0 && size < (1024 * 1024 * 1024))) { throw new InvalidParameterValueException("Please specify a size of at least 1 Gb."); - } else if (size > (_maxVolumeSizeInGb * 1024 * 1024 * 1024) ) { + } else if (size > (_maxVolumeSizeInGb * 1024 * 1024 * 1024)) { throw new InvalidParameterValueException("volume size " + size + ", but the maximum size allowed is " + _maxVolumeSizeInGb + " Gb."); } @@ -2717,196 +2714,195 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } } } - + @DB @Override public Volume migrateVolume(Long volumeId, Long storagePoolId) throws ConcurrentOperationException { - VolumeVO vol = _volsDao.findById(volumeId); - if (vol == null) { - throw new InvalidParameterValueException("Failed to find the volume id: " + volumeId); - } - - if (vol.getState() != Volume.State.Ready) { - throw new InvalidParameterValueException("Volume must be in ready state"); - } - - if (vol.getInstanceId() != null) { - throw new InvalidParameterValueException("Volume needs to be dettached from VM"); - } - - StoragePool destPool = _storagePoolDao.findById(storagePoolId); - if (destPool == null) { - throw new InvalidParameterValueException("Faild to find the destination storage pool: " + storagePoolId); - } - - List vols = new ArrayList(); - vols.add(vol); - - migrateVolumes(vols, destPool); - return vol; + VolumeVO vol = _volsDao.findById(volumeId); + if (vol == null) { + throw new InvalidParameterValueException("Failed to find the volume id: " + volumeId); + } + + if (vol.getState() != Volume.State.Ready) { + throw new InvalidParameterValueException("Volume must be in ready state"); + } + + if (vol.getInstanceId() != null) { + throw new InvalidParameterValueException("Volume needs to be dettached from VM"); + } + + StoragePool destPool = _storagePoolDao.findById(storagePoolId); + if (destPool == null) { + throw new InvalidParameterValueException("Faild to find the destination storage pool: " + storagePoolId); + } + + List vols = new ArrayList(); + vols.add(vol); + + migrateVolumes(vols, destPool); + return vol; } - + @DB public boolean migrateVolumes(List volumes, StoragePool destPool) throws ConcurrentOperationException { - Transaction txn = Transaction.currentTxn(); - txn.start(); - - boolean transitResult = false; - long checkPointTaskId = -1; - try { - List volIds = new ArrayList(); - for (Volume volume : volumes) { - if (!_snapshotMgr.canOperateOnVolume((VolumeVO)volume)) { - throw new CloudRuntimeException("There are snapshots creating on this volume, can not move this volume"); - } - - try { - if (!stateTransitTo(volume, Volume.Event.MigrationRequested)) { - throw new ConcurrentOperationException("Failed to transit volume state"); - } - } catch (NoTransitionException e) { - s_logger.debug("Failed to set state into migrate: " + e.toString()); - throw new CloudRuntimeException("Failed to set state into migrate: " + e.toString()); - } - volIds.add(volume.getId()); - } - - checkPointTaskId = _checkPointMgr.pushCheckPoint(new StorageMigrationCleanupMaid(StorageMigrationCleanupMaid.StorageMigrationState.MIGRATING, volIds)); - transitResult = true; - } finally { - if (!transitResult) { - txn.rollback(); - } else { - txn.commit(); - } - } - - //At this stage, nobody can modify volumes. Send the copyvolume command - List> destroyCmds = new ArrayList>(); - List answers = new ArrayList(); - try { - for (Volume volume: volumes) { - String secondaryStorageURL = getSecondaryStorageURL(volume.getDataCenterId()); - StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId()); - CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool, secondaryStorageURL, true, _copyvolumewait); - CopyVolumeAnswer cvAnswer; - try { - cvAnswer = (CopyVolumeAnswer) sendToPool(srcPool, cvCmd); - } catch (StorageUnavailableException e1) { - throw new CloudRuntimeException("Failed to copy the volume from the source primary storage pool to secondary storage.", e1); - } + Transaction txn = Transaction.currentTxn(); + txn.start(); - if (cvAnswer == null || !cvAnswer.getResult()) { - throw new CloudRuntimeException("Failed to copy the volume from the source primary storage pool to secondary storage."); - } + boolean transitResult = false; + long checkPointTaskId = -1; + try { + List volIds = new ArrayList(); + for (Volume volume : volumes) { + if (!_snapshotMgr.canOperateOnVolume((VolumeVO) volume)) { + throw new CloudRuntimeException("There are snapshots creating on this volume, can not move this volume"); + } - String secondaryStorageVolumePath = cvAnswer.getVolumePath(); + try { + if (!stateTransitTo(volume, Volume.Event.MigrationRequested)) { + throw new ConcurrentOperationException("Failed to transit volume state"); + } + } catch (NoTransitionException e) { + s_logger.debug("Failed to set state into migrate: " + e.toString()); + throw new CloudRuntimeException("Failed to set state into migrate: " + e.toString()); + } + volIds.add(volume.getId()); + } - // Copy the volume from secondary storage to the destination storage - // pool - cvCmd = new CopyVolumeCommand(volume.getId(), secondaryStorageVolumePath, destPool, secondaryStorageURL, false, _copyvolumewait); - try { - cvAnswer = (CopyVolumeAnswer) sendToPool(destPool, cvCmd); - } catch (StorageUnavailableException e1) { - throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); - } + checkPointTaskId = _checkPointMgr.pushCheckPoint(new StorageMigrationCleanupMaid(StorageMigrationCleanupMaid.StorageMigrationState.MIGRATING, volIds)); + transitResult = true; + } finally { + if (!transitResult) { + txn.rollback(); + } else { + txn.commit(); + } + } - if (cvAnswer == null || !cvAnswer.getResult()) { - throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); - } - - answers.add(cvAnswer); - destroyCmds.add(new Pair(srcPool, new DestroyCommand(srcPool, volume, null))); - } - } finally { - if (answers.size() != volumes.size()) { - //this means one of copying volume failed - for (Volume volume : volumes) { - try { - stateTransitTo(volume, Volume.Event.OperationFailed); - } catch (NoTransitionException e) { - s_logger.debug("Failed to change volume state: " + e.toString()); - } - } - _checkPointMgr.popCheckPoint(checkPointTaskId); - } else { - //Need a transaction, make sure all the volumes get migrated to new storage pool - txn = Transaction.currentTxn(); - txn.start(); - - transitResult = false; - try { - for (int i = 0; i < volumes.size(); i++) { - CopyVolumeAnswer answer = answers.get(i); - VolumeVO volume = (VolumeVO)volumes.get(i); - Long oldPoolId = volume.getPoolId(); - volume.setPath(answer.getVolumePath()); - volume.setFolder(destPool.getPath()); - volume.setPodId(destPool.getPodId()); - volume.setPoolId(destPool.getId()); - volume.setLastPoolId(oldPoolId); - volume.setPodId(destPool.getPodId()); - try { - stateTransitTo(volume, Volume.Event.OperationSucceeded); - } catch (NoTransitionException e) { - s_logger.debug("Failed to change volume state: " + e.toString()); - throw new CloudRuntimeException("Failed to change volume state: " + e.toString()); - } - } - transitResult = true; - try { - _checkPointMgr.popCheckPoint(checkPointTaskId); - } catch (Exception e) { + // At this stage, nobody can modify volumes. Send the copyvolume command + List> destroyCmds = new ArrayList>(); + List answers = new ArrayList(); + try { + for (Volume volume : volumes) { + String secondaryStorageURL = getSecondaryStorageURL(volume.getDataCenterId()); + StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId()); + CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool, secondaryStorageURL, true, _copyvolumewait); + CopyVolumeAnswer cvAnswer; + try { + cvAnswer = (CopyVolumeAnswer) sendToPool(srcPool, cvCmd); + } catch (StorageUnavailableException e1) { + throw new CloudRuntimeException("Failed to copy the volume from the source primary storage pool to secondary storage.", e1); + } - } - } finally { - if (!transitResult) { - txn.rollback(); - } else { - txn.commit(); - } - } - - - } - } - - //all the volumes get migrated to new storage pool, need to delete the copy on old storage pool - for (Pair cmd : destroyCmds) { - try { - Answer cvAnswer = sendToPool(cmd.first(), cmd.second()); - } catch (StorageUnavailableException e) { - s_logger.debug("Unable to delete the old copy on storage pool: " + e.toString()); - } - } - return true; + if (cvAnswer == null || !cvAnswer.getResult()) { + throw new CloudRuntimeException("Failed to copy the volume from the source primary storage pool to secondary storage."); + } + + String secondaryStorageVolumePath = cvAnswer.getVolumePath(); + + // Copy the volume from secondary storage to the destination storage + // pool + cvCmd = new CopyVolumeCommand(volume.getId(), secondaryStorageVolumePath, destPool, secondaryStorageURL, false, _copyvolumewait); + try { + cvAnswer = (CopyVolumeAnswer) sendToPool(destPool, cvCmd); + } catch (StorageUnavailableException e1) { + throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); + } + + if (cvAnswer == null || !cvAnswer.getResult()) { + throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); + } + + answers.add(cvAnswer); + destroyCmds.add(new Pair(srcPool, new DestroyCommand(srcPool, volume, null))); + } + } finally { + if (answers.size() != volumes.size()) { + // this means one of copying volume failed + for (Volume volume : volumes) { + try { + stateTransitTo(volume, Volume.Event.OperationFailed); + } catch (NoTransitionException e) { + s_logger.debug("Failed to change volume state: " + e.toString()); + } + } + _checkPointMgr.popCheckPoint(checkPointTaskId); + } else { + // Need a transaction, make sure all the volumes get migrated to new storage pool + txn = Transaction.currentTxn(); + txn.start(); + + transitResult = false; + try { + for (int i = 0; i < volumes.size(); i++) { + CopyVolumeAnswer answer = answers.get(i); + VolumeVO volume = (VolumeVO) volumes.get(i); + Long oldPoolId = volume.getPoolId(); + volume.setPath(answer.getVolumePath()); + volume.setFolder(destPool.getPath()); + volume.setPodId(destPool.getPodId()); + volume.setPoolId(destPool.getId()); + volume.setLastPoolId(oldPoolId); + volume.setPodId(destPool.getPodId()); + try { + stateTransitTo(volume, Volume.Event.OperationSucceeded); + } catch (NoTransitionException e) { + s_logger.debug("Failed to change volume state: " + e.toString()); + throw new CloudRuntimeException("Failed to change volume state: " + e.toString()); + } + } + transitResult = true; + try { + _checkPointMgr.popCheckPoint(checkPointTaskId); + } catch (Exception e) { + + } + } finally { + if (!transitResult) { + txn.rollback(); + } else { + txn.commit(); + } + } + + } + } + + // all the volumes get migrated to new storage pool, need to delete the copy on old storage pool + for (Pair cmd : destroyCmds) { + try { + Answer cvAnswer = sendToPool(cmd.first(), cmd.second()); + } catch (StorageUnavailableException e) { + s_logger.debug("Unable to delete the old copy on storage pool: " + e.toString()); + } + } + return true; } - + @Override public boolean StorageMigration(VirtualMachineProfile vm, StoragePool destPool) throws ConcurrentOperationException { - List vols = _volsDao.findUsableVolumesForInstance(vm.getId()); - List volumesNeedToMigrate = new ArrayList(); - - for (VolumeVO volume : vols) { - if (volume.getState() != Volume.State.Ready) { - s_logger.debug("volume: " + volume.getId() + " is in " + volume.getState() + " state"); - throw new CloudRuntimeException("volume: " + volume.getId() + " is in " + volume.getState() + " state"); - } - - if (volume.getPoolId() == destPool.getId()) { - s_logger.debug("volume: " + volume.getId() + " is on the same storage pool: " + destPool.getId()); - continue; - } - - volumesNeedToMigrate.add(volume); - } - - if (volumesNeedToMigrate.isEmpty()) { - s_logger.debug("No volume need to be migrated"); - return true; - } + List vols = _volsDao.findUsableVolumesForInstance(vm.getId()); + List volumesNeedToMigrate = new ArrayList(); - return migrateVolumes(volumesNeedToMigrate, destPool); + for (VolumeVO volume : vols) { + if (volume.getState() != Volume.State.Ready) { + s_logger.debug("volume: " + volume.getId() + " is in " + volume.getState() + " state"); + throw new CloudRuntimeException("volume: " + volume.getId() + " is in " + volume.getState() + " state"); + } + + if (volume.getPoolId() == destPool.getId()) { + s_logger.debug("volume: " + volume.getId() + " is on the same storage pool: " + destPool.getId()); + continue; + } + + volumesNeedToMigrate.add(volume); + } + + if (volumesNeedToMigrate.isEmpty()) { + s_logger.debug("No volume need to be migrated"); + return true; + } + + return migrateVolumes(volumesNeedToMigrate, destPool); } @Override @@ -2953,7 +2949,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag throw new StorageUnavailableException("Volume has no pool associate and also no storage pool assigned in DeployDestination, Unable to create " + vol, Volume.class, vol.getId()); } if (s_logger.isDebugEnabled()) { - s_logger.debug("No need to recreate the volume: "+vol+ ", since it already has a pool assigned: "+vol.getPoolId()+", adding disk to VM"); + s_logger.debug("No need to recreate the volume: " + vol + ", since it already has a pool assigned: " + vol.getPoolId() + ", adding disk to VM"); } StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); vm.addDisk(new VolumeTO(vol, pool)); @@ -2980,17 +2976,17 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag try { stateTransitTo(newVol, Volume.Event.CreateRequested); } catch (NoTransitionException e) { - throw new CloudRuntimeException("Unable to create " + e.toString()); - } + throw new CloudRuntimeException("Unable to create " + e.toString()); + } Pair created = createVolume(newVol, _diskOfferingDao.findById(newVol.getDiskOfferingId()), vm, vols, dest); if (created == null) { Long poolId = newVol.getPoolId(); newVol.setPoolId(null); try { - stateTransitTo(newVol, Volume.Event.OperationFailed); + stateTransitTo(newVol, Volume.Event.OperationFailed); } catch (NoTransitionException e) { - throw new CloudRuntimeException("Unable to update the failure on a volume: " + newVol, e); - } + throw new CloudRuntimeException("Unable to update the failure on a volume: " + newVol, e); + } throw new StorageUnavailableException("Unable to create " + newVol, poolId == null ? -1L : poolId); } created.first().setDeviceId(newVol.getDeviceId().intValue()); @@ -3000,7 +2996,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag newVol.setPoolType(created.second().getPoolType()); newVol.setPodId(created.second().getPodId()); try { - stateTransitTo(newVol, Volume.Event.OperationSucceeded); + stateTransitTo(newVol, Volume.Event.OperationSucceeded); } catch (NoTransitionException e) { throw new CloudRuntimeException("Unable to update an CREATE operation succeeded on volume " + newVol, e); } @@ -3017,19 +3013,19 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); try { - stateTransitTo(existingVolume, Volume.Event.DestroyRequested); + stateTransitTo(existingVolume, Volume.Event.DestroyRequested); } catch (NoTransitionException e) { - s_logger.debug("Unable to destroy existing volume: " + e.toString()); + s_logger.debug("Unable to destroy existing volume: " + e.toString()); } Long templateIdToUse = null; Long volTemplateId = existingVolume.getTemplateId(); long vmTemplateId = vm.getTemplateId(); if (volTemplateId != null && volTemplateId.longValue() != vmTemplateId) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("switchVolume: Old Volume's templateId: "+volTemplateId + " does not match the VM's templateId: "+vmTemplateId+", updating templateId in the new Volume"); - } - templateIdToUse = vmTemplateId; + if (s_logger.isDebugEnabled()) { + s_logger.debug("switchVolume: Old Volume's templateId: " + volTemplateId + " does not match the VM's templateId: " + vmTemplateId + ", updating templateId in the new Volume"); + } + templateIdToUse = vmTemplateId; } VolumeVO newVolume = allocateDuplicateVolume(existingVolume, templateIdToUse); txn.commit(); @@ -3203,7 +3199,6 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } } } - @Override public void onManagementNodeJoined(List nodeList, long selfNodeId) { @@ -3245,24 +3240,24 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (zoneId != null) { sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); } - + List hosts = new ArrayList(); - if(hostId != null){ - hosts.add(ApiDBUtils.findHostById(hostId)); - }else{ - hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); + if (hostId != null) { + hosts.add(ApiDBUtils.findHostById(hostId)); + } else { + hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId); } - CapacityVO capacity = new CapacityVO(hostId, zoneId, null, null, 0, 0, CapacityVO.CAPACITY_TYPE_SECONDARY_STORAGE); + CapacityVO capacity = new CapacityVO(hostId, zoneId, null, null, 0, 0, CapacityVO.CAPACITY_TYPE_SECONDARY_STORAGE); for (HostVO host : hosts) { StorageStats stats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); if (stats == null) { continue; } capacity.setUsedCapacity(stats.getByteUsed() + capacity.getUsedCapacity()); - capacity.setTotalCapacity(stats.getCapacityBytes() + capacity.getTotalCapacity()); + capacity.setTotalCapacity(stats.getCapacityBytes() + capacity.getTotalCapacity()); } - + return capacity; } @@ -3282,7 +3277,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (clusterId != null) { sc.addAnd("clusterId", SearchCriteria.Op.EQ, clusterId); } - + if (poolId != null) { sc.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, poolId); } @@ -3291,7 +3286,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } else { pools = _storagePoolDao.search(sc, null); } - + CapacityVO capacity = new CapacityVO(poolId, zoneId, podId, clusterId, 0, 0, CapacityVO.CAPACITY_TYPE_STORAGE); for (StoragePoolVO storagePool : pools) { StorageStats stats = ApiDBUtils.getStoragePoolStatistics(storagePool.getId()); @@ -3303,11 +3298,8 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } return capacity; } - - @Override - public StoragePool getStoragePool(long id) { return _storagePoolDao.findById(id); } @@ -3319,7 +3311,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag List secHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dcId); - //FIXME, for cloudzone, the local secondary storoge + // FIXME, for cloudzone, the local secondary storoge if (pool.isLocal() && pool.getPoolType() == StoragePoolType.Filesystem && secHosts.isEmpty()) { List sphs = _storagePoolHostDao.listByPoolId(pool.getId()); if (!sphs.isEmpty()) { @@ -3336,13 +3328,13 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag } if (podId != null) { List templHosts = _templateHostDao.listByTemplateStatus(templateId, dcId, podId, VMTemplateStorageResourceAssoc.Status.DOWNLOADED); - if( templHosts != null && ! templHosts.isEmpty()) { + if (templHosts != null && !templHosts.isEmpty()) { Collections.shuffle(templHosts); return templHosts.get(0); } } - List templHosts = _templateHostDao.listByTemplateStatus(templateId, dcId, VMTemplateStorageResourceAssoc.Status.DOWNLOADED); - if( templHosts != null && ! templHosts.isEmpty()) { + List templHosts = _templateHostDao.listByTemplateStatus(templateId, dcId, VMTemplateStorageResourceAssoc.Status.DOWNLOADED); + if (templHosts != null && !templHosts.isEmpty()) { Collections.shuffle(templHosts); return templHosts.get(0); } @@ -3357,11 +3349,12 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag sc.setJoinParameters("vmVolume", "poolId", storagePoolId); return _vmInstanceDao.search(sc, null); } + @Override @DB public StoragePoolVO findLocalStorageOnHost(long hostId) { SearchCriteria sc = LocalStorageSearch.create(); - sc.setParameters("type", new Object[]{StoragePoolType.Filesystem, StoragePoolType.LVM}); + sc.setParameters("type", new Object[] { StoragePoolType.Filesystem, StoragePoolType.LVM }); sc.setJoinParameters("poolHost", "hostId", hostId); List storagePools = _storagePoolDao.search(sc, null); if (!storagePools.isEmpty()) { @@ -3373,48 +3366,48 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override public Host updateSecondaryStorage(long secStorageId, String newUrl) { - HostVO secHost = _hostDao.findById(secStorageId); - if (secHost == null) { - throw new InvalidParameterValueException("Can not find out the secondary storage id: " + secStorageId); - } + HostVO secHost = _hostDao.findById(secStorageId); + if (secHost == null) { + throw new InvalidParameterValueException("Can not find out the secondary storage id: " + secStorageId); + } - if (secHost.getType() != Host.Type.SecondaryStorage) { - throw new InvalidParameterValueException("host: " + secStorageId + " is not a secondary storage"); - } - - URI uri = null; - try { - uri = new URI(UriUtils.encodeURIComponent(newUrl)); - if (uri.getScheme() == null) { - throw new InvalidParameterValueException("uri.scheme is null " + newUrl + ", add nfs:// as a prefix"); - } else if (uri.getScheme().equalsIgnoreCase("nfs")) { - if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) { - throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path"); - } - } - } catch (URISyntaxException e) { - throw new InvalidParameterValueException(newUrl + " is not a valid uri"); - } + if (secHost.getType() != Host.Type.SecondaryStorage) { + throw new InvalidParameterValueException("host: " + secStorageId + " is not a secondary storage"); + } - String oldUrl = secHost.getStorageUrl(); + URI uri = null; + try { + uri = new URI(UriUtils.encodeURIComponent(newUrl)); + if (uri.getScheme() == null) { + throw new InvalidParameterValueException("uri.scheme is null " + newUrl + ", add nfs:// as a prefix"); + } else if (uri.getScheme().equalsIgnoreCase("nfs")) { + if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) { + throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path"); + } + } + } catch (URISyntaxException e) { + throw new InvalidParameterValueException(newUrl + " is not a valid uri"); + } - URI oldUri = null; - try { - oldUri = new URI(UriUtils.encodeURIComponent(oldUrl)); - if (!oldUri.getScheme().equalsIgnoreCase(uri.getScheme())) { - throw new InvalidParameterValueException("can not change old scheme:" + oldUri.getScheme() + " to " + uri.getScheme()); - } - } catch (URISyntaxException e) { - s_logger.debug("Failed to get uri from " + oldUrl); - } + String oldUrl = secHost.getStorageUrl(); - secHost.setStorageUrl(newUrl); - secHost.setGuid(newUrl); - secHost.setName(newUrl); - _hostDao.update(secHost.getId(), secHost); - return secHost; + URI oldUri = null; + try { + oldUri = new URI(UriUtils.encodeURIComponent(oldUrl)); + if (!oldUri.getScheme().equalsIgnoreCase(uri.getScheme())) { + throw new InvalidParameterValueException("can not change old scheme:" + oldUri.getScheme() + " to " + uri.getScheme()); + } + } catch (URISyntaxException e) { + s_logger.debug("Failed to get uri from " + oldUrl); + } + + secHost.setStorageUrl(newUrl); + secHost.setGuid(newUrl); + secHost.setName(newUrl); + _hostDao.update(secHost.getId(), secHost); + return secHost; } - + @Override public List searchForVolumes(ListVolumesCmd cmd) { Account caller = UserContext.current().getCaller(); @@ -3433,19 +3426,19 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag podId = cmd.getPodId(); // host = cmd.getHostId(); TODO } - + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll()); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll()); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(VolumeVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); // hack for now, this should be done better but due to needing a join I opted to // do this quickly and worry about making it pretty later SearchBuilder sb = _volumeDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("volumeType", sb.entity().getVolumeType(), SearchCriteria.Op.LIKE); @@ -3464,11 +3457,11 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag vmSearch.and("type", vmSearch.entity().getType(), SearchCriteria.Op.NIN); vmSearch.or("nulltype", vmSearch.entity().getType(), SearchCriteria.Op.NULL); sb.join("vmSearch", vmSearch, sb.entity().getInstanceId(), vmSearch.entity().getId(), JoinBuilder.JoinType.LEFTOUTER); - + // now set the SC criteria... SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + if (keyword != null) { SearchCriteria ssc = _volumeDao.createSearchCriteria(); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -3480,13 +3473,13 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag if (name != null) { sc.setParameters("name", "%" + name + "%"); } - + sc.setJoinParameters("diskOfferingSearch", "systemUse", 1); if (id != null) { sc.setParameters("id", id); } - + if (type != null) { sc.setParameters("volumeType", "%" + type + "%"); } @@ -3508,4 +3501,5 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag return _volumeDao.search(sc, searchFilter); } + } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index 494181096e4..eba88911698 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -190,7 +190,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag private VpnUserDao _vpnUser; @Inject private DataCenterDao _dcDao; - @Inject + @Inject private DomainManager _domainMgr; @Inject private ProjectManager _projectMgr; @@ -204,7 +204,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag private ProjectAccountDao _projectAccountDao; @Inject private IPAddressDao _ipAddressDao; - + private Adapters _userAuthenticators; private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("AccountChecker")); @@ -235,7 +235,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag String value = configs.get(Config.AccountCleanupInterval.key()); _cleanupInterval = NumbersUtil.parseInt(value, 60 * 60 * 24); // 1 hour. - + _userAuthenticators = locator.getAdapters(UserAuthenticator.class); if (_userAuthenticators == null || !_userAuthenticators.isSet()) { s_logger.error("Unable to find an user authenticator."); @@ -303,12 +303,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public void checkAccess(Account caller, AccessType accessType, boolean sameOwner, ControlledEntity... entities) { - + if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(caller.getType())) { - //no need to make permission checks if the system/root admin makes the call + // no need to make permission checks if the system/root admin makes the call if (s_logger.isTraceEnabled()) { s_logger.trace("No need to make permission check for System/RootAdmin account, returning true"); - } + } return; } @@ -318,13 +318,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag for (ControlledEntity entity : entities) { long domainId = entity.getDomainId(); - if (entity.getAccountId() != -1 && domainId == -1){ // If account exists domainId should too so calculate it. This condition might be hit for templates or entities which miss domainId in their tables + if (entity.getAccountId() != -1 && domainId == -1) { // If account exists domainId should too so calculate +// it. This condition might be hit for templates or entities which miss domainId in their tables Account account = ApiDBUtils.findAccountById(entity.getAccountId()); - domainId = account != null ? account.getDomainId() : -1 ; + domainId = account != null ? account.getDomainId() : -1; } if (entity.getAccountId() != -1 && domainId != -1 && !(entity instanceof VirtualMachineTemplate) && !(accessType != null && accessType == AccessType.UseNetwork)) { List toBeChecked = domains.get(entity.getDomainId()); - //for templates, we don't have to do cross domains check + // for templates, we don't have to do cross domains check if (toBeChecked == null) { toBeChecked = new ArrayList(); domains.put(domainId, toBeChecked); @@ -341,14 +342,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag break; } } - + if (sameOwner) { - if (ownerId == null) { + if (ownerId == null) { ownerId = entity.getAccountId(); } else if (ownerId.longValue() != entity.getAccountId()) { - throw new PermissionDeniedException("Entity " + entity + " and entity " + prevEntity + " belong to different accounts"); + throw new PermissionDeniedException("Entity " + entity + " and entity " + prevEntity + " belong to different accounts"); } - prevEntity = entity; + prevEntity = entity; } if (!granted) { @@ -359,7 +360,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag for (Map.Entry> domain : domains.entrySet()) { for (SecurityChecker checker : _securityCheckers) { - Domain d = _domainMgr.getDomain(domain.getKey()); + Domain d = _domainMgr.getDomain(domain.getKey()); if (d == null || d.getRemoved() != null) { throw new PermissionDeniedException("Domain is not found.", caller, domain.getValue()); } @@ -371,9 +372,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } } - - //check that resources belong to the same account - + + // check that resources belong to the same account + } @Override @@ -509,7 +510,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.debug("Expunging # of vms (accountId=" + accountId + "): " + vms.size()); } - //no need to catch exception at this place as expunging vm should pass in order to perform further cleanup + // no need to catch exception at this place as expunging vm should pass in order to perform further cleanup for (UserVmVO vm : vms) { if (!_vmMgr.expunge(vm, callerUserId, caller)) { s_logger.error("Unable to expunge vm: " + vm.getId()); @@ -569,18 +570,19 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } } - - //release ip addresses belonging to the account + + // release ip addresses belonging to the account List ipsToRelease = _ipAddressDao.listByAccount(accountId); for (IpAddress ip : ipsToRelease) { - s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup"); - if (!_networkMgr.releasePublicIpAddress(ip.getId(), callerUserId, caller)) { - s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup"); - accountCleanupNeeded = true; - } + s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup"); + if (!_networkMgr.releasePublicIpAddress(ip.getId(), callerUserId, caller)) { + s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup"); + accountCleanupNeeded = true; + } } - // delete account specific Virtual vlans (belong to system Public Network) - only when networks are cleaned up + // delete account specific Virtual vlans (belong to system Public Network) - only when networks are cleaned +// up // successfully if (networksDeleted) { if (!_configMgr.deleteAccountSpecificVirtualRanges(accountId)) { @@ -595,7 +597,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.warn("Failed to cleanup account " + account + " due to ", ex); accountCleanupNeeded = true; return true; - }finally { + } finally { s_logger.info("Cleanup for account " + account.getId() + (accountCleanupNeeded ? " is needed." : " is not needed.")); if (accountCleanupNeeded) { _accountDao.markForCleanup(accountId); @@ -620,7 +622,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag AccountVO acctForUpdate = _accountDao.createForUpdate(); acctForUpdate.setState(State.disabled); success = _accountDao.update(Long.valueOf(accountId), acctForUpdate); - + if (success) { if (!doDisableAccount(accountId)) { s_logger.warn("Failed to disable account " + account + " resources as a part of disableAccount call, marking the account for cleanup"); @@ -658,54 +660,54 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override @DB @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account") - public UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, Map details) { - + public UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, + Map details) { + if (accountName == null) { accountName = userName; } if (domainId == null) { domainId = DomainVO.ROOT_DOMAIN; } - - //Validate domain + + // Validate domain Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account"); } - - //Check permissions - checkAccess(UserContext.current().getCaller(), domain); + // Check permissions + checkAccess(UserContext.current().getCaller(), domain); if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) { throw new InvalidParameterValueException("The user " + userName + " already exists in domain " + domainId); } - + 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 \"-\""); } } - + Transaction txn = Transaction.currentTxn(); txn.start(); - - //create account + + // create account Account account = createAccount(accountName, accountType, domainId, networkDomain, details); long accountId = account.getId(); - //create the first user for the account + // create the first user for the account UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone); - - if(accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN){ - //set registration token + + if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + // set registration token byte[] bytes = (domainId + accountName + userName + System.currentTimeMillis()).getBytes(); String registrationToken = UUID.nameUUIDFromBytes(bytes).toString(); user.setRegistrationToken(registrationToken); } - + txn.commit(); return _userAccountDao.findById(user.getId()); } @@ -717,20 +719,20 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId == null) { domainId = Domain.ROOT_DOMAIN; } - + Domain domain = _domainMgr.getDomain(domainId); - if (domain == null) { + if (domain == null) { throw new CloudRuntimeException("The domain " + domainId + " does not exist; unable to create user"); } else if (domain.getState().equals(Domain.State.Inactive)) { throw new CloudRuntimeException("The user cannot be created as domain " + domain.getName() + " is being deleted"); } - + checkAccess(UserContext.current().getCaller(), domain); - + Account account = _accountDao.findEnabledAccount(accountName, domainId); if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain id=" + domainId + " to create user"); - } + } if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) { throw new CloudRuntimeException("The user " + userName + " already exists in domain " + domainId); @@ -767,8 +769,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // If the account is an admin type, return an error. We do not allow this Account account = _accountDao.findById(user.getAccountId()); - - //don't allow updating project account + + // don't allow updating project account if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("unable to find user by id"); } @@ -786,7 +788,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag user.setLastname(lastName); } if (userName != null) { - //don't allow to have same user names in the same domain + // don't allow to have same user names in the same domain List duplicatedUsers = _userDao.findUsersLike(userName); for (UserVO duplicatedUser : duplicatedUsers) { if (duplicatedUser.getId() != user.getId()) { @@ -796,7 +798,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } } - + user.setUsername(userName); } if (password != null) { @@ -815,7 +817,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag user.setSecretKey(secretKey); } - if (s_logger.isDebugEnabled()) { s_logger.debug("updating user with id: " + id); } @@ -833,7 +834,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } } - + _userDao.update(id, user); } catch (Throwable th) { s_logger.error("error updating user", th); @@ -852,19 +853,19 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (user == null || user.getRemoved() != null) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); } - + Account account = _accountDao.findById(user.getAccountId()); - - //don't allow disabling user belonging to project's account + + // don't allow disabling user belonging to project's account if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); } - + // If the user is a System user, return an error if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new InvalidParameterValueException("User id : " + userId + " is a system user, disabling is not allowed"); } - + checkAccess(caller, null, true, account); boolean success = doSetUserStatus(userId, State.disabled); @@ -876,7 +877,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } - @Override @DB + @Override + @DB @ActionEvent(eventType = EventTypes.EVENT_USER_ENABLE, eventDescription = "enabling User") public UserAccount enableUser(long userId) { @@ -887,13 +889,13 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (user == null || user.getRemoved() != null) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); } - + Account account = _accountDao.findById(user.getAccountId()); - + if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); } - + // If the user is a System user, return an error if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new InvalidParameterValueException("User id : " + userId + " is a system user, enabling is not allowed"); @@ -903,12 +905,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); - + boolean success = doSetUserStatus(userId, State.enabled); // make sure the account is enabled too success = success && enableAccount(user.getAccountId()); - + txn.commit(); if (success) { @@ -927,24 +929,25 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag User user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { throw new InvalidParameterValueException("Unable to find user by id"); - } - + } + Account account = _accountDao.findById(user.getAccountId()); - - //don't allow to lock user of the account of type Project + + // don't allow to lock user of the account of type Project if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find user by id"); } - + // If the user is a System user, return an error. We do not allow this if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new PermissionDeniedException("user id : " + userId + " is a system user, locking is not allowed"); } - + checkAccess(caller, null, true, account); // make sure the account is enabled too - // if the user is either locked already or disabled already, don't change state...only lock currently enabled users + // if the user is either locked already or disabled already, don't change state...only lock currently enabled +// users boolean success = true; if (user.getState().equals(State.locked)) { // already locked...no-op @@ -986,53 +989,53 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag UserContext ctx = UserContext.current(); long callerUserId = ctx.getCallerUserId(); Account caller = ctx.getCaller(); - + // If the user is a System user, return an error. We do not allow this AccountVO account = _accountDao.findById(accountId); - + if (account.getRemoved() != null) { s_logger.info("The account:" + account.getAccountName() + " is already removed"); return true; } - + // don't allow removing Project account if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("The specified account does not exist in the system"); } - + checkAccess(caller, null, true, account); - + if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new PermissionDeniedException("Account id : " + accountId + " is a system account, delete is not allowed"); } - - //Account that manages project(s) can't be removed + + // Account that manages project(s) can't be removed List managedProjectIds = _projectAccountDao.listAdministratedProjects(accountId); if (!managedProjectIds.isEmpty()) { - StringBuilder projectIds = new StringBuilder(); - for (Long projectId : managedProjectIds) { - projectIds.append(projectId + ", "); - } - - throw new InvalidParameterValueException("The account id=" + accountId + " manages project(s) with ids " + projectIds + "and can't be removed"); + StringBuilder projectIds = new StringBuilder(); + for (Long projectId : managedProjectIds) { + projectIds.append(projectId + ", "); + } + + throw new InvalidParameterValueException("The account id=" + accountId + " manages project(s) with ids " + projectIds + "and can't be removed"); } - + return deleteAccount(account, callerUserId, caller); } @Override public AccountVO enableAccount(String accountName, Long domainId, Long accountId) { - + // Check if account exists Account account = null; - if(accountId != null){ + if (accountId != null) { account = _accountDao.findById(accountId); - }else{ + } else { account = _accountDao.findActiveAccount(accountName, domainId); } - + if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } // Don't allow to modify system account @@ -1048,7 +1051,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (success) { return _accountDao.findById(account.getId()); } else { - throw new CloudRuntimeException("Unable to enable account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); + throw new CloudRuntimeException("Unable to enable account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } } @@ -1056,20 +1059,20 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "locking account", async = true) public AccountVO lockAccount(String accountName, Long domainId, Long accountId) { Account caller = UserContext.current().getCaller(); - + Account account = null; - if(accountId != null){ + if (accountId != null) { account = _accountDao.findById(accountId); - }else{ + } else { account = _accountDao.findActiveAccount(accountName, domainId); } - + if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find active account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); + throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } - + checkAccess(caller, null, true, account); - + // don't allow modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new InvalidParameterValueException("can not lock system account"); @@ -1078,7 +1081,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (lockAccount(account.getId())) { return _accountDao.findById(account.getId()); } else { - throw new CloudRuntimeException("Unable to lock account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); + throw new CloudRuntimeException("Unable to lock account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } } @@ -1086,48 +1089,49 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "disabling account", async = true) public AccountVO disableAccount(String accountName, Long domainId, Long accountId) throws ConcurrentOperationException, ResourceUnavailableException { Account caller = UserContext.current().getCaller(); - + Account account = null; - if(accountId != null){ + if (accountId != null) { account = _accountDao.findById(accountId); - }else{ + } else { account = _accountDao.findActiveAccount(accountName, domainId); } - + if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } - + checkAccess(caller, null, true, account); - + if (disableAccount(account.getId())) { return _accountDao.findById(account.getId()); } else { - throw new CloudRuntimeException("Unable to update account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); + throw new CloudRuntimeException("Unable to update account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } } - @Override @DB + @Override + @DB public AccountVO updateAccount(UpdateAccountCmd cmd) { Long accountId = cmd.getId(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); String newAccountName = cmd.getNewName(); String networkDomain = cmd.getNetworkDomain(); - Mapdetails = cmd.getDetails(); + Map details = cmd.getDetails(); boolean success = false; Account account = null; - if(accountId != null){ + if (accountId != null) { account = _accountDao.findById(accountId); - }else{ + } else { account = _accountDao.findEnabledAccount(accountName, domainId); } // Check if account exists if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - s_logger.error("Unable to find account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); - throw new InvalidParameterValueException("Unable to find account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); + s_logger.error("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } // Don't allow to modify system account @@ -1141,11 +1145,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // check if the given account name is unique in this domain for updating Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId); if (duplicateAcccount != null && duplicateAcccount.getId() != account.getId()) {// allow - // same - // account - // to - // update - // itself + // same + // account + // to + // update + // itself throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:" + duplicateAcccount.getId()); } @@ -1154,36 +1158,36 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag 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 \"-\""); } } - + AccountVO acctForUpdate = _accountDao.findById(account.getId()); acctForUpdate.setAccountName(newAccountName); - + if (networkDomain != null) { - if (networkDomain.isEmpty()) { - acctForUpdate.setNetworkDomain(null); - } else { - acctForUpdate.setNetworkDomain(networkDomain); - } + if (networkDomain.isEmpty()) { + acctForUpdate.setNetworkDomain(null); + } else { + acctForUpdate.setNetworkDomain(networkDomain); + } } - + Transaction txn = Transaction.currentTxn(); txn.start(); - + success = _accountDao.update(account.getId(), acctForUpdate); - + if (details != null && success) { _accountDetailsDao.update(account.getId(), details); } - + txn.commit(); - + if (success) { return _accountDao.findById(account.getId()); } else { - throw new CloudRuntimeException("Unable to update account by accountId: "+accountId+" OR by name: "+ accountName + " in domain " + domainId); + throw new CloudRuntimeException("Unable to update account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } } @@ -1197,10 +1201,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (user == null) { throw new InvalidParameterValueException("The specified user doesn't exist in the system"); } - + Account account = _accountDao.findById(user.getAccountId()); - - //don't allow to delete the user from the account of type Project + + // don't allow to delete the user from the account of type Project if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("The specified user doesn't exist in the system"); } @@ -1208,16 +1212,15 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new InvalidParameterValueException("Account id : " + user.getAccountId() + " is a system account, delete for user associated with this account is not allowed"); } - + checkAccess(UserContext.current().getCaller(), null, true, account); return _userDao.remove(id); } - public class ResourceCountCalculateTask implements Runnable { @Override public void run() { - + } } @@ -1240,7 +1243,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag try { txn = Transaction.open(Transaction.CLOUD_DB); - //Cleanup removed accounts + // Cleanup removed accounts List removedAccounts = _accountDao.findCleanupsForRemovedAccounts(null); s_logger.info("Found " + removedAccounts.size() + " removed accounts to cleanup"); for (AccountVO account : removedAccounts) { @@ -1254,8 +1257,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.error("Skipping due to error on account " + account.getId(), e); } } - - //cleanup disabled accounts + + // cleanup disabled accounts List disabledAccounts = _accountDao.findCleanupsForDisabledAccounts(); s_logger.info("Found " + disabledAccounts.size() + " disabled accounts to cleanup"); for (AccountVO account : disabledAccounts) { @@ -1269,8 +1272,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.error("Skipping due to error on account " + account.getId(), e); } } - - //cleanup inactive domains + + // cleanup inactive domains List inactiveDomains = _domainMgr.findInactiveDomains(); s_logger.info("Found " + inactiveDomains.size() + " inactive domains to cleanup"); for (Domain inactiveDomain : inactiveDomains) { @@ -1282,13 +1285,13 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag _domainMgr.removeDomain(domainId); } else { s_logger.debug("Can't remove inactive domain id=" + domainId + " as it has accounts that need cleanup"); - } + } } catch (Exception e) { s_logger.error("Skipping due to error on domain " + domainId, e); } } - - //cleanup inactive projects + + // cleanup inactive projects List inactiveProjects = _projectDao.listByState(Project.State.Disabled); s_logger.info("Found " + inactiveProjects.size() + " disabled projects to cleanup"); for (Project project : inactiveProjects) { @@ -1299,12 +1302,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag _projectMgr.deleteProject(project.getId()); } else { s_logger.debug("Can't remove disabled project " + project + " as it has non removed account id=" + project.getId()); - } + } } catch (Exception e) { s_logger.error("Skipping due to error on project " + project, e); } } - + } catch (Exception e) { s_logger.error("Exception ", e); } finally { @@ -1326,27 +1329,27 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (caller.getId() == Account.ACCOUNT_ID_SYSTEM && ((accountName == null || domainId == null) && projectId == null)) { throw new InvalidParameterValueException("Account and domainId are needed for resource creation"); } - - //projectId and account/domainId can't be specified together + + // projectId and account/domainId can't be specified together if ((accountName != null && domainId != null) && projectId != null) { throw new InvalidParameterValueException("ProjectId and account/domainId can't be specified together"); } - + if (projectId != null) { Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id=" + projectId); } - + if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { throw new PermissionDeniedException("Account " + caller + " is unauthorised to use project id=" + projectId); } - + return getAccount(project.getProjectAccountId()); } if (isAdmin(caller.getType()) && accountName != null && domainId != null) { - Domain domain = _domainMgr.getDomain(domainId); + Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { throw new InvalidParameterValueException("Unable to find the domain by id=" + domainId); } @@ -1404,16 +1407,16 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public User getActiveUser(long userId) { return _userDao.findById(userId); } - + @Override public User getUserIncludingRemoved(long userId) { return _userDao.findByIdIncludingRemoved(userId); } @Override - public Pair,Long> finalizeAccountDomainForList(Account caller, String accountName, Long domainId, Long projectId) { + public Pair, Long> finalizeAccountDomainForList(Account caller, String accountName, Long domainId, Long projectId) { List permittedAccounts = new ArrayList(); - + if (isAdmin(caller.getType())) { if (domainId == null && accountName != null) { throw new InvalidParameterValueException("accountName and domainId might be specified together"); @@ -1430,7 +1433,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (owner == null) { throw new InvalidParameterValueException("Unable to find account with name " + accountName + " in domain id=" + domainId); } - + permittedAccounts.add(owner.getId()); } } @@ -1442,17 +1445,17 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } else { permittedAccounts.add(caller.getAccountId()); } - + if (domainId == null && caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { domainId = caller.getDomainId(); } - - //set project information + + // set project information if (projectId != null) { - if (projectId == -1) { + if (projectId == -1) { permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId())); - } else { - permittedAccounts.clear(); + } else { + permittedAccounts.clear(); Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); @@ -1461,7 +1464,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag throw new InvalidParameterValueException("Account " + caller + " can't access project id=" + projectId); } permittedAccounts.add(project.getProjectAccountId()); - } + } } return new Pair, Long>(permittedAccounts, domainId); @@ -1476,78 +1479,78 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public void markUserRegistered(long userId) { UserVO userForUpdate = _userDao.createForUpdate(); userForUpdate.setRegistered(true); - _userDao.update(Long.valueOf(userId), userForUpdate); + _userDao.update(Long.valueOf(userId), userForUpdate); } - - @Override @DB + + @Override + @DB public Account createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map details) { - //Validate domain + // Validate domain Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account"); - } - + } + if (domain.getState().equals(Domain.State.Inactive)) { throw new CloudRuntimeException("The account cannot be created as domain " + domain.getName() + " is being deleted"); } - + if ((domainId != DomainVO.ROOT_DOMAIN) && (accountType == Account.ACCOUNT_TYPE_ADMIN)) { throw new InvalidParameterValueException("Invalid account type " + accountType + " given for an account in domain " + domainId + "; unable to create user."); } - //Validate account/user/domain settings - if ( _accountDao.findActiveAccount(accountName, domainId) != null) { + // Validate account/user/domain settings + if (_accountDao.findActiveAccount(accountName, domainId) != null) { throw new InvalidParameterValueException("The specified account: " + accountName + " already exists"); } - + 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 \"-\""); } } - - //Verify account type + + // Verify account type if ((accountType < Account.ACCOUNT_TYPE_NORMAL) || (accountType > Account.ACCOUNT_TYPE_PROJECT)) { throw new InvalidParameterValueException("Invalid account type " + accountType + " given; unable to create user"); } - + if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { List dc = _dcDao.findZonesByDomainId(domainId); if (dc.isEmpty()) { throw new InvalidParameterValueException("The account cannot be created as domain " + domain.getName() + " is not associated with any private Zone"); } } - - //Create the account + + // Create the account Transaction txn = Transaction.currentTxn(); txn.start(); - + Account account = _accountDao.persist(new AccountVO(accountName, domainId, networkDomain, accountType)); - + if (account == null) { throw new CloudRuntimeException("Failed to create account name " + accountName + " in domain id=" + domainId); } - + Long accountId = account.getId(); - + if (details != null) { _accountDetailsDao.persist(accountId, details); } - - //Create resource count records for the account + + // Create resource count records for the account _resourceCountDao.createResourceCounts(accountId, ResourceLimit.ResourceOwnerType.Account); - - //Create default security group + + // Create default security group _networkGroupMgr.createDefaultSecurityGroup(accountId); - - + txn.commit(); - + return account; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User") public UserVO createUser(long accountId, String userName, String password, String firstName, String lastName, String email, String timezone) { @@ -1555,11 +1558,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.debug("Creating user: " + userName + ", accountId: " + accountId + " timezone:" + timezone); } UserVO user = _userDao.persist(new UserVO(accountId, userName, password, firstName, lastName, email, timezone)); - + return user; } - - + @Override public void logoutUser(Long userId) { UserAccount userAcct = _userAccountDao.findById(userId); @@ -1567,7 +1569,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag EventUtils.saveEvent(userId, userAcct.getAccountId(), userAcct.getDomainId(), EventTypes.EVENT_USER_LOGOUT, "user has logged out"); } // else log some kind of error event? This likely means the user doesn't exist, or has been deleted... } - + @Override public UserAccount getUserAccount(String username, Long domainId) { if (s_logger.isDebugEnabled()) { @@ -1584,7 +1586,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return userAccount; } - + @Override public UserAccount authenticateUser(String username, String password, Long domainId, Map requestParameters) { UserAccount user = null; @@ -1599,7 +1601,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag String singleSignOnTolerance = _configDao.getValue("security.singlesignon.tolerance.millis"); if (singleSignOnTolerance == null) { - // the SSO tolerance is gone (how much time before/after system time we'll allow the login request to be valid), + // the SSO tolerance is gone (how much time before/after system time we'll allow the login request to be +// valid), // don't authenticate return null; } @@ -1696,16 +1699,16 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return null; } } - + private UserAccount getUserAccount(String username, String password, Long domainId, Map requestParameters) { if (s_logger.isDebugEnabled()) { s_logger.debug("Attempting to log in user: " + username + " in domain " + domainId); } - + boolean authenticated = false; - for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();){ + for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { UserAuthenticator authenticator = en.nextElement(); - if (authenticator.authenticate(username, password, domainId, requestParameters)){ + if (authenticator.authenticate(username, password, domainId, requestParameters)) { authenticated = true; break; } @@ -1739,12 +1742,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return null; } } - + @Override public Pair findUserByApiKey(String apiKey) { return _accountDao.findUserAccountByApiKey(apiKey); } - + @Override public String[] createApiKeyAndSecretKey(RegisterCmd cmd) { Long userId = cmd.getId(); @@ -1815,7 +1818,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } return null; } - + @Override public List searchForAccounts(ListAccountsCmd cmd) { Account caller = UserContext.current().getCaller(); @@ -1825,7 +1828,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag boolean isRecursive = cmd.isRecursive(); boolean listAll = cmd.listAll(); Boolean listForDomain = false; - + if (accountId != null) { Account account = _accountDao.findById(accountId); if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { @@ -1834,13 +1837,13 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag checkAccess(caller, null, true, account); } - + if (domainId != null) { Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); } - + checkAccess(caller, domain); if (accountName != null) { @@ -1851,19 +1854,19 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag checkAccess(caller, null, true, account); } } - + if (accountId == null) { - if (isAdmin(caller.getType()) && listAll && domainId == null) { - listForDomain = true; - isRecursive = true; - if (domainId == null) { - domainId = caller.getDomainId(); - } + if (isAdmin(caller.getType()) && listAll && domainId == null) { + listForDomain = true; + isRecursive = true; + if (domainId == null) { + domainId = caller.getDomainId(); + } } else if (domainId != null) { - listForDomain = true; + listForDomain = true; } else { - accountId = caller.getAccountId(); - } + accountId = caller.getAccountId(); + } } Filter searchFilter = new Filter(AccountVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -1882,17 +1885,17 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag sb.and("needsCleanup", sb.entity().getNeedsCleanup(), SearchCriteria.Op.EQ); sb.and("typeNEQ", sb.entity().getType(), SearchCriteria.Op.NEQ); sb.and("idNEQ", sb.entity().getId(), SearchCriteria.Op.NEQ); - + if (listForDomain && isRecursive) { - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); + SearchBuilder domainSearch = _domainDao.createSearchBuilder(); + domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); + sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } SearchCriteria sc = sb.create(); - + sc.setParameters("idNEQ", Account.ACCOUNT_ID_SYSTEM); - + if (keyword != null) { SearchCriteria ssc = _accountDao.createSearchCriteria(); ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -1911,14 +1914,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (isCleanupRequired != null) { sc.setParameters("needsCleanup", isCleanupRequired); } - + if (accountName != null) { sc.setParameters("accountName", accountName); } - - //don't return account of type project to the end user + + // don't return account of type project to the end user sc.setParameters("typeNEQ", 5); - + if (accountId != null) { sc.setParameters("id", accountId); } @@ -1928,25 +1931,24 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (isRecursive) { sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); } else { - sc.setParameters("domainId", domainId); + sc.setParameters("domainId", domainId); } } return _accountDao.search(sc, searchFilter); } - + @Override public List searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException { Account caller = UserContext.current().getCaller(); - - + Long domainId = cmd.getDomainId(); if (domainId != null) { Domain domain = _domainDao.findById(domainId); if (domain == null) { throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); } - + checkAccess(caller, domain); } else { // default domainId to the caller's domain @@ -2032,62 +2034,62 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return _userAccountDao.search(sc, searchFilter); } - + @Override - public void buildACLSearchBuilder(SearchBuilder sb, - Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { - - if (sb.entity() instanceof IPAddressVO) { - sb.and("accountIdIN", ((IPAddressVO)sb.entity()).getAllocatedToAccountId(), SearchCriteria.Op.IN); - sb.and("domainId", ((IPAddressVO)sb.entity()).getAllocatedInDomainId(), SearchCriteria.Op.EQ); - } else if (sb.entity() instanceof ProjectInvitationVO) { - sb.and("accountIdIN", ((ProjectInvitationVO)sb.entity()).getForAccountId(), SearchCriteria.Op.IN); - sb.and("domainId", ((ProjectInvitationVO)sb.entity()).getInDomainId(), SearchCriteria.Op.EQ); - } else { - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); + public void buildACLSearchBuilder(SearchBuilder sb, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + + if (sb.entity() instanceof IPAddressVO) { + sb.and("accountIdIN", ((IPAddressVO) sb.entity()).getAllocatedToAccountId(), SearchCriteria.Op.IN); + sb.and("domainId", ((IPAddressVO) sb.entity()).getAllocatedInDomainId(), SearchCriteria.Op.EQ); + } else if (sb.entity() instanceof ProjectInvitationVO) { + sb.and("accountIdIN", ((ProjectInvitationVO) sb.entity()).getForAccountId(), SearchCriteria.Op.IN); + sb.and("domainId", ((ProjectInvitationVO) sb.entity()).getInDomainId(), SearchCriteria.Op.EQ); + } else { + sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - } + } if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - + if (sb.entity() instanceof IPAddressVO) { - sb.join("domainSearch", domainSearch, ((IPAddressVO)sb.entity()).getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); + sb.join("domainSearch", domainSearch, ((IPAddressVO) sb.entity()).getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } else if (sb.entity() instanceof ProjectInvitationVO) { - sb.join("domainSearch", domainSearch, ((ProjectInvitationVO)sb.entity()).getInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - }else { + sb.join("domainSearch", domainSearch, ((ProjectInvitationVO) sb.entity()).getInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } else { sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + } if (listProjectResourcesCriteria != null) { - SearchBuilder accountSearch = _accountDao.createSearchBuilder(); - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.EQ); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); - } - - if (sb.entity() instanceof IPAddressVO) { - sb.join("accountSearch", accountSearch, ((IPAddressVO)sb.entity()).getAllocatedToAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } else if (sb.entity() instanceof ProjectInvitationVO) { - sb.join("accountSearch", accountSearch, ((ProjectInvitationVO)sb.entity()).getForAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } else { - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } + SearchBuilder accountSearch = _accountDao.createSearchBuilder(); + if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { + accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.EQ); + } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { + accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); + } + + if (sb.entity() instanceof IPAddressVO) { + sb.join("accountSearch", accountSearch, ((IPAddressVO) sb.entity()).getAllocatedToAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } else if (sb.entity() instanceof ProjectInvitationVO) { + sb.join("accountSearch", accountSearch, ((ProjectInvitationVO) sb.entity()).getForAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } else { + sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } } - } - + } + @Override - public void buildACLSearchCriteria(SearchCriteria sc, - Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { - - if (listProjectResourcesCriteria != null) { - sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); + public void buildACLSearchCriteria(SearchCriteria sc, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + + if (listProjectResourcesCriteria != null) { + sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); } - + if (!permittedAccounts.isEmpty()) { sc.setParameters("accountIdIN", permittedAccounts.toArray()); } else if (domainId != null) { @@ -2098,49 +2100,50 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag sc.setParameters("domainId", domainId); } } - } - + } + @Override - public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, boolean listAll) { - Long domainId = domainIdRecursiveListProject.first(); - - if (domainId != null) { - Domain domain = _domainDao.findById(domainId); - if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id " + domainId); - } - //check permissions - checkAccess(caller, domain); + public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, + boolean listAll) { + Long domainId = domainIdRecursiveListProject.first(); + + if (domainId != null) { + Domain domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Unable to find domain by id " + domainId); + } + // check permissions + checkAccess(caller, domain); } - + if (accountName != null) { - if (projectId != null) { - throw new InvalidParameterValueException("Account and projectId can't be specified together"); - } - - Account userAccount = null; - if (domainId != null) { - userAccount = _accountDao.findActiveAccount(accountName, domainId); - } else { - userAccount = _accountDao.findActiveAccount(accountName, caller.getDomainId()); - } - - if (userAccount != null) { + if (projectId != null) { + throw new InvalidParameterValueException("Account and projectId can't be specified together"); + } + + Account userAccount = null; + if (domainId != null) { + userAccount = _accountDao.findActiveAccount(accountName, domainId); + } else { + userAccount = _accountDao.findActiveAccount(accountName, caller.getDomainId()); + } + + if (userAccount != null) { permittedAccounts.add(userAccount.getId()); } else { throw new InvalidParameterValueException("could not find account " + accountName + " in domain " + domainId); } - } - - //set project information + } + + // set project information if (projectId != null) { - if (projectId == -1) { - if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { + if (projectId == -1) { + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId())); - } else { - domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.ListProjectResourcesOnly); - } - } else { + } else { + domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.ListProjectResourcesOnly); + } + } else { Project project = _projectMgr.getProject(projectId); if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); @@ -2149,28 +2152,29 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag throw new PermissionDeniedException("Account " + caller + " can't access project id=" + projectId); } permittedAccounts.add(project.getProjectAccountId()); - } + } } else { - if (id == null) { - domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.SkipProjectResources); - } - if (permittedAccounts.isEmpty() && domainId == null) { - if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { - permittedAccounts.add(caller.getId()); - } else if (!listAll) { - if (id == null) { - permittedAccounts.add(caller.getId()); - } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - domainIdRecursiveListProject.first(caller.getDomainId()); - domainIdRecursiveListProject.second(true); - } - } else if (domainId == null){ - if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN){ - domainIdRecursiveListProject.first(caller.getDomainId()); - domainIdRecursiveListProject.second(true); - } - } - } - } + if (id == null) { + domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.SkipProjectResources); + } + if (permittedAccounts.isEmpty() && domainId == null) { + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { + permittedAccounts.add(caller.getId()); + } else if (!listAll) { + if (id == null) { + permittedAccounts.add(caller.getId()); + } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + domainIdRecursiveListProject.first(caller.getDomainId()); + domainIdRecursiveListProject.second(true); + } + } else if (domainId == null) { + if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { + domainIdRecursiveListProject.first(caller.getDomainId()); + domainIdRecursiveListProject.second(true); + } + } + } + + } } } diff --git a/server/src/com/cloud/user/DomainManager.java b/server/src/com/cloud/user/DomainManager.java index ea990d86dda..5bc05025405 100644 --- a/server/src/com/cloud/user/DomainManager.java +++ b/server/src/com/cloud/user/DomainManager.java @@ -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 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 getDomainParentIds(long domainId); - + boolean removeDomain(long domainId); - + List findInactiveDomains(); boolean deleteDomain(DomainVO domain, Boolean cleanup); diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java index 563263ce4a7..d88d2c4bc30 100644 --- a/server/src/com/cloud/user/DomainManagerImpl.java +++ b/server/src/com/cloud/user/DomainManagerImpl.java @@ -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 params) throws ConfigurationException { _name = name; return true; } - + @Override public Set getDomainChildrenIds(String parentDomainPath) { Set childDomains = new HashSet(); SearchCriteria sc = _domainDao.createSearchCriteria(); sc.addAnd("path", SearchCriteria.Op.LIKE, parentDomainPath + "%"); - + List 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 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 getDomainParentIds(long domainId) { - return _domainDao.getDomainParentIds(domainId); + return _domainDao.getDomainParentIds(domainId); } - + @Override public boolean removeDomain(long domainId) { return _domainDao.remove(domainId); } - + @Override public List 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 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 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 accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domainId); if (accountsForCleanup.isEmpty()) { @@ -318,14 +316,14 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager{ return success && deleteDomainSuccess; } - + @Override - public List searchForDomains(ListDomainsCmd cmd){ + public List 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 searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException { + public List 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 searchForDomainChildren(Filter searchFilter, Long domainId, String domainName, Object keyword, String path, boolean listActiveOnly) { SearchCriteria 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); } + } diff --git a/server/test/com/cloud/upgrade/Test2214To30DBUpgrade.java b/server/test/com/cloud/upgrade/Test2214To30DBUpgrade.java index 3216568ecbf..c5d555f6d2a 100644 --- a/server/test/com/cloud/upgrade/Test2214To30DBUpgrade.java +++ b/server/test/com/cloud/upgrade/Test2214To30DBUpgrade.java @@ -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 fields = new ArrayList(); - 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 fields = new ArrayList(); + 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 fields = new ArrayList(); - 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 fields = new ArrayList(); + 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(); + } - - + } - - + }