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 extends PhysicalNetworkTrafficType> 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 extends FirewallRule> listFirewallRules(ListFirewallRulesCmd cmd);
-
+
/**
- * Revokes a firewall rule
- * @param ruleId the id of the rule to revoke.
+ * Revokes a firewall rule
+ *
+ * @param ruleId
+ * the id of the rule to revoke.
* @return
*/
boolean revokeFirewallRule(long ruleId, boolean apply);
-
+
boolean applyFirewallRules(long ipId, Account caller) throws ResourceUnavailableException;
-
+
FirewallRule getFirewallRule(long ruleId);
-
+
boolean revokeRelatedFirewallRule(long ruleId, boolean apply);
+
}
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 extends LoadBalancer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd);
+
/**
* List stickiness policies based on the given criteria
- * @param cmd the command specifies the load balancing rule id.
+ *
+ * @param cmd
+ * the command specifies the load balancing rule id.
* @return list of stickiness policies that match the criteria.
*/
List extends StickinessPolicy> searchForLBStickinessPolicies(ListLBStickinessPoliciesCmd cmd);
-
-
+
List 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 extends FirewallRule> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll);
+ List extends FirewallRule> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll);
/**
* Creates a port forwarding rule between two ip addresses or between
* an ip address and a virtual machine.
- * @param rule rule to be created.
- * @param vmId vm to be linked to. If specified the destination ip address is ignored.
- * @param openFirewall TODO
+ *
+ * @param rule
+ * rule to be created.
+ * @param vmId
+ * vm to be linked to. If specified the destination ip address is ignored.
+ * @param openFirewall
+ * TODO
* @return PortForwardingRule if created.
- * @throws NetworkRuleConflictException if conflicts in the network rules are detected.
+ * @throws NetworkRuleConflictException
+ * if conflicts in the network rules are detected.
*/
PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException;
-
+
/**
- * Revokes a port forwarding rule
- * @param ruleId the id of the rule to revoke.
- * @param caller
+ * Revokes a port forwarding rule
+ *
+ * @param ruleId
+ * the id of the rule to revoke.
+ * @param caller
* @return
*/
boolean revokePortForwardingRule(long ruleId, boolean apply);
+
/**
* List port forwarding rules assigned to an ip address
- * @param cmd the command object holding the criteria for listing port forwarding rules (the ipAddress)
+ *
+ * @param cmd
+ * the command object holding the criteria for listing port forwarding rules (the ipAddress)
* @return list of port forwarding rules on the given address, empty list if no rules exist
*/
public List extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd);
boolean applyPortForwardingRules(long ipAdddressId, Account caller) throws ResourceUnavailableException;
-
+
boolean enableStaticNat(long ipAddressId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException;
-
+
PortForwardingRule getPortForwardigRule(long ruleId);
+
FirewallRule getFirewallRule(long ruleId);
-
+
StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException;
-
+
boolean revokeStaticNatRule(long ruleId, boolean apply);
-
+
boolean applyStaticNatRules(long ipAdddressId, Account caller) throws ResourceUnavailableException;
-
+
StaticNatRule buildStaticNatRule(FirewallRule rule);
-
+
List 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 extends Domain> searchForDomains(ListDomainsCmd cmd)
- throws PermissionDeniedException;
+ List extends Domain> searchForDomains(ListDomainsCmd cmd)
+ throws PermissionDeniedException;
+
+ List extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
+ throws PermissionDeniedException;
- List extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
- throws PermissionDeniedException;
}
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 extends ResourceCount> recalculateResourceCount(Long accountId, Long domainId, Integer typeId);
-
+
/**
* Search for resource limits for the given id and/or account and/or type and/or domain.
- * @param id TODO
- * @param accountId TODO
- * @param domainId TODO
- * @param type TODO
+ *
+ * @param id
+ * TODO
+ * @param accountId
+ * TODO
+ * @param domainId
+ * TODO
+ * @param type
+ * TODO
* @return a list of limits that match the criteria
*/
public List extends ResourceLimit> searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal);
-
+
/**
* Finds the resource limit for a specified account and type. If the account has an infinite limit, will check
* the account's parent domain, and if that limit is also infinite, will return the ROOT domain's limit.
+ *
* @param account
* @param type
* @return resource limit
@@ -69,6 +84,7 @@ public interface ResourceLimitService {
/**
* Finds the resource limit for a specified domain and type. If the domain has an infinite limit, will check
* up the domain hierarchy
+ *
* @param account
* @param type
* @return resource limit
@@ -77,31 +93,37 @@ public interface ResourceLimitService {
/**
* Increments the resource count
+ *
* @param accountId
* @param type
* @param delta
*/
- public void incrementResourceCount(long accountId, ResourceType type, Long...delta);
-
+ public void incrementResourceCount(long accountId, ResourceType type, Long... delta);
+
/**
* Decrements the resource count
+ *
* @param accountId
* @param type
* @param delta
*/
- public void decrementResourceCount(long accountId, ResourceType type, Long...delta);
-
+ public void decrementResourceCount(long accountId, ResourceType type, Long... delta);
+
/**
* Checks if a limit has been exceeded for an account
+ *
* @param account
* @param type
- * @param count the number of resources being allocated, count will be added to current allocation and compared against maximum allowed allocation
- * @throws ResourceAllocationException
+ * @param count
+ * the number of resources being allocated, count will be added to current allocation and compared
+ * against maximum allowed allocation
+ * @throws ResourceAllocationException
*/
- public void checkResourceLimit(Account account, ResourceCount.ResourceType type, long...count) throws ResourceAllocationException;
-
+ public void checkResourceLimit(Account account, ResourceCount.ResourceType type, long... count) throws ResourceAllocationException;
+
/**
* Gets the count of resources for a resource type and account
+ *
* @param account
* @param type
* @return count of resources
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 extends Capacity> 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 extends Capacity> 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 extends Network.Provider> 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 extends StickinessPolicy> 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