Merge branch 'master' of ssh://git.cloud.com/var/lib/git/cloudstack-oss

This commit is contained in:
Sam Robertson 2012-02-03 16:59:25 -08:00
commit c358f469c0
176 changed files with 8083 additions and 7451 deletions

View File

@ -42,44 +42,58 @@ public interface SecurityChecker extends Adapter {
ModifyProject, ModifyProject,
UseNetwork UseNetwork
} }
/** /**
* Checks if the account owns the object. * Checks if the account owns the object.
* *
* @param caller account to check against. * @param caller
* @param object object that the account is trying to access. * account to check against.
* @param object
* object that the account is trying to access.
* @return true if access allowed. false if this adapter cannot authenticate ownership. * @return true if access allowed. false if this adapter cannot authenticate ownership.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed. * @throws PermissionDeniedException
* if this adapter is suppose to authenticate ownership and the check failed.
*/ */
boolean checkAccess(Account caller, Domain domain) throws PermissionDeniedException; boolean checkAccess(Account caller, Domain domain) throws PermissionDeniedException;
/** /**
* Checks if the user belongs to an account that owns the object. * Checks if the user belongs to an account that owns the object.
* *
* @param user user to check against. * @param user
* @param object object that the account is trying to access. * user to check against.
* @param object
* object that the account is trying to access.
* @return true if access allowed. false if this adapter cannot authenticate ownership. * @return true if access allowed. false if this adapter cannot authenticate ownership.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed. * @throws PermissionDeniedException
* if this adapter is suppose to authenticate ownership and the check failed.
*/ */
boolean checkAccess(User user, Domain domain) throws PermissionDeniedException; boolean checkAccess(User user, Domain domain) throws PermissionDeniedException;
/** /**
* Checks if the account can access the object. * Checks if the account can access the object.
* *
* @param caller account to check against. * @param caller
* @param entity object that the account is trying to access. * account to check against.
* @param accessType TODO * @param entity
* object that the account is trying to access.
* @param accessType
* TODO
* @return true if access allowed. false if this adapter cannot provide permission. * @return true if access allowed. false if this adapter cannot provide permission.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed. * @throws PermissionDeniedException
* if this adapter is suppose to authenticate ownership and the check failed.
*/ */
boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType) throws PermissionDeniedException; boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType) throws PermissionDeniedException;
/** /**
* Checks if the user belongs to an account that can access the object. * Checks if the user belongs to an account that can access the object.
* *
* @param user user to check against. * @param user
* @param entity object that the account is trying to access. * user to check against.
* @param entity
* object that the account is trying to access.
* @return true if access allowed. false if this adapter cannot authenticate ownership. * @return true if access allowed. false if this adapter cannot authenticate ownership.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed. * @throws PermissionDeniedException
* if this adapter is suppose to authenticate ownership and the check failed.
*/ */
boolean checkAccess(User user, ControlledEntity entity) throws PermissionDeniedException; boolean checkAccess(User user, ControlledEntity entity) throws PermissionDeniedException;

View File

@ -32,7 +32,6 @@ public abstract class BaseAsyncCmd extends BaseCmd {
public static final String ipAddressSyncObject = "ipaddress"; public static final String ipAddressSyncObject = "ipaddress";
public static final String networkSyncObject = "network"; public static final String networkSyncObject = "network";
private AsyncJob job; private AsyncJob job;
@Parameter(name = "starteventid", type = CommandType.LONG) @Parameter(name = "starteventid", type = CommandType.LONG)
@ -42,6 +41,7 @@ public abstract class BaseAsyncCmd extends BaseCmd {
* For proper tracking of async commands through the system, events must be generated when the command is * For proper tracking of async commands through the system, events must be generated when the command is
* scheduled, started, and completed. Commands should specify the type of event so that when the scheduled, * scheduled, started, and completed. Commands should specify the type of event so that when the scheduled,
* started, and completed events are saved to the events table, they have the proper type information. * started, and completed events are saved to the events table, they have the proper type information.
*
* @return a string representing the type of event, e.g. VM.START, VOLUME.CREATE. * @return a string representing the type of event, e.g. VM.START, VOLUME.CREATE.
*/ */
public abstract String getEventType(); public abstract String getEventType();
@ -50,6 +50,7 @@ public abstract class BaseAsyncCmd extends BaseCmd {
* For proper tracking of async commands through the system, events must be generated when the command is * For proper tracking of async commands through the system, events must be generated when the command is
* scheduled, started, and completed. Commands should specify a description for these events so that when * scheduled, started, and completed. Commands should specify a description for these events so that when
* the scheduled, started, and completed events are saved to the events table, they have a meaningful description. * the scheduled, started, and completed events are saved to the events table, they have a meaningful description.
*
* @return a string representing a description of the event * @return a string representing a description of the event
*/ */
public abstract String getEventDescription(); public abstract String getEventDescription();
@ -130,4 +131,5 @@ public abstract class BaseAsyncCmd extends BaseCmd {
} }
return _mgr.saveCompletedEvent((userId == null) ? User.UID_SYSTEM : userId, getEntityOwnerId(), level, eventType, description, startEvent); return _mgr.saveCompletedEvent((userId == null) ? User.UID_SYSTEM : userId, getEntityOwnerId(), level, eventType, description, startEvent);
} }
} }

View File

@ -53,4 +53,5 @@ public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd {
public String getCreateEventDescription() { public String getCreateEventDescription() {
return null; return null;
} }
} }

View File

@ -28,7 +28,6 @@ import java.util.regex.Pattern;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.api.response.TrafficTypeImplementorResponse;
import com.cloud.configuration.ConfigurationService; import com.cloud.configuration.ConfigurationService;
import com.cloud.consoleproxy.ConsoleProxyService; import com.cloud.consoleproxy.ConsoleProxyService;
import com.cloud.dao.EntityManager; import com.cloud.dao.EntityManager;
@ -177,6 +176,7 @@ public abstract class BaseCmd {
/** /**
* For commands the API framework needs to know the owner of the object being acted upon. This method is * For commands the API framework needs to know the owner of the object being acted upon. This method is
* used to determine that information. * used to determine that information.
*
* @return the id of the account that owns the object being acted upon * @return the id of the account that owns the object being acted upon
*/ */
public abstract long getEntityOwnerId(); public abstract long getEntityOwnerId();
@ -208,7 +208,8 @@ public abstract class BaseCmd {
int arrayStartIndex = key.indexOf('['); int arrayStartIndex = key.indexOf('[');
int arrayStartLastIndex = key.lastIndexOf('['); int arrayStartLastIndex = key.lastIndexOf('[');
if (arrayStartIndex != arrayStartLastIndex) { if (arrayStartIndex != arrayStartLastIndex) {
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup"); throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key
+ "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
} }
if (arrayStartIndex > 0) { if (arrayStartIndex > 0) {
@ -216,14 +217,16 @@ public abstract class BaseCmd {
int arrayEndLastIndex = key.lastIndexOf(']'); int arrayEndLastIndex = key.lastIndexOf(']');
if ((arrayEndIndex < arrayStartIndex) || (arrayEndIndex != arrayEndLastIndex)) { if ((arrayEndIndex < arrayStartIndex) || (arrayEndIndex != arrayEndLastIndex)) {
// malformed parameter // malformed parameter
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup"); throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key
+ "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
} }
// Now that we have an array object, check for a field name in the case of a complex object // Now that we have an array object, check for a field name in the case of a complex object
int fieldIndex = key.indexOf('.'); int fieldIndex = key.indexOf('.');
String fieldName = null; String fieldName = null;
if (fieldIndex < arrayEndIndex) { if (fieldIndex < arrayEndIndex) {
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup"); throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key
+ "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
} else { } else {
fieldName = key.substring(fieldIndex + 1); fieldName = key.substring(fieldIndex + 1);
} }
@ -247,7 +250,8 @@ public abstract class BaseCmd {
} }
if (!parsedIndex) { if (!parsedIndex) {
throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup"); throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key
+ "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup");
} }
Object value = lowercaseParams.get(paramName); Object value = lowercaseParams.get(paramName);
@ -320,7 +324,8 @@ public abstract class BaseCmd {
} }
if (suffixSb.length() > 0) { if (suffixSb.length() > 0) {
if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)){ // append comma only if we have some suffix else not as per strict Json syntax. if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { // append comma only if we have some suffix else
// not as per strict Json syntax.
prefixSb.append(","); prefixSb.append(",");
} }
prefixSb.append(suffixSb); prefixSb.append(suffixSb);
@ -449,8 +454,7 @@ public abstract class BaseCmd {
public static boolean isAdmin(short accountType) { public static boolean isAdmin(short accountType) {
return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || return ((accountType == Account.ACCOUNT_TYPE_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
(accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
} }
public static boolean isRootAdmin(short accountType) { public static boolean isRootAdmin(short accountType) {

View File

@ -23,7 +23,6 @@ public abstract class BaseListAccountResourcesCmd extends BaseListDomainResource
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "List resources by account. Must be used with the domainId parameter.") @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "List resources by account. Must be used with the domainId parameter.")
private String accountName; private String accountName;
public String getAccountName() { public String getAccountName() {
return accountName; return accountName;
} }

View File

@ -40,8 +40,6 @@ public abstract class BaseListCmd extends BaseCmd {
@Parameter(name = ApiConstants.PAGE_SIZE, type = CommandType.INTEGER) @Parameter(name = ApiConstants.PAGE_SIZE, type = CommandType.INTEGER)
private Integer pageSize; private Integer pageSize;
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////

View File

@ -44,4 +44,3 @@ public class IdentityProxy {
_value = value; _value = value;
} }
} }

View File

@ -19,6 +19,8 @@ package com.cloud.api;
public interface IdentityService { public interface IdentityService {
Long getIdentityId(IdentityMapper mapper, String identityString); Long getIdentityId(IdentityMapper mapper, String identityString);
Long getIdentityId(String tableName, String identityString); Long getIdentityId(String tableName, String identityString);
String getIdentityUuid(String tableName, String identityString); String getIdentityUuid(String tableName, String identityString);
} }

View File

@ -28,8 +28,12 @@ import java.lang.annotation.Target;
@Target({ TYPE }) @Target({ TYPE })
public @interface Implementation { public @interface Implementation {
Class<?> responseObject(); Class<?> responseObject();
String description() default ""; String description() default "";
String usage() default ""; String usage() default "";
boolean includeInApiDoc() default true; boolean includeInApiDoc() default true;
String since() default ""; String since() default "";
} }

View File

@ -30,13 +30,20 @@ import com.cloud.api.BaseCmd.CommandType;
@Target({ FIELD }) @Target({ FIELD })
public @interface Parameter { public @interface Parameter {
String name() default ""; String name() default "";
String description() default ""; String description() default "";
boolean required() default false; boolean required() default false;
CommandType type() default CommandType.OBJECT; CommandType type() default CommandType.OBJECT;
CommandType collectionType() default CommandType.OBJECT; CommandType collectionType() default CommandType.OBJECT;
boolean expose() default true; boolean expose() default true;
boolean includeInApiDoc() default true; boolean includeInApiDoc() default true;
int length() default 255; int length() default 255;
String since() default ""; String since() default "";
} }

View File

@ -43,11 +43,9 @@ import com.cloud.api.response.IPAddressResponse;
import com.cloud.api.response.InstanceGroupResponse; import com.cloud.api.response.InstanceGroupResponse;
import com.cloud.api.response.IpForwardingRuleResponse; import com.cloud.api.response.IpForwardingRuleResponse;
import com.cloud.api.response.LBStickinessResponse; import com.cloud.api.response.LBStickinessResponse;
import com.cloud.api.response.LDAPConfigResponse;
import com.cloud.api.response.ListResponse; import com.cloud.api.response.ListResponse;
import com.cloud.api.response.LoadBalancerResponse; import com.cloud.api.response.LoadBalancerResponse;
import com.cloud.api.response.LBStickinessPolicyResponse;
import com.cloud.network.rules.StickinessPolicy;
import com.cloud.api.response.LDAPConfigResponse;
import com.cloud.api.response.NetworkOfferingResponse; import com.cloud.api.response.NetworkOfferingResponse;
import com.cloud.api.response.NetworkResponse; import com.cloud.api.response.NetworkResponse;
import com.cloud.api.response.PhysicalNetworkResponse; import com.cloud.api.response.PhysicalNetworkResponse;
@ -106,9 +104,10 @@ import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.LoadBalancer;
import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StaticNatRule;
import com.cloud.network.security.SecurityRule; import com.cloud.network.rules.StickinessPolicy;
import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroup;
import com.cloud.network.security.SecurityGroupRules; import com.cloud.network.security.SecurityGroupRules;
import com.cloud.network.security.SecurityRule;
import com.cloud.offering.DiskOffering; import com.cloud.offering.DiskOffering;
import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering; import com.cloud.offering.ServiceOffering;
@ -205,6 +204,7 @@ public interface ResponseGenerator {
VpnUsersResponse createVpnUserResponse(VpnUser user); VpnUsersResponse createVpnUserResponse(VpnUser user);
RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn); RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn);
List<TemplateResponse> createTemplateResponses(long templateId, Long zoneId, boolean readyOnly); List<TemplateResponse> createTemplateResponses(long templateId, Long zoneId, boolean readyOnly);
List<TemplateResponse> createTemplateResponses(long templateId, Long snapshotId, Long volumeId, boolean readyOnly); List<TemplateResponse> createTemplateResponses(long templateId, Long snapshotId, Long volumeId, boolean readyOnly);

View File

@ -21,24 +21,28 @@ package com.cloud.api;
public interface ResponseObject { public interface ResponseObject {
/** /**
* Get the name of the API response * Get the name of the API response
*
* @return the name of the API response * @return the name of the API response
*/ */
String getResponseName(); String getResponseName();
/** /**
* Set the name of the API response * Set the name of the API response
*
* @param name * @param name
*/ */
void setResponseName(String name); void setResponseName(String name);
/** /**
* Get the name of the API object * Get the name of the API object
*
* @return the name of the API object * @return the name of the API object
*/ */
String getObjectName(); String getObjectName();
/** /**
* Set the name of the APIobject * Set the name of the APIobject
*
* @param name * @param name
*/ */
void setObjectName(String name); void setObjectName(String name);
@ -50,18 +54,21 @@ public interface ResponseObject {
/** /**
* Returns the job id * Returns the job id
*
* @return * @return
*/ */
Long getJobId(); Long getJobId();
/** /**
* Sets the job id * Sets the job id
*
* @param jobId * @param jobId
*/ */
void setJobId(Long jobId); void setJobId(Long jobId);
/** /**
* Returns the job status * Returns the job status
*
* @return * @return
*/ */
Integer getJobStatus(); Integer getJobStatus();

View File

@ -36,6 +36,7 @@ public class ServerApiException extends RuntimeException {
public int getErrorCode() { public int getErrorCode() {
return _errorCode; return _errorCode;
} }
public void setErrorCode(int errorCode) { public void setErrorCode(int errorCode) {
_errorCode = errorCode; _errorCode = errorCode;
} }
@ -43,6 +44,7 @@ public class ServerApiException extends RuntimeException {
public String getDescription() { public String getDescription() {
return _description; return _description;
} }
public void setDescription(String description) { public void setDescription(String description) {
_description = description; _description = description;
} }

View File

@ -1,4 +1,5 @@
/** /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
@ -25,7 +26,6 @@ import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation; import com.cloud.api.Implementation;
import com.cloud.api.Parameter; import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException; import com.cloud.api.ServerApiException;
import com.cloud.api.BaseCmd.CommandType;
import com.cloud.api.response.SecurityGroupResponse; import com.cloud.api.response.SecurityGroupResponse;
import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroup;
import com.cloud.user.Account; import com.cloud.user.Account;
@ -58,7 +58,6 @@ public class CreateSecurityGroupCmd extends BaseCmd {
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "Deploy vm for the project") @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "Deploy vm for the project")
private Long projectId; private Long projectId;
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
// ///////////////// Accessors /////////////////////// // ///////////////// Accessors ///////////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
@ -83,7 +82,6 @@ public class CreateSecurityGroupCmd extends BaseCmd {
return projectId; return projectId;
} }
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
// ///////////// API Implementation/////////////////// // ///////////// API Implementation///////////////////
// /////////////////////////////////////////////////// // ///////////////////////////////////////////////////
@ -109,7 +107,8 @@ public class CreateSecurityGroupCmd extends BaseCmd {
return account.getId(); return account.getId();
} }
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are
// tracked
} }
@Override @Override

View File

@ -40,27 +40,50 @@ public interface AsyncJob extends Identity{
} }
Long getId(); Long getId();
long getUserId(); long getUserId();
long getAccountId(); long getAccountId();
String getCmd(); String getCmd();
int getCmdVersion(); int getCmdVersion();
String getCmdInfo(); String getCmdInfo();
int getCallbackType(); int getCallbackType();
String getCallbackAddress(); String getCallbackAddress();
int getStatus(); int getStatus();
int getProcessStatus(); int getProcessStatus();
int getResultCode(); int getResultCode();
String getResult(); String getResult();
Long getInitMsid(); Long getInitMsid();
Long getCompleteMsid(); Long getCompleteMsid();
Date getCreated(); Date getCreated();
Date getLastUpdated(); Date getLastUpdated();
Date getLastPolled(); Date getLastPolled();
Date getRemoved(); Date getRemoved();
Type getInstanceType(); Type getInstanceType();
Long getInstanceId(); Long getInstanceId();
String getSessionKey(); String getSessionKey();
String getCmdOriginator(); String getCmdOriginator();
boolean isFromPreviousSession(); boolean isFromPreviousSession();
SyncQueueItem getSyncSource(); SyncQueueItem getSyncSource();
} }

View File

@ -21,6 +21,6 @@ package com.cloud.async;
public interface SyncQueueItem { public interface SyncQueueItem {
String getContentType(); String getContentType();
Long getContentId();
Long getContentId();
} }

View File

@ -36,14 +36,19 @@ public interface Capacity {
public long getId(); public long getId();
public Long getHostOrPoolId(); public Long getHostOrPoolId();
public long getDataCenterId(); public long getDataCenterId();
public Long getPodId(); public Long getPodId();
public Long getClusterId(); public Long getClusterId();
public long getUsedCapacity(); public long getUsedCapacity();
public long getTotalCapacity(); public long getTotalCapacity();
public short getCapacityType(); public short getCapacityType();
long getReservedCapacity(); long getReservedCapacity();
} }

View File

@ -16,18 +16,17 @@
* *
*/ */
package com.cloud.cluster; package com.cloud.cluster;
public interface ManagementServerHost { public interface ManagementServerHost {
public static enum State { Up, Starting, Down }; public static enum State {
Up, Starting, Down
};
long getMsid(); long getMsid();
State getState(); State getState();
String getVersion(); String getVersion();
} }

View File

@ -18,7 +18,6 @@
package com.cloud.configuration; package com.cloud.configuration;
public interface Configuration { public interface Configuration {
public String getCategory(); public String getCategory();
@ -33,5 +32,4 @@ public interface Configuration{
public String getDescription(); public String getDescription();
} }

View File

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

View File

@ -72,3 +72,4 @@ public interface EntityManager {
public <T, K extends Serializable> void remove(Class<T> entityType, K id); public <T, K extends Serializable> void remove(Class<T> entityType, K id);
} }

View File

@ -34,28 +34,49 @@ public interface DataCenter extends Grouping {
Basic, Basic,
Advanced, Advanced,
} }
long getId(); long getId();
String getDns1(); String getDns1();
String getDns2(); String getDns2();
String getName(); String getName();
Long getDomainId(); Long getDomainId();
String getDescription(); String getDescription();
String getDomain(); String getDomain();
NetworkType getNetworkType(); NetworkType getNetworkType();
String getInternalDns1(); String getInternalDns1();
String getInternalDns2(); String getInternalDns2();
String getDnsProvider(); String getDnsProvider();
String getGatewayProvider(); String getGatewayProvider();
String getFirewallProvider(); String getFirewallProvider();
String getDhcpProvider(); String getDhcpProvider();
String getLoadBalancerProvider(); String getLoadBalancerProvider();
String getUserDataProvider(); String getUserDataProvider();
String getVpnProvider(); String getVpnProvider();
boolean isSecurityGroupEnabled(); boolean isSecurityGroupEnabled();
Map<String, String> getDetails(); Map<String, String> getDetails();
void setDetails(Map<String, String> details); void setDetails(Map<String, String> details);
AllocationState getAllocationState(); AllocationState getAllocationState();
String getZoneToken(); String getZoneToken();
} }

View File

@ -22,7 +22,6 @@
package com.cloud.dc; package com.cloud.dc;
import com.cloud.org.Grouping; import com.cloud.org.Grouping;
import com.cloud.org.Grouping.AllocationState;
/** /**
* Represents one pod in the cloud stack. * Represents one pod in the cloud stack.

View File

@ -43,9 +43,12 @@ public interface DeploymentPlanner extends Adapter {
/** /**
* plan is called to determine where a virtual machine should be running. * plan is called to determine where a virtual machine should be running.
* *
* @param vm virtual machine. * @param vm
* @param plan deployment plan that tells you where it's being deployed to. * virtual machine.
* @param avoid avoid these data centers, pods, clusters, or hosts. * @param plan
* deployment plan that tells you where it's being deployed to.
* @param avoid
* avoid these data centers, pods, clusters, or hosts.
* @return DeployDestination for that virtual machine. * @return DeployDestination for that virtual machine.
*/ */
DeployDestination plan(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, ExcludeList avoid) throws InsufficientServerCapacityException; DeployDestination plan(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, ExcludeList avoid) throws InsufficientServerCapacityException;
@ -54,21 +57,30 @@ public interface DeploymentPlanner extends Adapter {
* check() is called right before the virtual machine starts to make sure * check() is called right before the virtual machine starts to make sure
* the host has enough capacity. * the host has enough capacity.
* *
* @param vm virtual machine in question. * @param vm
* @param plan deployment plan used to determined the deploy destination. * virtual machine in question.
* @param dest destination returned by plan. * @param plan
* @param avoid what to avoid. * deployment plan used to determined the deploy destination.
* @return true if it's okay to start; false if not. If false, the exclude list will include what should be excluded. * @param dest
* destination returned by plan.
* @param avoid
* what to avoid.
* @return true if it's okay to start; false if not. If false, the exclude list will include what should be
* excluded.
*/ */
boolean check(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, DeployDestination dest, ExcludeList exclude); boolean check(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, DeployDestination dest, ExcludeList exclude);
/** /**
* canHandle is called before plan to determine if the plan can do the allocation. Planers should be exclusive so planner writer must * canHandle is called before plan to determine if the plan can do the allocation. Planers should be exclusive so
* planner writer must
* make sure only one planer->canHandle return true in the planner list * make sure only one planer->canHandle return true in the planner list
* *
* @param vm virtual machine. * @param vm
* @param plan deployment plan that tells you where it's being deployed to. * virtual machine.
* @param avoid avoid these data centers, pods, clusters, or hosts. * @param plan
* deployment plan that tells you where it's being deployed to.
* @param avoid
* avoid these data centers, pods, clusters, or hosts.
* @return true if it's okay to allocate; false or not * @return true if it's okay to allocate; false or not
*/ */
boolean canHandle(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, ExcludeList avoid); boolean canHandle(VirtualMachineProfile<? extends VirtualMachine> vm, DeploymentPlan plan, ExcludeList avoid);

View File

@ -31,7 +31,9 @@ import com.cloud.user.OwnedBy;
public interface Domain extends OwnedBy { public interface Domain extends OwnedBy {
public static final long ROOT_DOMAIN = 1L; public static final long ROOT_DOMAIN = 1L;
enum State {Active, Inactive}; enum State {
Active, Inactive
};
long getId(); long getId();

View File

@ -28,7 +28,10 @@ import java.lang.annotation.Target;
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface ActionEvent { public @interface ActionEvent {
boolean create() default false; boolean create() default false;
boolean async() default false; boolean async() default false;
String eventType(); String eventType();
String eventDescription(); String eventDescription();
} }

View File

@ -37,5 +37,4 @@ public class AccountLimitException extends CloudRuntimeException {
} }
// TODO: Add the actual thing that causes the exception. Is it ip address, vm, etc? // TODO: Add the actual thing that causes the exception. Is it ip address, vm, etc?
} }

View File

@ -20,13 +20,10 @@ package com.cloud.exception;
public class InternalErrorException extends ManagementServerException { public class InternalErrorException extends ManagementServerException {
private static final long serialVersionUID = -3070582946175427902L; private static final long serialVersionUID = -3070582946175427902L;
public InternalErrorException(String message) { public InternalErrorException(String message) {
super(message); super(message);
} }
} }

View File

@ -25,20 +25,14 @@ import com.cloud.utils.SerialVersionUID;
*/ */
public class ManagementServerException extends Exception { public class ManagementServerException extends Exception {
private static final long serialVersionUID = SerialVersionUID.ManagementServerException; private static final long serialVersionUID = SerialVersionUID.ManagementServerException;
public ManagementServerException() { public ManagementServerException() {
} }
public ManagementServerException(String message) { public ManagementServerException(String message) {
super(message); super(message);
} }
} }

View File

@ -24,7 +24,6 @@ import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
public class NetworkProfile implements Network { public class NetworkProfile implements Network {
private long id; private long id;
private long dataCenterId; private long dataCenterId;

View File

@ -132,4 +132,5 @@ public interface NetworkService {
Network getExclusiveGuestNetwork(long zoneId); Network getExclusiveGuestNetwork(long zoneId);
List<Pair<TrafficType, String>> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd); List<Pair<TrafficType, String>> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd);
} }

View File

@ -161,7 +161,8 @@ public class Networks {
public <T> URI toUri(T value) { public <T> URI toUri(T value) {
try { try {
//assert(this!=Vlan || value.getClass().isAssignableFrom(Integer.class)) : "Why are you putting non integer into vlan url"; // assert(this!=Vlan || value.getClass().isAssignableFrom(Integer.class)) :
// "Why are you putting non integer into vlan url";
return new URI(scheme + "://" + value.toString()); return new URI(scheme + "://" + value.toString());
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new CloudRuntimeException("Unable to convert to isolation type URI: " + value); throw new CloudRuntimeException("Unable to convert to isolation type URI: " + value);

View File

@ -25,8 +25,6 @@ import java.util.List;
import com.cloud.network.Network.Service; import com.cloud.network.Network.Service;
/** /**
* This defines the specifics of a physical network service provider * This defines the specifics of a physical network service provider
* *

View File

@ -17,7 +17,6 @@
*/ */
package com.cloud.network; package com.cloud.network;
/** /**
* PhysicalNetworkNames provides the labels to identify per traffic type * PhysicalNetworkNames provides the labels to identify per traffic type
* the physical networks available to the host . * the physical networks available to the host .
@ -84,5 +83,4 @@ public class PhysicalNetworkSetupInfo {
this.mgmtVlan = mgmtVlan; this.mgmtVlan = mgmtVlan;
} }
} }

View File

@ -23,8 +23,6 @@ package com.cloud.network;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
/** /**
* This defines the specifics of a physical network traffic type * This defines the specifics of a physical network traffic type
* *

View File

@ -22,19 +22,22 @@ import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter;
import com.cloud.utils.component.PluggableService;
public interface VirtualNetworkApplianceService { public interface VirtualNetworkApplianceService {
/** /**
* Starts domain router * Starts domain router
* @param cmd the command specifying router's id *
* @param cmd
* the command specifying router's id
* @return DomainRouter object * @return DomainRouter object
*/ */
VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
/** /**
* Reboots domain router * Reboots domain router
* @param cmd the command specifying router's id *
* @param cmd
* the command specifying router's id
* @return router if successful * @return router if successful
*/ */
VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
@ -43,8 +46,11 @@ public interface VirtualNetworkApplianceService {
/** /**
* Stops domain router * Stops domain router
* @param id of the router *
* @param forced just do it. caller knows best. * @param id
* of the router
* @param forced
* just do it. caller knows best.
* @return router if successful, null otherwise * @return router if successful, null otherwise
* @throws ResourceUnavailableException * @throws ResourceUnavailableException
* @throws ConcurrentOperationException * @throws ConcurrentOperationException

View File

@ -23,8 +23,12 @@ public interface VirtualRouterProvider {
VirtualRouter, VirtualRouter,
ElasticLoadBalancerVm ElasticLoadBalancerVm
} }
public VirtualRouterProviderType getType(); public VirtualRouterProviderType getType();
public long getId(); public long getId();
public boolean isEnabled(); public boolean isEnabled();
public long getNspId(); public long getNspId();
} }

View File

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

View File

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

View File

@ -31,24 +31,34 @@ public interface RulesService {
/** /**
* Creates a port forwarding rule between two ip addresses or between * Creates a port forwarding rule between two ip addresses or between
* an ip address and a virtual machine. * an ip address and a virtual machine.
* @param rule rule to be created. *
* @param vmId vm to be linked to. If specified the destination ip address is ignored. * @param rule
* @param openFirewall TODO * rule to be created.
* @param vmId
* vm to be linked to. If specified the destination ip address is ignored.
* @param openFirewall
* TODO
* @return PortForwardingRule if created. * @return PortForwardingRule if created.
* @throws NetworkRuleConflictException if conflicts in the network rules are detected. * @throws NetworkRuleConflictException
* if conflicts in the network rules are detected.
*/ */
PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException; PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException;
/** /**
* Revokes a port forwarding rule * Revokes a port forwarding rule
* @param ruleId the id of the rule to revoke. *
* @param ruleId
* the id of the rule to revoke.
* @param caller * @param caller
* @return * @return
*/ */
boolean revokePortForwardingRule(long ruleId, boolean apply); boolean revokePortForwardingRule(long ruleId, boolean apply);
/** /**
* List port forwarding rules assigned to an ip address * List port forwarding rules assigned to an ip address
* @param cmd the command object holding the criteria for listing port forwarding rules (the ipAddress) *
* @param cmd
* the command object holding the criteria for listing port forwarding rules (the ipAddress)
* @return list of port forwarding rules on the given address, empty list if no rules exist * @return list of port forwarding rules on the given address, empty list if no rules exist
*/ */
public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd); public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd);
@ -58,6 +68,7 @@ public interface RulesService {
boolean enableStaticNat(long ipAddressId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException; boolean enableStaticNat(long ipAddressId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException;
PortForwardingRule getPortForwardigRule(long ruleId); PortForwardingRule getPortForwardigRule(long ruleId);
FirewallRule getFirewallRule(long ruleId); FirewallRule getFirewallRule(long ruleId);
StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException; StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException;

View File

@ -21,7 +21,6 @@ import java.util.List;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
/** /**
* Definition for a StickinessPolicy * Definition for a StickinessPolicy
*/ */

View File

@ -19,7 +19,6 @@ package com.cloud.offering;
import java.util.Date; import java.util.Date;
/** /**
* Represents a disk offering that specifies what the end user needs in * Represents a disk offering that specifies what the end user needs in
* the disk offering. * the disk offering.

View File

@ -104,4 +104,5 @@ public interface NetworkOffering {
boolean getElasticLb(); boolean getElasticLb();
boolean getSpecifyIpRanges(); boolean getSpecifyIpRanges();
} }

View File

@ -31,18 +31,21 @@ package com.cloud.offering;
public interface OfferingManager { public interface OfferingManager {
/** /**
* Creates a service offering. * Creates a service offering.
*
* @return ServiceOffering * @return ServiceOffering
*/ */
ServiceOffering createServiceOffering(); ServiceOffering createServiceOffering();
/** /**
* Creates a disk offering. * Creates a disk offering.
*
* @return DiskOffering * @return DiskOffering
*/ */
DiskOffering createDiskOffering(); DiskOffering createDiskOffering();
/** /**
* Creates a network offering. * Creates a network offering.
*
* @return NetworkOffering * @return NetworkOffering
*/ */
NetworkOffering createNetworkOffering(); NetworkOffering createNetworkOffering();

View File

@ -42,7 +42,6 @@ public interface ServiceOffering {
*/ */
String getName(); String getName();
/** /**
* @return is this a system service offering * @return is this a system service offering
*/ */

View File

@ -33,11 +33,16 @@ public interface Cluster extends Grouping {
long getId(); long getId();
String getName(); String getName();
long getDataCenterId(); long getDataCenterId();
long getPodId(); long getPodId();
HypervisorType getHypervisorType(); HypervisorType getHypervisorType();
ClusterType getClusterType(); ClusterType getClusterType();
AllocationState getAllocationState(); AllocationState getAllocationState();
ManagedState getManagedState(); ManagedState getManagedState();
} }

View File

@ -23,8 +23,13 @@ import com.cloud.api.Identity;
import com.cloud.domain.PartOf; import com.cloud.domain.PartOf;
public interface Project extends PartOf, Identity { public interface Project extends PartOf, Identity {
public enum State {Active, Disabled, Suspended} public enum State {
public enum ListProjectResourcesCriteria {ListProjectResourcesOnly, SkipProjectResources} Active, Disabled, Suspended
}
public enum ListProjectResourcesCriteria {
ListProjectResourcesOnly, SkipProjectResources
}
String getDisplayText(); String getDisplayText();

View File

@ -1,8 +1,9 @@
package com.cloud.projects; package com.cloud.projects;
public interface ProjectAccount { public interface ProjectAccount {
public enum Role {Admin, Regular}; public enum Role {
Admin, Regular
};
long getAccountId(); long getAccountId();

View File

@ -5,7 +5,9 @@ import java.util.Date;
import com.cloud.acl.ControlledEntity; import com.cloud.acl.ControlledEntity;
public interface ProjectInvitation extends ControlledEntity { public interface ProjectInvitation extends ControlledEntity {
public enum State {Pending, Completed, Expired, Declined} public enum State {
Pending, Completed, Expired, Declined
}
long getId(); long getId();

View File

@ -8,15 +8,18 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.projects.ProjectAccount.Role; import com.cloud.projects.ProjectAccount.Role;
import com.cloud.user.Account; import com.cloud.user.Account;
public interface ProjectService { public interface ProjectService {
/** /**
* Creates a new project * Creates a new project
* *
* @param name - project name * @param name
* @param displayText - project display text * - project name
* @param accountName - account name of the project owner * @param displayText
* @param domainId - domainid of the project owner * - project display text
* @param accountName
* - account name of the project owner
* @param domainId
* - domainid of the project owner
* @return the project if created successfully, null otherwise * @return the project if created successfully, null otherwise
* @throws ResourceAllocationException * @throws ResourceAllocationException
*/ */
@ -25,7 +28,8 @@ public interface ProjectService {
/** /**
* Deletes a project * Deletes a project
* *
* @param id - project id * @param id
* - project id
* @return true if the project was deleted successfully, false otherwise * @return true if the project was deleted successfully, false otherwise
*/ */
boolean deleteProject(long id); boolean deleteProject(long id);
@ -33,7 +37,8 @@ public interface ProjectService {
/** /**
* Gets a project by id * Gets a project by id
* *
* @param id - project id * @param id
* - project id
* @return project object * @return project object
*/ */
Project getProject(long id); Project getProject(long id);
@ -58,7 +63,8 @@ public interface ProjectService {
List<? extends ProjectAccount> listProjectAccounts(long projectId, String accountName, String role, Long startIndex, Long pageSizeVal); List<? extends ProjectAccount> listProjectAccounts(long projectId, String accountName, String role, Long startIndex, Long pageSizeVal);
List<? extends ProjectInvitation> listProjectInvitations(Long id, Long projectId, String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive, boolean listAll); List<? extends ProjectInvitation> listProjectInvitations(Long id, Long projectId, String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive,
boolean listAll);
boolean updateInvitation(long projectId, String accountName, String token, boolean accept); boolean updateInvitation(long projectId, String accountName, String token, boolean accept);

View File

@ -3,7 +3,6 @@ package com.cloud.resource;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.StateMachine; import com.cloud.utils.fsm.StateMachine;
public enum ResourceState { public enum ResourceState {
@ -34,6 +33,7 @@ public enum ResourceState {
Unmanaged("Umanage a cluster"); Unmanaged("Umanage a cluster");
private final String comment; private final String comment;
private Event(String comment) { private Event(String comment) {
this.comment = comment; this.comment = comment;
} }

View File

@ -24,10 +24,13 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface Param { public @interface Param {
String name() default ""; String name() default "";
String propName() default ""; String propName() default "";
String description() default ""; String description() default "";
// 2 parameters below are used by cloudstack api // 2 parameters below are used by cloudstack api
Class<?> responseObject() default Object.class; Class<?> responseObject() default Object.class;
boolean includeInApiDoc() default true; boolean includeInApiDoc() default true;
} }

View File

@ -100,7 +100,8 @@ public interface ManagementService {
static final String Name = "management-server"; static final String Name = "management-server";
/** /**
* Retrieves the list of data centers with search criteria. Currently the only search criteria is "available" zones for the * Retrieves the list of data centers with search criteria. Currently the only search criteria is "available" zones
* for the
* account that invokes the API. By specifying available=true all zones which the account can access. By specifying * account that invokes the API. By specifying available=true all zones which the account can access. By specifying
* available=false the zones where the account has virtual machine instances will be returned. * available=false the zones where the account has virtual machine instances will be returned.
* *
@ -140,7 +141,8 @@ public interface ManagementService {
List<? extends Pod> searchForPods(ListPodsByCmd cmd); List<? extends Pod> searchForPods(ListPodsByCmd cmd);
/** /**
* Searches for servers by the specified search criteria Can search by: "name", "type", "state", "dataCenterId", "podId" * Searches for servers by the specified search criteria Can search by: "name", "type", "state", "dataCenterId",
* "podId"
* *
* @param cmd * @param cmd
* @return List of Hosts * @return List of Hosts
@ -158,7 +160,8 @@ public interface ManagementService {
VirtualMachineTemplate updateTemplate(UpdateTemplateCmd cmd); VirtualMachineTemplate updateTemplate(UpdateTemplateCmd cmd);
/** /**
* Obtains a list of events by the specified search criteria. Can search by: "username", "type", "level", "startDate", * Obtains a list of events by the specified search criteria. Can search by: "username", "type", "level",
* "startDate",
* "endDate" * "endDate"
* *
* @param c * @param c
@ -167,7 +170,8 @@ public interface ManagementService {
List<? extends Event> searchForEvents(ListEventsCmd c); List<? extends Event> searchForEvents(ListEventsCmd c);
/** /**
* Obtains a list of routers by the specified search criteria. Can search by: "userId", "name", "state", "dataCenterId", * Obtains a list of routers by the specified search criteria. Can search by: "userId", "name", "state",
* "dataCenterId",
* "podId", "hostId" * "podId", "hostId"
* *
* @param cmd * @param cmd
@ -175,9 +179,9 @@ public interface ManagementService {
*/ */
List<? extends VirtualRouter> searchForRouters(ListRoutersCmd cmd); List<? extends VirtualRouter> searchForRouters(ListRoutersCmd cmd);
/** /**
* Obtains a list of IP Addresses by the specified search criteria. Can search by: "userId", "dataCenterId", "address" * Obtains a list of IP Addresses by the specified search criteria. Can search by: "userId", "dataCenterId",
* "address"
* *
* @param cmd * @param cmd
* the command that wraps the search criteria * the command that wraps the search criteria
@ -236,7 +240,8 @@ public interface ManagementService {
* List ISOs that match the specified criteria. * List ISOs that match the specified criteria.
* *
* @param cmd * @param cmd
* The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId * The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account,
* and zoneId
* parameters. * parameters.
* @return list of ISOs * @return list of ISOs
*/ */
@ -246,7 +251,8 @@ public interface ManagementService {
* List templates that match the specified criteria. * List templates that match the specified criteria.
* *
* @param cmd * @param cmd
* The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, and zoneId * The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account,
* and zoneId
* parameters. * parameters.
* @return list of ISOs * @return list of ISOs
*/ */
@ -300,7 +306,8 @@ public interface ManagementService {
* Extracts the volume to a particular location. * Extracts the volume to a particular location.
* *
* @param cmd * @param cmd
* the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume exists), * the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume
* exists),
* id (the id of the volume) * id (the id of the volume)
* @throws URISyntaxException * @throws URISyntaxException
* @throws InternalErrorException * @throws InternalErrorException
@ -311,7 +318,9 @@ public interface ManagementService {
/** /**
* return an array of available hypervisors * return an array of available hypervisors
* @param zoneId TODO *
* @param zoneId
* TODO
* *
* @return an array of available hypervisors in the cloud * @return an array of available hypervisors in the cloud
*/ */
@ -381,7 +390,8 @@ public interface ManagementService {
* *
* @param cmd * @param cmd
* The api command class. * The api command class.
* @return A VO containing the key pair name, finger print for the public key and the private key material of the key pair. * @return A VO containing the key pair name, finger print for the public key and the private key material of the
* key pair.
*/ */
SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd); SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd);
@ -406,12 +416,15 @@ public interface ManagementService {
Type findSystemVMTypeById(long instanceId); Type findSystemVMTypeById(long instanceId);
/** /**
* List hosts for migrating the given VM. The API returns list of all hosts in the VM's cluster minus the current host and * List hosts for migrating the given VM. The API returns list of all hosts in the VM's cluster minus the current
* host and
* also a list of hosts that seem to have enough CPU and RAM capacity to host this VM. * also a list of hosts that seem to have enough CPU and RAM capacity to host this VM.
* *
* @param Long vmId * @param Long
* vmId
* Id of The VM to migrate * Id of The VM to migrate
* @return Pair<List<? extends Host>, List<? extends Host>> List of all Hosts in VM's cluster and list of Hosts with enough capacity * @return Pair<List<? extends Host>, List<? extends Host>> List of all Hosts in VM's cluster and list of Hosts with
* enough capacity
*/ */
Pair<List<? extends Host>, List<? extends Host>> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize); Pair<List<? extends Host>, List<? extends Host>> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize);

View File

@ -21,7 +21,10 @@ package com.cloud.storage;
public interface GuestOS { public interface GuestOS {
long getId(); long getId();
String getName(); String getName();
String getDisplayName(); String getDisplayName();
long getCategoryId(); long getCategoryId();
} }

View File

@ -70,15 +70,25 @@ public interface Snapshot extends ControlledEntity{
public static final long MANUAL_POLICY_ID = 0L; public static final long MANUAL_POLICY_ID = 0L;
Long getId(); Long getId();
long getAccountId(); long getAccountId();
long getVolumeId(); long getVolumeId();
String getPath(); String getPath();
String getName(); String getName();
Date getCreated(); Date getCreated();
Type getType(); Type getType();
Status getStatus(); Status getStatus();
HypervisorType getHypervisorType(); HypervisorType getHypervisorType();
boolean isRecursive(); boolean isRecursive();
short getsnapshotType(); short getsnapshotType();
} }

View File

@ -114,6 +114,7 @@ public class Storage {
return shared; return shared;
} }
} }
public static List<StoragePoolType> getNonSharedStoragePoolTypes() { public static List<StoragePoolType> getNonSharedStoragePoolTypes() {
List<StoragePoolType> nonSharedStoragePoolTypes = new ArrayList<StoragePoolType>(); List<StoragePoolType> nonSharedStoragePoolTypes = new ArrayList<StoragePoolType>();
for (StoragePoolType storagePoolType : StoragePoolType.values()) { for (StoragePoolType storagePoolType : StoragePoolType.values()) {
@ -125,5 +126,7 @@ public class Storage {
} }
public static enum StorageResourceType {STORAGE_POOL, STORAGE_HOST, SECONDARY_STORAGE, LOCAL_SECONDARY_STORAGE} public static enum StorageResourceType {
STORAGE_POOL, STORAGE_HOST, SECONDARY_STORAGE, LOCAL_SECONDARY_STORAGE
}
} }

View File

@ -25,6 +25,8 @@ import com.cloud.utils.component.Adapter;
*/ */
public interface StorageGuru extends Adapter { public interface StorageGuru extends Adapter {
void createVolume(); void createVolume();
void prepareVolume(); void prepareVolume();
void destroyVolume(); void destroyVolume();
} }

View File

@ -19,7 +19,6 @@ package com.cloud.storage;
import java.util.Date; import java.util.Date;
import com.cloud.host.Status;
import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.StoragePoolType;
/** /**
@ -60,7 +59,6 @@ public interface StoragePool {
*/ */
Date getUpdateTime(); Date getUpdateTime();
/** /**
* @return availability zone. * @return availability zone.
*/ */
@ -71,13 +69,11 @@ public interface StoragePool {
*/ */
long getCapacityBytes(); long getCapacityBytes();
/** /**
* @return available storage in bytes * @return available storage in bytes
*/ */
long getAvailableBytes(); long getAvailableBytes();
Long getClusterId(); Long getClusterId();
/** /**

View File

@ -38,7 +38,8 @@ public interface StorageService {
* Create StoragePool based on uri * Create StoragePool based on uri
* *
* @param cmd * @param cmd
* the command object that specifies the zone, cluster/pod, URI, details, etc. to use to create the storage pool. * the command object that specifies the zone, cluster/pod, URI, details, etc. to use to create the
* storage pool.
* @return * @return
* @throws ResourceInUseException * @throws ResourceInUseException
* @throws IllegalArgumentException * @throws IllegalArgumentException
@ -52,7 +53,8 @@ public interface StorageService {
* Creates the database object for a volume based on the given criteria * Creates the database object for a volume based on the given criteria
* *
* @param cmd * @param cmd
* the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, name) * the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot,
* name)
* @return the volume object * @return the volume object
* @throws PermissionDeniedException * @throws PermissionDeniedException
*/ */
@ -62,7 +64,8 @@ public interface StorageService {
* Creates the volume based on the given criteria * Creates the volume based on the given criteria
* *
* @param cmd * @param cmd
* the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, name) * the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot,
* name)
* @return the volume object * @return the volume object
*/ */
Volume createVolume(CreateVolumeCmd cmd); Volume createVolume(CreateVolumeCmd cmd);

View File

@ -21,9 +21,14 @@ import com.cloud.agent.api.to.SwiftTO;
public interface Swift { public interface Swift {
public long getId(); public long getId();
public String getUrl(); public String getUrl();
public String getAccount(); public String getAccount();
public String getUserName(); public String getUserName();
public String getKey(); public String getKey();
public SwiftTO toSwiftTO(); public SwiftTO toSwiftTO();
} }

View File

@ -22,9 +22,17 @@ import java.util.Date;
public interface Upload { public interface Upload {
public static enum Status {UNKNOWN, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS, NOT_COPIED, COPY_IN_PROGRESS, COPY_ERROR, COPY_COMPLETE, DOWNLOAD_URL_CREATED, DOWNLOAD_URL_NOT_CREATED, ERROR} public static enum Status {
public static enum Type {VOLUME, TEMPLATE, ISO} UNKNOWN, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS, NOT_COPIED, COPY_IN_PROGRESS, COPY_ERROR, COPY_COMPLETE, DOWNLOAD_URL_CREATED, DOWNLOAD_URL_NOT_CREATED, ERROR
public static enum Mode {FTP_UPLOAD, HTTP_DOWNLOAD} }
public static enum Type {
VOLUME, TEMPLATE, ISO
}
public static enum Mode {
FTP_UPLOAD, HTTP_DOWNLOAD
}
long getHostId(); long getHostId();

View File

@ -24,7 +24,9 @@ import java.util.Date;
* *
*/ */
public interface VMTemplateStorageResourceAssoc { public interface VMTemplateStorageResourceAssoc {
public static enum Status {UNKNOWN, DOWNLOAD_ERROR, NOT_DOWNLOADED, DOWNLOAD_IN_PROGRESS, DOWNLOADED, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS} public static enum Status {
UNKNOWN, DOWNLOAD_ERROR, NOT_DOWNLOADED, DOWNLOAD_IN_PROGRESS, DOWNLOADED, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS
}
String getInstallPath(); String getInstallPath();

View File

@ -42,19 +42,24 @@ public interface SnapshotService {
List<? extends Snapshot> listSnapshots(ListSnapshotsCmd cmd); List<? extends Snapshot> listSnapshots(ListSnapshotsCmd cmd);
/** /**
* Delete specified snapshot from the specified. If no other policies are assigned it calls destroy snapshot. This will be * Delete specified snapshot from the specified. If no other policies are assigned it calls destroy snapshot. This
* will be
* used for manual snapshots too. * used for manual snapshots too.
* @param snapshotId TODO *
* @param snapshotId
* TODO
*/ */
boolean deleteSnapshot(long snapshotId); boolean deleteSnapshot(long snapshotId);
/** /**
* Creates a policy with specified schedule. maxSnaps specifies the number of most recent snapshots that are to be retained. * Creates a policy with specified schedule. maxSnaps specifies the number of most recent snapshots that are to be
* retained.
* If the number of snapshots go beyond maxSnaps the oldest snapshot is deleted * If the number of snapshots go beyond maxSnaps the oldest snapshot is deleted
* *
* @param cmd * @param cmd
* the command that * the command that
* @param policyOwner TODO * @param policyOwner
* TODO
* @return the newly created snapshot policy if success, null otherwise * @return the newly created snapshot policy if success, null otherwise
*/ */
SnapshotPolicy createPolicy(CreateSnapshotPolicyCmd cmd, Account policyOwner); SnapshotPolicy createPolicy(CreateSnapshotPolicyCmd cmd, Account policyOwner);
@ -84,7 +89,9 @@ public interface SnapshotService {
/** /**
* Create a snapshot of a volume * Create a snapshot of a volume
* @param snapshotOwner TODO *
* @param snapshotOwner
* TODO
* @param cmd * @param cmd
* the API command wrapping the parameters for creating the snapshot (mainly volumeId) * the API command wrapping the parameters for creating the snapshot (mainly volumeId)
* *

View File

@ -17,8 +17,6 @@
*/ */
package com.cloud.storage.template; package com.cloud.storage.template;
public class TemplateInfo { public class TemplateInfo {
String templateName; String templateName;
String installPath; String installPath;
@ -80,4 +78,5 @@ public class TemplateInfo {
public void setSize(long size) { public void setSize(long size) {
this.size = size; this.size = size;
} }
} }

View File

@ -27,13 +27,17 @@ import com.cloud.storage.Storage.TemplateType;
public interface VirtualMachineTemplate extends ControlledEntity { public interface VirtualMachineTemplate extends ControlledEntity {
public static enum BootloaderType { PyGrub, HVM, External, CD }; public static enum BootloaderType {
PyGrub, HVM, External, CD
};
public enum TemplateFilter { public enum TemplateFilter {
featured, // returns templates that have been marked as featured and public featured, // returns templates that have been marked as featured and public
self, // returns templates that have been registered or created by the calling user self, // returns templates that have been registered or created by the calling user
selfexecutable, // same as self, but only returns templates that are ready to be deployed with selfexecutable, // same as self, but only returns templates that are ready to be deployed with
sharedexecutable, // ready templates that have been granted to the calling user by another user sharedexecutable, // ready templates that have been granted to the calling user by another user
executable, // templates that are owned by the calling user, or public templates, that can be used to deploy a new VM executable, // templates that are owned by the calling user, or public templates, that can be used to deploy a
// new VM
community, // returns templates that have been marked as public but not featured community, // returns templates that have been marked as public but not featured
all // all templates (only usable by admins) all // all templates (only usable by admins)
} }

View File

@ -51,9 +51,14 @@ public interface Account extends ControlledEntity {
public static final long ACCOUNT_ID_SYSTEM = 1; public static final long ACCOUNT_ID_SYSTEM = 1;
public long getId(); public long getId();
public String getAccountName(); public String getAccountName();
public short getType(); public short getType();
public State getState(); public State getState();
public Date getRemoved(); public Date getRemoved();
public String getNetworkDomain(); public String getNetworkDomain();
} }

View File

@ -38,24 +38,38 @@ public interface AccountService {
/** /**
* Creates a new user and account, stores the password as is so encrypted passwords are recommended. * Creates a new user and account, stores the password as is so encrypted passwords are recommended.
* @param userName TODO *
* @param password TODO * @param userName
* @param firstName TODO * TODO
* @param lastName TODO * @param password
* @param email TODO * TODO
* @param timezone TODO * @param firstName
* @param accountName TODO * TODO
* @param accountType TODO * @param lastName
* @param domainId TODO * TODO
* @param networkDomain TODO * @param email
* TODO
* @param timezone
* TODO
* @param accountName
* TODO
* @param accountType
* TODO
* @param domainId
* TODO
* @param networkDomain
* TODO
* *
* @return the user if created successfully, null otherwise * @return the user if created successfully, null otherwise
*/ */
UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, Map<String, String> details); UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain,
Map<String, String> details);
/** /**
* Deletes a user by userId * Deletes a user by userId
* @param accountId - id of the account do delete *
* @param accountId
* - id of the account do delete
* *
* @return true if delete was successful, false otherwise * @return true if delete was successful, false otherwise
*/ */
@ -64,7 +78,8 @@ public interface AccountService {
/** /**
* Disables a user by userId * Disables a user by userId
* *
* @param userId - the userId * @param userId
* - the userId
* @return UserAccount object * @return UserAccount object
*/ */
UserAccount disableUser(long userId); UserAccount disableUser(long userId);
@ -72,13 +87,15 @@ public interface AccountService {
/** /**
* Enables a user * Enables a user
* *
* @param userId - the userId * @param userId
* - the userId
* @return UserAccount object * @return UserAccount object
*/ */
UserAccount enableUser(long userId); UserAccount enableUser(long userId);
/** /**
* Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses allocated/etc. * Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses
* allocated/etc.
* *
* @param userId * @param userId
* @return UserAccount object * @return UserAccount object
@ -95,8 +112,11 @@ public interface AccountService {
/** /**
* Disables an account by accountName and domainId * Disables an account by accountName and domainId
* @param accountName TODO *
* @param domainId TODO * @param accountName
* TODO
* @param domainId
* TODO
* @param accountId * @param accountId
* @param disabled * @param disabled
* account if success * account if success
@ -109,19 +129,22 @@ public interface AccountService {
* *
* @param accountName * @param accountName
* - the enableAccount command defining the accountId to be deleted. * - the enableAccount command defining the accountId to be deleted.
* @param domainId TODO * @param domainId
* TODO
* @param accountId * @param accountId
* @return account object * @return account object
*/ */
Account enableAccount(String accountName, Long domainId, Long accountId); Account enableAccount(String accountName, Long domainId, Long accountId);
/** /**
* Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP addresses * Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP
* addresses
* allocated/etc. * allocated/etc.
* *
* @param accountName * @param accountName
* - the LockAccount command defining the accountId to be locked. * - the LockAccount command defining the accountId to be locked.
* @param domainId TODO * @param domainId
* TODO
* @param accountId * @param accountId
* @return account object * @return account object
*/ */
@ -142,6 +165,7 @@ public interface AccountService {
User getSystemUser(); User getSystemUser();
User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId); User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId);
boolean deleteUser(DeleteUserCmd deleteUserCmd); boolean deleteUser(DeleteUserCmd deleteUserCmd);
boolean isAdmin(short accountType); boolean isAdmin(short accountType);

View File

@ -46,4 +46,5 @@ public interface DomainService {
List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd) List<? extends Domain> searchForDomainChildren(ListDomainChildrenCmd cmd)
throws PermissionDeniedException; throws PermissionDeniedException;
} }

View File

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

View File

@ -87,7 +87,8 @@ public class UserContext {
// TODO: we should enforce explicit UserContext setup at major entry-points for security concerns, // TODO: we should enforce explicit UserContext setup at major entry-points for security concerns,
// however, there are many places that run background jobs assume the system context. // however, there are many places that run background jobs assume the system context.
// //
// If there is a security concern, all entry points from user (including the front end that takes HTTP request in and // If there is a security concern, all entry points from user (including the front end that takes HTTP
// request in and
// the core async-job manager that runs commands from user) have explicitly setup the UserContext. // the core async-job manager that runs commands from user) have explicitly setup the UserContext.
// //
return s_adminContext; return s_adminContext;

View File

@ -18,7 +18,6 @@
package com.cloud.vm; package com.cloud.vm;
import com.cloud.exception.ResourceAllocationException;
public interface BareMetalVmService extends UserVmService { public interface BareMetalVmService extends UserVmService {
} }

View File

@ -105,6 +105,7 @@ public class DiskProfile {
public void setUseLocalStorage(boolean useLocalStorage) { public void setUseLocalStorage(boolean useLocalStorage) {
this.useLocalStorage = useLocalStorage; this.useLocalStorage = useLocalStorage;
} }
/** /**
* @return Is this volume recreatable? A volume is recreatable if the disk's content can be * @return Is this volume recreatable? A volume is recreatable if the disk's content can be
* reconstructed from the template. * reconstructed from the template.

View File

@ -23,8 +23,11 @@ import com.cloud.acl.ControlledEntity;
public interface InstanceGroup extends ControlledEntity { public interface InstanceGroup extends ControlledEntity {
long getId(); long getId();
String getName(); String getName();
Date getCreated(); Date getCreated();
Short getAccountType(); Short getAccountType();
} }

View File

@ -92,7 +92,8 @@ public interface Nic {
long getId(); long getId();
/** /**
* @return reservation id returned by the allocation source. This can be the String version of the database id if the * @return reservation id returned by the allocation source. This can be the String version of the database id if
* the
* allocation source does not need it's own implementation of the reservation id. This is passed back to the * allocation source does not need it's own implementation of the reservation id. This is passed back to the
* allocation source to release the resource. * allocation source to release the resource.
*/ */

View File

@ -121,9 +121,11 @@ public interface UserVmService {
* Create a template database record in preparation for creating a private template. * Create a template database record in preparation for creating a private template.
* *
* @param cmd * @param cmd
* the command object that defines the name, display text, snapshot/volume, bits, public/private, etc. for the * the command object that defines the name, display text, snapshot/volume, bits, public/private, etc.
* for the
* private template * private template
* @param templateOwner TODO * @param templateOwner
* TODO
* @return the vm template object if successful, null otherwise * @return the vm template object if successful, null otherwise
* @throws ResourceAllocationException * @throws ResourceAllocationException
*/ */
@ -154,10 +156,14 @@ public interface UserVmService {
* @param displayName * @param displayName
* - an optional user generated name for the virtual machine * - an optional user generated name for the virtual machine
* @param diskOfferingId * @param diskOfferingId
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is * - the ID of the disk offering for the virtual machine. If the template is of ISO format, the
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. * diskOfferingId is
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume * for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk * volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk
* Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT
* Disk
* Volume created * Volume created
* @param diskSize * @param diskSize
* - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId * - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId
@ -166,17 +172,22 @@ public interface UserVmService {
* @param hypervisor * @param hypervisor
* - the hypervisor on which to deploy the virtual machine * - the hypervisor on which to deploy the virtual machine
* @param userData * @param userData
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary * - an optional binary data that can be sent to the virtual machine upon a successful deployment. This
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP * binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported.
* Using HTTP
* GET (via querystring), you can send up to 2KB of data after base64 encoding * GET (via querystring), you can send up to 2KB of data after base64 encoding
* @param sshKeyPair * @param sshKeyPair
* - name of the ssh key pair used to login to the virtual machine * - name of the ssh key pair used to login to the virtual machine
* @param requestedIps TODO * @param requestedIps
* @param defaultIp TODO * TODO
* @param defaultIp
* TODO
* @param accountName * @param accountName
* - an optional account for the virtual machine. Must be used with domainId * - an optional account for the virtual machine. Must be used with domainId
* @param domainId * @param domainId
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also
* be used
* @return UserVm object if successful. * @return UserVm object if successful.
* *
* @throws InsufficientCapacityException * @throws InsufficientCapacityException
@ -192,7 +203,8 @@ public interface UserVmService {
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException;
/** /**
* Creates a User VM in Advanced Zone (Security Group feature is enabled) in the database and returns the VM to the caller. * Creates a User VM in Advanced Zone (Security Group feature is enabled) in the database and returns the VM to the
* caller.
* *
* @param zone * @param zone
* - availability zone for the virtual machine * - availability zone for the virtual machine
@ -209,10 +221,14 @@ public interface UserVmService {
* @param displayName * @param displayName
* - an optional user generated name for the virtual machine * - an optional user generated name for the virtual machine
* @param diskOfferingId * @param diskOfferingId
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is * - the ID of the disk offering for the virtual machine. If the template is of ISO format, the
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. * diskOfferingId is
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume * for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk * volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk
* Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT
* Disk
* Volume created * Volume created
* @param diskSize * @param diskSize
* - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId * - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId
@ -221,17 +237,22 @@ public interface UserVmService {
* @param hypervisor * @param hypervisor
* - the hypervisor on which to deploy the virtual machine * - the hypervisor on which to deploy the virtual machine
* @param userData * @param userData
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary * - an optional binary data that can be sent to the virtual machine upon a successful deployment. This
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP * binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported.
* Using HTTP
* GET (via querystring), you can send up to 2KB of data after base64 encoding * GET (via querystring), you can send up to 2KB of data after base64 encoding
* @param sshKeyPair * @param sshKeyPair
* - name of the ssh key pair used to login to the virtual machine * - name of the ssh key pair used to login to the virtual machine
* @param requestedIps TODO * @param requestedIps
* @param defaultIp TODO * TODO
* @param defaultIp
* TODO
* @param accountName * @param accountName
* - an optional account for the virtual machine. Must be used with domainId * - an optional account for the virtual machine. Must be used with domainId
* @param domainId * @param domainId
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also
* be used
* @return UserVm object if successful. * @return UserVm object if successful.
* *
* @throws InsufficientCapacityException * @throws InsufficientCapacityException
@ -243,11 +264,13 @@ public interface UserVmService {
* @throws InsufficientResourcesException * @throws InsufficientResourcesException
*/ */
UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List<Long> networkIdList, List<Long> securityGroupIdList, UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List<Long> networkIdList, List<Long> securityGroupIdList,
Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Map<Long, String> requestedIps, String defaultIp, String keyboard) Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, String userData, String sshKeyPair, Map<Long, String> requestedIps,
String defaultIp, String keyboard)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException;
/** /**
* Creates a User VM in Advanced Zone (Security Group feature is disabled) in the database and returns the VM to the caller. * Creates a User VM in Advanced Zone (Security Group feature is disabled) in the database and returns the VM to the
* caller.
* *
* @param zone * @param zone
* - availability zone for the virtual machine * - availability zone for the virtual machine
@ -262,10 +285,14 @@ public interface UserVmService {
* @param displayName * @param displayName
* - an optional user generated name for the virtual machine * - an optional user generated name for the virtual machine
* @param diskOfferingId * @param diskOfferingId
* - the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is * - the ID of the disk offering for the virtual machine. If the template is of ISO format, the
* for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. * diskOfferingId is
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume * for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk * volume.
* If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk
* Volume
* created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT
* Disk
* Volume created * Volume created
* @param diskSize * @param diskSize
* - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId * - the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId
@ -274,17 +301,22 @@ public interface UserVmService {
* @param hypervisor * @param hypervisor
* - the hypervisor on which to deploy the virtual machine * - the hypervisor on which to deploy the virtual machine
* @param userData * @param userData
* - an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary * - an optional binary data that can be sent to the virtual machine upon a successful deployment. This
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP * binary
* data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported.
* Using HTTP
* GET (via querystring), you can send up to 2KB of data after base64 encoding * GET (via querystring), you can send up to 2KB of data after base64 encoding
* @param sshKeyPair * @param sshKeyPair
* - name of the ssh key pair used to login to the virtual machine * - name of the ssh key pair used to login to the virtual machine
* @param requestedIps TODO * @param requestedIps
* @param defaultIp TODO * TODO
* @param defaultIp
* TODO
* @param accountName * @param accountName
* - an optional account for the virtual machine. Must be used with domainId * - an optional account for the virtual machine. Must be used with domainId
* @param domainId * @param domainId
* - an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also
* be used
* @return UserVm object if successful. * @return UserVm object if successful.
* *
* @throws InsufficientCapacityException * @throws InsufficientCapacityException
@ -359,10 +391,14 @@ public interface UserVmService {
UserVm getUserVm(long vmId); UserVm getUserVm(long vmId);
/** /**
* Migrate the given VM to the destination host provided. The API returns the migrated VM if migration succeeds. Only Root * Migrate the given VM to the destination host provided. The API returns the migrated VM if migration succeeds.
* Only Root
* Admin can migrate a VM. * Admin can migrate a VM.
* @param destinationStorage TODO *
* @param Long vmId * @param destinationStorage
* TODO
* @param Long
* vmId
* vmId of The VM to migrate * vmId of The VM to migrate
* @param Host * @param Host
* destinationHost to migrate the VM * destinationHost to migrate the VM

View File

@ -26,7 +26,6 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.utils.fsm.StateMachine2; import com.cloud.utils.fsm.StateMachine2;
import com.cloud.utils.fsm.StateObject; import com.cloud.utils.fsm.StateObject;
/** /**
* VirtualMachine describes the properties held by a virtual machine * VirtualMachine describes the properties held by a virtual machine
* *
@ -45,7 +44,6 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
Unknown(false, "VM state is unknown."), Unknown(false, "VM state is unknown."),
Shutdowned(false, "VM is shutdowned from inside"); Shutdowned(false, "VM is shutdowned from inside");
private final boolean _transitional; private final boolean _transitional;
String _description; String _description;
@ -73,7 +71,8 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
s_fsm.addTransition(State.Stopped, VirtualMachine.Event.StopRequested, State.Stopped); s_fsm.addTransition(State.Stopped, VirtualMachine.Event.StopRequested, State.Stopped);
s_fsm.addTransition(State.Stopped, VirtualMachine.Event.AgentReportStopped, State.Stopped); s_fsm.addTransition(State.Stopped, VirtualMachine.Event.AgentReportStopped, State.Stopped);
// please pay attention about state transition to Error state, there should be only one case (failed in VM creation process) // please pay attention about state transition to Error state, there should be only one case (failed in VM
// creation process)
// that can have such transition // that can have such transition
s_fsm.addTransition(State.Stopped, VirtualMachine.Event.OperationFailedToError, State.Error); s_fsm.addTransition(State.Stopped, VirtualMachine.Event.OperationFailedToError, State.Error);
@ -247,6 +246,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
/** /**
* returns the guest OS ID * returns the guest OS ID
*
* @return guestOSId * @return guestOSId
*/ */
public long getGuestOSId(); public long getGuestOSId();
@ -265,6 +265,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
* @return id of the host it was assigned last time. * @return id of the host it was assigned last time.
*/ */
public Long getLastHostId(); public Long getLastHostId();
@Override @Override
public Long getHostId(); public Long getHostId();
@ -277,6 +278,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S
* @return should limit CPU usage to the service offering? * @return should limit CPU usage to the service offering?
*/ */
public boolean limitCpuUse(); public boolean limitCpuUse();
/** /**
* @return date when machine was created * @return date when machine was created
*/ */

View File

@ -27,7 +27,6 @@ import com.cloud.template.VirtualMachineTemplate;
import com.cloud.template.VirtualMachineTemplate.BootloaderType; import com.cloud.template.VirtualMachineTemplate.BootloaderType;
import com.cloud.user.Account; import com.cloud.user.Account;
/** /**
* VirtualMachineProfile describes one virtual machine. This object * VirtualMachineProfile describes one virtual machine. This object
* is passed to various adapters to be processed. Anything that is * is passed to various adapters to be processed. Anything that is
@ -37,11 +36,11 @@ import com.cloud.user.Account;
* on what the virtual machine profile should look like before it is * on what the virtual machine profile should look like before it is
* actually started on the hypervisor. * actually started on the hypervisor.
* *
* @param <T> a VirtualMachine * @param <T>
* a VirtualMachine
*/ */
public interface VirtualMachineProfile<T extends VirtualMachine> { public interface VirtualMachineProfile<T extends VirtualMachine> {
public static class Param { public static class Param {
public static final Param VmPassword = new Param("VmPassword"); public static final Param VmPassword = new Param("VmPassword");
@ -131,6 +130,7 @@ public interface VirtualMachineProfile<T extends VirtualMachine> {
void setParameter(Param name, Object value); void setParameter(Param name, Object value);
void setBootLoaderType(BootloaderType bootLoader); void setBootLoaderType(BootloaderType bootLoader);
BootloaderType getBootLoaderType(); BootloaderType getBootLoaderType();
Map<Param, Object> getParameters(); Map<Param, Object> getParameters();

View File

@ -21,7 +21,9 @@ package com.cloud.vm;
public interface VmStats { public interface VmStats {
// vm related stats // vm related stats
public double getCPUUtilization(); public double getCPUUtilization();
public double getNetworkReadKBs(); public double getNetworkReadKBs();
public double getNetworkWriteKBs(); public double getNetworkWriteKBs();
} }

View File

@ -49,7 +49,8 @@ public class ResourceLimitVO implements ResourceLimit {
@Column(name = "max") @Column(name = "max")
private Long max; private Long max;
public ResourceLimitVO() {} public ResourceLimitVO() {
}
public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) { public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) {
this.type = type; this.type = type;

View File

@ -531,12 +531,13 @@ public class XenServerConnectionPool {
s_logger.debug(msg); s_logger.debug(msg);
throw new CloudRuntimeException(msg); throw new CloudRuntimeException(msg);
} }
Host host = null;
synchronized (poolUuid.intern()) { synchronized (poolUuid.intern()) {
// Let's see if it is an existing connection. // Let's see if it is an existing connection.
mConn = getConnect(poolUuid); mConn = getConnect(poolUuid);
if (mConn != null){ if (mConn != null){
try{ try{
Host.getByUuid(mConn, hostUuid); host = Host.getByUuid(mConn, hostUuid);
} catch (Types.SessionInvalid e) { } catch (Types.SessionInvalid e) {
s_logger.debug("Session thgrough ip " + mConn.getIp() + " is invalid for pool(" + poolUuid + ") due to " + e.toString()); s_logger.debug("Session thgrough ip " + mConn.getIp() + " is invalid for pool(" + poolUuid + ") due to " + e.toString());
try { try {
@ -635,6 +636,45 @@ public class XenServerConnectionPool {
} }
} }
} }
if ( mConn != null ) {
if (s_managePool) {
try {
Map<String, String> args = new HashMap<String, String>();
host.callPlugin(mConn, "echo", "main", args);
} catch (Types.SessionInvalid e) {
if (s_logger.isDebugEnabled()) {
String msg = "Catch Exception: " + e.getClass().getName() + " Can't connect host " + ipAddress + " due to " + e.toString();
s_logger.debug(msg);
}
PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword());
} catch (Types.CannotContactHost e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Catch Exception: " + e.getClass().getName() + " Can't connect host " + ipAddress + " due to " + e.toString();
s_logger.debug(msg);
}
PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword());
} catch (Types.HostOffline e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Catch Exception: " + e.getClass().getName() + " Host is offline " + ipAddress + " due to " + e.toString();
s_logger.debug(msg);
}
PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword());
} catch (Types.HostNotLive e ) {
String msg = "Catch Exception: " + e.getClass().getName() + " Host Not Live " + ipAddress + " due to " + e.toString();
if (s_logger.isDebugEnabled()) {
s_logger.debug(msg);
}
PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword());
} catch (Exception e) {
String msg = "Master can not talk to Slave " + hostUuid + " IP " + ipAddress;
if (s_logger.isDebugEnabled()) {
s_logger.debug(msg);
}
throw new CloudRuntimeException(msg);
}
}
}
return mConn; return mConn;
} }
@ -879,24 +919,6 @@ public class XenServerConnectionPool {
} }
loginWithPassword(this, _username, _password, APIVersion.latest().toString()); loginWithPassword(this, _username, _password, APIVersion.latest().toString());
method_params[0] = getSessionReference(); method_params[0] = getSessionReference();
} catch (Types.CannotContactHost e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Cannot Contact Host for method: " + method_call + " due to " + e.toString();
s_logger.debug(msg);
}
throw e;
} catch (Types.HostOffline e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Host Offline for method: " + method_call + " due to " + e.toString();
s_logger.debug(msg);
}
throw e;
} catch (Types.HostNotLive e ) {
if (s_logger.isDebugEnabled()) {
String msg = "Host is Not alive for method: " + method_call + " due to " + e.toString();
s_logger.debug(msg);
}
throw e;
} catch (XmlRpcClientException e) { } catch (XmlRpcClientException e) {
s_logger.debug("XmlRpcClientException for method: " + method_call + " due to " + e.getMessage()); s_logger.debug("XmlRpcClientException for method: " + method_call + " due to " + e.getMessage());
removeConnect(_poolUuid); removeConnect(_poolUuid);

View File

@ -278,7 +278,8 @@ public class ApiResponseHelper implements ResponseGenerator {
Long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId()); Long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId());
Long ips = ipLimit - ipTotal; 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(); Long ipsLeft = ApiDBUtils.countFreePublicIps();
boolean unlimited = true; boolean unlimited = true;
if (ips.longValue() > ipsLeft.longValue()) { if (ips.longValue() > ipsLeft.longValue()) {
@ -354,7 +355,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return accountResponse; return accountResponse;
} }
@Override @Override
public UserResponse createUserResponse(UserAccount user) { public UserResponse createUserResponse(UserAccount user) {
UserResponse userResponse = new UserResponse(); UserResponse userResponse = new UserResponse();
@ -529,7 +529,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return policyResponse; return policyResponse;
} }
@Override @Override
public HostResponse createHostResponse(Host host) { public HostResponse createHostResponse(Host host) {
return createHostResponse(host, EnumSet.of(HostDetails.all)); return createHostResponse(host, EnumSet.of(HostDetails.all));
@ -1209,7 +1208,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return response; return response;
} }
@Override @Override
public List<UserVmResponse> createUserVmResponse(String objectName, EnumSet<VMDetails> details, UserVm... userVms) { public List<UserVmResponse> createUserVmResponse(String objectName, EnumSet<VMDetails> details, UserVm... userVms) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
@ -1234,8 +1232,6 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setName(userVm.getHostName()); userVmResponse.setName(userVm.getHostName());
userVmResponse.setCreated(userVm.getCreated()); userVmResponse.setCreated(userVm.getCreated());
userVmResponse.setHaEnable(userVm.isHaEnabled()); userVmResponse.setHaEnable(userVm.isHaEnabled());
if (userVm.getDisplayName() != null) { if (userVm.getDisplayName() != null) {
@ -1265,7 +1261,6 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setZoneId(zone.getId()); userVmResponse.setZoneId(zone.getId());
userVmResponse.setZoneName(zone.getName()); userVmResponse.setZoneName(zone.getName());
// if user is an admin, display host id // if user is an admin, display host id
if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) { if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) {
Host host = hosts.get(userVm.getHostId()); Host host = hosts.get(userVm.getHostId());
@ -1326,7 +1321,6 @@ public class ApiResponseHelper implements ResponseGenerator {
} }
} }
if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) { if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) {
// ISO Info // ISO Info
VMTemplateVO iso = templates.get(userVm.getIsoId()); VMTemplateVO iso = templates.get(userVm.getIsoId());
@ -1493,7 +1487,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return vmResponses; return vmResponses;
} }
@Override @Override
public DomainRouterResponse createDomainRouterResponse(VirtualRouter router) { public DomainRouterResponse createDomainRouterResponse(VirtualRouter router) {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
@ -1553,7 +1546,6 @@ public class ApiResponseHelper implements ResponseGenerator {
populateOwner(routerResponse, router); populateOwner(routerResponse, router);
DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterIdToDeployIn()); DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterIdToDeployIn());
if (zone != null) { if (zone != null) {
routerResponse.setZoneName(zone.getName()); routerResponse.setZoneName(zone.getName());
@ -1910,6 +1902,7 @@ public class ApiResponseHelper implements ResponseGenerator {
responses.add(templateResponse); responses.add(templateResponse);
return responses; return responses;
} }
@Override @Override
public List<TemplateResponse> createIsoResponses(long isoId, Long zoneId, boolean readyOnly) { public List<TemplateResponse> createIsoResponses(long isoId, Long zoneId, boolean readyOnly) {
@ -2153,6 +2146,7 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setResponses(netGrpResponses); response.setResponses(netGrpResponses);
return response; return response;
} }
@Override @Override
public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) { public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) {
SecurityGroupResponse response = new SecurityGroupResponse(); SecurityGroupResponse response = new SecurityGroupResponse();
@ -2225,7 +2219,6 @@ public class ApiResponseHelper implements ResponseGenerator {
} }
} }
jobResponse.setObjectName("asyncjobs"); jobResponse.setObjectName("asyncjobs");
return jobResponse; return jobResponse;
} }
@ -2272,7 +2265,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return responseEvent; return responseEvent;
} }
private List<CapacityVO> sumCapacities(List<? extends Capacity> hostCapacities) { private List<CapacityVO> sumCapacities(List<? extends Capacity> hostCapacities) {
Map<String, Long> totalCapacityMap = new HashMap<String, Long>(); Map<String, Long> totalCapacityMap = new HashMap<String, Long>();
Map<String, Long> usedCapacityMap = new HashMap<String, Long>(); Map<String, Long> usedCapacityMap = new HashMap<String, Long>();
@ -2339,11 +2331,16 @@ public class ApiResponseHelper implements ResponseGenerator {
if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved
// Capacity // Capacity
// accounts for // accounts
// stopped vms // for
// that have been // stopped
// stopped within // vms
// an interval // that
// have been
// stopped
// within
// an
// interval
usedCapacity += capacity.getReservedCapacity(); usedCapacity += capacity.getReservedCapacity();
} }
@ -2376,10 +2373,13 @@ public class ApiResponseHelper implements ResponseGenerator {
// accounts // accounts
// for // for
// stopped // stopped
// vms that // vms
// have been // that
// have
// been
// stopped // stopped
// within an // within
// an
// interval // interval
usedCapacity += capacity.getReservedCapacity(); usedCapacity += capacity.getReservedCapacity();
} }
@ -2814,7 +2814,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return response; return response;
} }
@Override @Override
public FirewallResponse createFirewallResponse(FirewallRule fwRule) { public FirewallResponse createFirewallResponse(FirewallRule fwRule) {
FirewallResponse response = new FirewallResponse(); FirewallResponse response = new FirewallResponse();
@ -2850,8 +2849,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return response; return response;
} }
public UserVmData newUserVmData(UserVm userVm) { public UserVmData newUserVmData(UserVm userVm) {
UserVmData userVmData = new UserVmData(); UserVmData userVmData = new UserVmData();
userVmData.setId(userVm.getId()); userVmData.setId(userVm.getId());
@ -3195,7 +3192,6 @@ public class ApiResponseHelper implements ResponseGenerator {
return response; return response;
} }
@Override @Override
public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) { public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) {
VirtualRouterProviderResponse response = new VirtualRouterProviderResponse(); VirtualRouterProviderResponse response = new VirtualRouterProviderResponse();
@ -3206,6 +3202,7 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setObjectName("virtualrouterelement"); response.setObjectName("virtualrouterelement");
return response; return response;
} }
@Override @Override
public LBStickinessResponse createLBStickinessPolicyResponse( public LBStickinessResponse createLBStickinessPolicyResponse(
StickinessPolicy stickinessPolicy, LoadBalancer lb) { StickinessPolicy stickinessPolicy, LoadBalancer lb) {
@ -3236,7 +3233,8 @@ public class ApiResponseHelper implements ResponseGenerator {
List<? extends StickinessPolicy> stickinessPolicies, LoadBalancer lb) { List<? extends StickinessPolicy> stickinessPolicies, LoadBalancer lb) {
LBStickinessResponse spResponse = new LBStickinessResponse(); LBStickinessResponse spResponse = new LBStickinessResponse();
if (lb == null) return spResponse ; if (lb == null)
return spResponse;
spResponse.setlbRuleId(lb.getId()); spResponse.setlbRuleId(lb.getId());
Account account = ApiDBUtils.findAccountById(lb.getAccountId()); Account account = ApiDBUtils.findAccountById(lb.getAccountId());
if (account != null) { if (account != null) {
@ -3285,4 +3283,5 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setObjectName("storagenetworkiprange"); response.setObjectName("storagenetworkiprange");
return response; return response;
} }
} }

View File

@ -1,4 +1,5 @@
/** /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
* *
* This software is licensed under the GNU General Public License v3 or later. * This software is licensed under the GNU General Public License v3 or later.
@ -333,7 +334,8 @@ public class ApiServer implements HttpRequestHandler {
if ("response".equalsIgnoreCase(paramValue[0])) { if ("response".equalsIgnoreCase(paramValue[0])) {
responseType = paramValue[1]; responseType = paramValue[1];
} else { } else {
// according to the servlet spec, the parameter map should be in the form (name=String, value=String[]), so // according to the servlet spec, the parameter map should be in the form (name=String,
// value=String[]), so
// parameter values will be stored in an array // parameter values will be stored in an array
parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] }); parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] });
} }
@ -557,10 +559,13 @@ public class ApiServer implements HttpRequestHandler {
auditTrailSb.append(" " + HttpServletResponse.SC_OK + " "); auditTrailSb.append(" " + HttpServletResponse.SC_OK + " ");
auditTrailSb.append(result); auditTrailSb.append(result);
/* /*
* if (command.equals("queryAsyncJobResult")){ //For this command we need to also log job status and job resultcode for * if (command.equals("queryAsyncJobResult")){ //For this command we need to also log job status and job
* resultcode for
* (Pair<String,Object> pair : resultValues){ String key = pair.first(); if (key.equals("jobstatus")){ * (Pair<String,Object> pair : resultValues){ String key = pair.first(); if (key.equals("jobstatus")){
* auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("="); auditTrailSb.append(pair.second()); * auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("=");
* }else if (key.equals("jobresultcode")){ auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("="); * auditTrailSb.append(pair.second());
* }else if (key.equals("jobresultcode")){ auditTrailSb.append(" "); auditTrailSb.append(key);
* auditTrailSb.append("=");
* auditTrailSb.append(pair.second()); } } }else { for (Pair<String,Object> pair : resultValues){ if * auditTrailSb.append(pair.second()); } } }else { for (Pair<String,Object> pair : resultValues){ if
* (pair.first().equals("jobid")){ // Its an async job so report the jobid auditTrailSb.append(" "); * (pair.first().equals("jobid")){ // Its an async job so report the jobid auditTrailSb.append(" ");
* auditTrailSb.append(pair.first()); auditTrailSb.append("="); auditTrailSb.append(pair.second()); } } } * auditTrailSb.append(pair.first()); auditTrailSb.append("="); auditTrailSb.append(pair.second()); } } }
@ -861,7 +866,8 @@ public class ApiServer implements HttpRequestHandler {
// FIXME: the following two threads are copied from // FIXME: the following two threads are copied from
// http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java // http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java
// we have to cite a license if we are using this code directly, so we need to add the appropriate citation or modify the // we have to cite a license if we are using this code directly, so we need to add the appropriate citation or
// modify the
// code to be very specific to our needs // code to be very specific to our needs
static class ListenerThread extends Thread { static class ListenerThread extends Thread {
private HttpService _httpService = null; private HttpService _httpService = null;

View File

@ -48,13 +48,15 @@ import com.cloud.utils.component.Manager;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
/** /**
* ConfigurationManager handles adding pods/zones, changing IP ranges, enabling external firewalls, and editing configuration values * ConfigurationManager handles adding pods/zones, changing IP ranges, enabling external firewalls, and editing
* configuration values
* *
*/ */
public interface ConfigurationManager extends ConfigurationService, Manager { public interface ConfigurationManager extends ConfigurationService, Manager {
/** /**
* Updates a configuration entry with a new value * Updates a configuration entry with a new value
*
* @param userId * @param userId
* @param name * @param name
* @param value * @param value
@ -63,6 +65,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
/** /**
* Creates a new service offering * Creates a new service offering
*
* @param name * @param name
* @param cpu * @param cpu
* @param ramSize * @param ramSize
@ -72,15 +75,18 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
* @param offerHA * @param offerHA
* @param domainId * @param domainId
* @param hostTag * @param hostTag
* @param networkRate TODO * @param networkRate
* TODO
* @param id * @param id
* @param useVirtualNetwork * @param useVirtualNetwork
* @return ID * @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); 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 * Creates a new disk offering
*
* @param domainId * @param domainId
* @param name * @param name
* @param description * @param description
@ -93,6 +99,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
/** /**
* Creates a new pod * Creates a new pod
*
* @param userId * @param userId
* @param podName * @param podName
* @param zoneId * @param zoneId
@ -101,13 +108,15 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
* @param startIp * @param startIp
* @param endIp * @param endIp
* @param allocationState * @param allocationState
* @param skipGatewayOverlapCheck (true if it is ok to not validate that gateway IP address overlap with Start/End IP of the POD) * @param skipGatewayOverlapCheck
* (true if it is ok to not validate that gateway IP address overlap with Start/End IP of the POD)
* @return Pod * @return Pod
*/ */
HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationState, boolean skipGatewayOverlapCheck); HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationState, boolean skipGatewayOverlapCheck);
/** /**
* Creates a new zone * Creates a new zone
*
* @param userId * @param userId
* @param zoneName * @param zoneName
* @param dns1 * @param dns1
@ -116,36 +125,44 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
* @param internalDns2 * @param internalDns2
* @param zoneType * @param zoneType
* @param allocationState * @param allocationState
* @param networkDomain TODO * @param networkDomain
* @param isSecurityGroupEnabled TODO * TODO
* @param isSecurityGroupEnabled
* TODO
* @return * @return
* @throws * @throws
* @throws * @throws
*/ */
DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String domain, Long domainId, NetworkType zoneType, String allocationState, String networkDomain, boolean isSecurityGroupEnabled); DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String domain, Long domainId, NetworkType zoneType, String allocationState,
String networkDomain, boolean isSecurityGroupEnabled);
/** /**
* Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated IP addresses. * Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated
* IP addresses.
*
* @param userId * @param userId
* @param vlanDbId * @param vlanDbId
* @return success/failure * @return success/failure
*/ */
boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId); boolean deleteVlanAndPublicIpRange(long userId, long vlanDbId);
/** /**
* Adds/deletes private IPs * Adds/deletes private IPs
* @param add - either true or false *
* @param add
* - either true or false
* @param podId * @param podId
* @param startIP * @param startIP
* @param endIP * @param endIP
* @return Message to display to user * @return Message to display to user
* @throws if unable to add private ip range * @throws if
* unable to add private ip range
*/ */
String changePrivateIPRange(boolean add, long podId, String startIP, String endIP); String changePrivateIPRange(boolean add, long podId, String startIP, String endIP);
/** /**
* Converts a comma separated list of tags to a List * Converts a comma separated list of tags to a List
*
* @param tags * @param tags
* @return List of tags * @return List of tags
*/ */
@ -153,6 +170,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
/** /**
* Converts a List of tags to a comma separated list * Converts a List of tags to a comma separated list
*
* @param tags * @param tags
* @return String containing a comma separated list of tags * @return String containing a comma separated list of tags
*/ */
@ -167,29 +185,40 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
void checkDiskOfferingAccess(Account caller, DiskOffering dof) void checkDiskOfferingAccess(Account caller, DiskOffering dof)
throws PermissionDeniedException; throws PermissionDeniedException;
/** /**
* Creates a new network offering * Creates a new network offering
*
* @param name * @param name
* @param displayText * @param displayText
* @param trafficType * @param trafficType
* @param tags * @param tags
* @param networkRate TODO * @param networkRate
* @param serviceProviderMap TODO * TODO
* @param isDefault TODO * @param serviceProviderMap
* @param type TODO * TODO
* @param systemOnly TODO * @param isDefault
* TODO
* @param type
* TODO
* @param systemOnly
* TODO
* @param serviceOfferingId * @param serviceOfferingId
* @param specifyIpRanges TODO * @param specifyIpRanges
* TODO
* @param id * @param id
* @param specifyVlan; * @param specifyVlan
* @param conserveMode; * ;
* @param conserveMode
* ;
* @return network offering object * @return network offering object
*/ */
NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, Integer networkRate, Map<Service, Set<Provider>> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode, Map<Service, Map<Capability, String>> serviceCapabilityMap, boolean specifyIpRanges); NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, Integer networkRate,
Map<Service, Set<Provider>> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode,
Map<Service, Map<Capability, String>> serviceCapabilityMap, boolean specifyIpRanges);
Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, long networkId, Long physicalNetworkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException; Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, long networkId,
Long physicalNetworkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException;
void createDefaultSystemNetworks(long zoneId) throws ConcurrentOperationException; void createDefaultSystemNetworks(long zoneId) throws ConcurrentOperationException;
@ -203,6 +232,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
/** /**
* Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system. * Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system.
*
* @param id * @param id
* @param name * @param name
* @param startIp * @param startIp

View File

@ -341,7 +341,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
throw new CloudRuntimeException("Failed to update configuration value. Please contact Cloud Support."); throw new CloudRuntimeException("Failed to update configuration value. Please contact Cloud Support.");
} }
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
if (Config.XenGuestNetwork.key().equalsIgnoreCase(name)) { if (Config.XenGuestNetwork.key().equalsIgnoreCase(name)) {
String sql = "update host_details set value=? where name=?"; String sql = "update host_details set value=? where name=?";
@ -705,7 +704,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
String checkPodCIDRs = _configDao.getValue("check.pod.cidrs"); String checkPodCIDRs = _configDao.getValue("check.pod.cidrs");
if (checkPodCIDRs == null || checkPodCIDRs.trim().isEmpty() || Boolean.parseBoolean(checkPodCIDRs)) { if (checkPodCIDRs == null || checkPodCIDRs.trim().isEmpty() || Boolean.parseBoolean(checkPodCIDRs)) {
checkPodCidrSubnets(zoneId, podId, cidr); 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); * checkCidrVlanOverlap(zoneId, cidr);
*/ */
@ -1177,8 +1177,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
List<HostPodVO> podsInZone = _podDao.listByDataCenterId(zoneId); List<HostPodVO> podsInZone = _podDao.listByDataCenterId(zoneId);
for (HostPodVO hostPod : podsInZone) { for (HostPodVO hostPod : podsInZone) {
String[] IpRange = hostPod.getDescription().split("-"); String[] IpRange = hostPod.getDescription().split("-");
if (IpRange[0]==null || IpRange[1]==null) continue; if (IpRange[0] == null || IpRange[1] == null)
if (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1])) continue; continue;
if (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))
continue;
if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { 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]); throw new InvalidParameterValueException("The Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]);
} }
@ -1228,7 +1230,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
} }
@Override @Override
@DB @DB
public boolean updateLDAP(LDAPConfigCmd cmd) { public boolean updateLDAP(LDAPConfigCmd cmd) {
@ -1266,51 +1267,58 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
DirContext ctx = new InitialDirContext(env); DirContext ctx = new InitialDirContext(env);
ctx.close(); ctx.close();
// store the result in DB COnfiguration // store the result in DB COnfiguration
ConfigurationVO cvo = _configDao.findByName(LDAPParams.hostname.toString()); ConfigurationVO cvo = _configDao.findByName(LDAPParams.hostname.toString());
if (cvo == null) { 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 = 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.setValue(hostname);
_configDao.persist(cvo);
cvo = _configDao.findByName(LDAPParams.port.toString()); cvo = _configDao.findByName(LDAPParams.port.toString());
if (cvo == null) { if (cvo == null) {
cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.port.toString(), null, "Specify the LDAP port if required, default is 389"); 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.setValue(port.toString());
_configDao.persist(cvo);
cvo = _configDao.findByName(LDAPParams.queryfilter.toString()); cvo = _configDao.findByName(LDAPParams.queryfilter.toString());
if (cvo == null) { 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 = 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.setValue(queryFilter);
_configDao.persist(cvo);
cvo = _configDao.findByName(LDAPParams.searchbase.toString()); cvo = _configDao.findByName(LDAPParams.searchbase.toString());
if (cvo == null) { 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 = 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(searchBase);
_configDao.persist(cvo);
cvo = _configDao.findByName(LDAPParams.usessl.toString()); cvo = _configDao.findByName(LDAPParams.usessl.toString());
if (cvo == null) { 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 = 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.setValue(useSSL.toString());
_configDao.persist(cvo);
cvo = _configDao.findByName(LDAPParams.dn.toString()); cvo = _configDao.findByName(LDAPParams.dn.toString());
if (cvo == null) { 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 = 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.setValue(bindDN);
_configDao.persist(cvo);
cvo = _configDao.findByName(LDAPParams.passwd.toString()); cvo = _configDao.findByName(LDAPParams.passwd.toString());
if (cvo == null) { if (cvo == null) {
cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.passwd.toString(), null, "Enter the password"); cvo = new ConfigurationVO("Advanced", "DEFAULT", "management-server", LDAPParams.passwd.toString(), null, "Enter the password");
} }
cvo.setValue(bindPasswd); _configDao.persist(cvo); cvo.setValue(bindPasswd);
} _configDao.persist(cvo);
catch (NamingException ne){ } catch (NamingException ne) {
ne.printStackTrace(); 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()) : ""));
} }
@ -1473,7 +1481,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
_networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage); _networkMgr.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage);
} catch (InvalidParameterValueException noStorage) { } catch (InvalidParameterValueException noStorage) {
PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(), TrafficType.Management); 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()); _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"); 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) { } catch (InvalidParameterValueException ex) {
@ -1547,7 +1556,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
} }
} }
@Override @Override
public void createDefaultSystemNetworks(long zoneId) throws ConcurrentOperationException { public void createDefaultSystemNetworks(long zoneId) throws ConcurrentOperationException {
DataCenterVO zone = _zoneDao.findById(zoneId); DataCenterVO zone = _zoneDao.findById(zoneId);
@ -2399,7 +2407,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
vlan = _vlanDao.persist(vlan); vlan = _vlanDao.persist(vlan);
if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId, physicalNetworkId)) { 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. // Public IP.
} }
@ -3126,7 +3135,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
} }
} }
void validateStaticNatServiceCapablities(Map<Capability, String> staticNatServiceCapabilityMap) { void validateStaticNatServiceCapablities(Map<Capability, String> staticNatServiceCapabilityMap) {
if (staticNatServiceCapabilityMap != null && !staticNatServiceCapabilityMap.isEmpty()) { if (staticNatServiceCapabilityMap != null && !staticNatServiceCapabilityMap.isEmpty()) {
if (staticNatServiceCapabilityMap.keySet().size() > 1) { if (staticNatServiceCapabilityMap.keySet().size() > 1) {
@ -3163,7 +3171,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
throw new InvalidParameterValueException("SpecifyIpRanges should be true if network offering's type is " + type); throw new InvalidParameterValueException("SpecifyIpRanges should be true if network offering's type is " + type);
} }
//specifyVlan should always be true for Shared network offerings and Isolated network offerings with specifyIpRanges = true // specifyVlan should always be true for Shared network offerings and Isolated network offerings with
// specifyIpRanges = true
if (!specifyVlan) { if (!specifyVlan) {
if (type == GuestType.Shared) { if (type == GuestType.Shared) {
throw new InvalidParameterValueException("SpecifyVlan should be true if network offering's type is " + type); throw new InvalidParameterValueException("SpecifyVlan should be true if network offering's type is " + type);
@ -3176,7 +3185,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
if (availability == NetworkOffering.Availability.Required) { if (availability == NetworkOffering.Availability.Required) {
boolean canOffBeRequired = (type == GuestType.Isolated && serviceProviderMap.containsKey(Service.SourceNat)); boolean canOffBeRequired = (type == GuestType.Isolated && serviceProviderMap.containsKey(Service.SourceNat));
if (!canOffBeRequired) { if (!canOffBeRequired) {
throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with "
+ Service.SourceNat.getName() + " enabled");
} }
// only one network offering in the system can be Required // only one network offering in the system can be Required
@ -3230,7 +3240,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
} }
} }
NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, isDefault, availability, tags, type, conserveMode, dedicatedLb, sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges); NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, isDefault, availability, tags, type, conserveMode, dedicatedLb,
sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges);
if (serviceOfferingId != null) { if (serviceOfferingId != null) {
offering.setServiceOfferingId(serviceOfferingId); offering.setServiceOfferingId(serviceOfferingId);
@ -3528,7 +3539,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
if (availability == NetworkOffering.Availability.Required) { if (availability == NetworkOffering.Availability.Required) {
boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkMgr.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat)); boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkMgr.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat));
if (!canOffBeRequired) { if (!canOffBeRequired) {
throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with "
+ Service.SourceNat.getName() + " enabled");
} }
// only one network offering in the system can be Required // only one network offering in the system can be Required

View File

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

View File

@ -59,7 +59,6 @@ public class ResourceLimitDaoImpl extends GenericDaoBase<ResourceLimitVO, Long>
} }
} }
@Override @Override
public boolean update(Long id, Long max) { public boolean update(Long id, Long max) {
ResourceLimitVO limit = findById(id); ResourceLimitVO limit = findById(id);

View File

@ -385,7 +385,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
try { try {
if (deviceMapLock.lock(120)) { if (deviceMapLock.lock(120)) {
try { try {
boolean dedicatedLB = offering.getDedicatedLB(); // does network offering supports a dedicated load balancer? boolean dedicatedLB = offering.getDedicatedLB(); // does network offering supports a dedicated
// load balancer?
long lbDeviceId; long lbDeviceId;
txn.start(); txn.start();
@ -398,7 +399,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
lbDeviceId = lbDevice.getId(); lbDeviceId = lbDevice.getId();
// persist the load balancer device id that will be used for this network. Once a network // persist the load balancer device id that will be used for this network. Once a network
// is implemented on a LB device then later on all rules will be programmed on to same device // is implemented on a LB device then later on all rules will be programmed on to same
// device
NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId);
_networkExternalLBDao.persist(networkLB); _networkExternalLBDao.persist(networkLB);
@ -415,11 +417,13 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
// if already attempted to provision load balancer then throw out of capacity exception, // if already attempted to provision load balancer then throw out of capacity exception,
if (tryLbProvisioning) { if (tryLbProvisioning) {
retry = false; retry = false;
//TODO: throwing warning instead of error for now as its possible another provider can service this network // TODO: throwing warning instead of error for now as its possible another provider can
// service this network
s_logger.warn("There are no load balancer device with the capacity for implementing this network"); s_logger.warn("There are no load balancer device with the capacity for implementing this network");
throw exception; throw exception;
} else { } else {
tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network tryLbProvisioning = true; // if possible provision a LB appliance in to the physical
// network
} }
} }
} finally { } finally {
@ -433,14 +437,16 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
deviceMapLock.releaseRef(); deviceMapLock.releaseRef();
} }
// there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance // there are no LB devices or there is no free capacity on the devices in the physical network so provision
// a new LB appliance
if (tryLbProvisioning) { if (tryLbProvisioning) {
// check if LB appliance can be dynamically provisioned // check if LB appliance can be dynamically provisioned
List<ExternalLoadBalancerDeviceVO> providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); List<ExternalLoadBalancerDeviceVO> providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider);
if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) {
for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) {
if (lbProviderDevice.getState() == LBDeviceState.Enabled) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) {
// acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, // acquire a private IP from the data center which will be used as management IP of
// provisioned LB appliance,
DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid());
if (dcPrivateIp == null) { if (dcPrivateIp == null) {
throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() +
@ -470,10 +476,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
String publicIf = createLbAnswer.getPublicInterface(); String publicIf = createLbAnswer.getPublicInterface();
String privateIf = createLbAnswer.getPrivateInterface(); String privateIf = createLbAnswer.getPrivateInterface();
//we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer // we have provisioned load balancer so add the appliance as cloudstack provisioned external
// load balancer
String dedicatedLb = offering.getDedicatedLB() ? "true" : "false"; String dedicatedLb = offering.getDedicatedLB() ? "true" : "false";
//acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) // acquire a public IP to associate with lb appliance (used as subnet IP to make the
// appliance part of private network)
PublicIp publicIp = _networkMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false); PublicIp publicIp = _networkMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false);
String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPNetmask = publicIp.getVlanNetmask();
String publicIPgateway = publicIp.getVlanGateway(); String publicIPgateway = publicIp.getVlanGateway();
@ -490,7 +498,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
if (lbAppliance != null) { if (lbAppliance != null) {
// mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned // mark the load balancer as cloudstack managed and set parent host id on which lb
// appliance is provisioned
ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId());
managedLb.setIsManagedDevice(true); managedLb.setIsManagedDevice(true);
managedLb.setParentHostId(lbProviderDevice.getHostId()); managedLb.setParentHostId(lbProviderDevice.getHostId());
@ -504,7 +513,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if (answer == null || !answer.getResult()) { if (answer == null || !answer.getResult()) {
s_logger.warn("Failed to destroy load balancer appliance created"); s_logger.warn("Failed to destroy load balancer appliance created");
} else { } else {
// release the public & private IP back to dc pool, as the load balancer appliance is now destroyed // release the public & private IP back to dc pool, as the load balancer
// appliance is now destroyed
_dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null);
_networkMgr.releasePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); _networkMgr.releasePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount());
} }
@ -583,7 +593,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
} }
// if we are here then there are no existing LB devices in shared use or the devices in shared use has no free capacity left // if we are here then there are no existing LB devices in shared use or the devices in shared use has no
// free capacity left
// so allocate a new load balancer configured for shared use from the pool of free LB devices // so allocate a new load balancer configured for shared use from the pool of free LB devices
lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free);
if (lbDevices != null && !lbDevices.isEmpty()) { if (lbDevices != null && !lbDevices.isEmpty()) {
@ -619,7 +630,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
boolean lbCloudManaged = lbDevice.getIsManagedDevice(); boolean lbCloudManaged = lbDevice.getIsManagedDevice();
if (!lbInUse && !lbCloudManaged) { if (!lbInUse && !lbCloudManaged) {
// this is the last network mapped to the load balancer device so set device allocation state to be free // this is the last network mapped to the load balancer device so set device allocation state to be
// free
lbDevice.setAllocationState(LBDeviceAllocationState.Free); lbDevice.setAllocationState(LBDeviceAllocationState.Free);
_externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice);
} }
@ -822,7 +834,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId()); mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId());
_inlineLoadBalancerNicMapDao.persist(mapping); _inlineLoadBalancerNicMapDao.persist(mapping);
// On the firewall provider for the network, create a static NAT rule between the source IP address and the load balancing IP address // On the firewall provider for the network, create a static NAT rule between the source IP
// address and the load balancing IP address
applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address()); applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address());
} else { } else {
loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); loadBalancingIpNic = _nicDao.findById(mapping.getNicId());
@ -832,7 +845,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
// Find the NIC that the mapping refers to // Find the NIC that the mapping refers to
loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); loadBalancingIpNic = _nicDao.findById(mapping.getNicId());
// On the firewall provider for the network, delete the static NAT rule between the source IP address and the load balancing IP address // On the firewall provider for the network, delete the static NAT rule between the source IP
// address and the load balancing IP address
applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address()); applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address());
// Delete the mapping between the source IP address and the load balancing IP address // Delete the mapping between the source IP address and the load balancing IP address
@ -1212,7 +1226,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
/* /*
* Creates/updates all necessary stats entries for an account and zone. * Creates/updates all necessary stats entries for an account and zone.
* Stats entries are created for source NAT IP addresses, static NAT rules, port forwarding rules, and load balancing rules * Stats entries are created for source NAT IP addresses, static NAT rules, port forwarding rules, and load
* balancing rules
*/ */
private boolean manageStatsEntries(boolean create, long accountId, long zoneId, Network network, private boolean manageStatsEntries(boolean create, long accountId, long zoneId, Network network,
HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) { HostVO externalLoadBalancer, ExternalNetworkResourceUsageAnswer lbAnswer) {
@ -1390,4 +1405,5 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
} }
return new DeleteHostAnswer(true); return new DeleteHostAnswer(true);
} }
} }

View File

@ -35,7 +35,6 @@ import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.ResourceUnavailableException;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.Network.Capability; import com.cloud.network.Network.Capability;
@ -73,11 +72,14 @@ public interface NetworkManager extends NetworkService {
* @param owner * @param owner
* @param type * @param type
* @param networkId * @param networkId
* @param requestedIp TODO * @param requestedIp
* @param allocatedBy TODO * TODO
* @param allocatedBy
* TODO
* @return * @return
* @throws InsufficientAddressCapacityException * @throws InsufficientAddressCapacityException
*/ */
PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isElastic) throws InsufficientAddressCapacityException; PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isElastic) throws InsufficientAddressCapacityException;
/** /**
@ -169,7 +171,8 @@ public interface NetworkManager extends NetworkService {
/** /**
* @throws InsufficientCapacityException * @throws InsufficientCapacityException
* Associates an ip address list to an account. The list of ip addresses are all addresses associated with the * Associates an ip address list to an account. The list of ip addresses are all addresses associated
* with the
* given vlan id. * given vlan id.
* @param userId * @param userId
* @param accountId * @param accountId

View File

@ -278,19 +278,32 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
PortForwardingRulesDao _portForwardingDao; PortForwardingRulesDao _portForwardingDao;
@Inject @Inject
ResourceLimitService _resourceLimitMgr; ResourceLimitService _resourceLimitMgr;
@Inject DomainRouterDao _routerDao; @Inject
@Inject DomainManager _domainMgr; DomainRouterDao _routerDao;
@Inject ProjectManager _projectMgr; @Inject
@Inject NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; DomainManager _domainMgr;
@Inject PhysicalNetworkDao _physicalNetworkDao; @Inject
@Inject PhysicalNetworkServiceProviderDao _pNSPDao; ProjectManager _projectMgr;
@Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject
@Inject LoadBalancerDao _lbDao; NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao;
@Inject PhysicalNetworkTrafficTypeDao _pNTrafficTypeDao; @Inject
@Inject AgentManager _agentMgr; PhysicalNetworkDao _physicalNetworkDao;
@Inject HostDao _hostDao; @Inject
@Inject NetworkServiceMapDao _ntwkSrvcDao; PhysicalNetworkServiceProviderDao _pNSPDao;
@Inject StorageNetworkManager _stnwMgr; @Inject
PortForwardingRulesDao _portForwardingRulesDao;
@Inject
LoadBalancerDao _lbDao;
@Inject
PhysicalNetworkTrafficTypeDao _pNTrafficTypeDao;
@Inject
AgentManager _agentMgr;
@Inject
HostDao _hostDao;
@Inject
NetworkServiceMapDao _ntwkSrvcDao;
@Inject
StorageNetworkManager _stnwMgr;
private final HashMap<String, NetworkOfferingVO> _systemNetworks = new HashMap<String, NetworkOfferingVO>(5); private final HashMap<String, NetworkOfferingVO> _systemNetworks = new HashMap<String, NetworkOfferingVO>(5);
@ -311,7 +324,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
private Map<String, String> _configs; private Map<String, String> _configs;
HashMap<Long, Long> _lastNetworkIdsToFree = new HashMap<Long, Long>(); HashMap<Long, Long> _lastNetworkIdsToFree = new HashMap<Long, Long>();
private static HashMap<Service, List<Provider>> s_serviceToImplementedProvidersMap = new HashMap<Service, List<Provider>>(); private static HashMap<Service, List<Provider>> s_serviceToImplementedProvidersMap = new HashMap<Service, List<Provider>>();
@ -378,7 +390,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
sc.setJoinParameters("vlan", "type", vlanUse); sc.setJoinParameters("vlan", "type", vlanUse);
if (requestedIp != null) { if (requestedIp != null) {
sc.addAnd("address", SearchCriteria.Op.EQ, requestedIp); sc.addAnd("address", SearchCriteria.Op.EQ, requestedIp);
errorMessage.append(": requested ip " + requestedIp + " is not available"); errorMessage.append(": requested ip " + requestedIp + " is not available");
@ -426,8 +437,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
long macAddress = NetUtils.createSequenceBasedMacAddress(addr.getMacAddress()); long macAddress = NetUtils.createSequenceBasedMacAddress(addr.getMacAddress());
return new PublicIp(addr, _vlanDao.findById(addr.getVlanId()), macAddress); return new PublicIp(addr, _vlanDao.findById(addr.getVlanId()), macAddress);
} }
@ -598,7 +607,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
markPublicIpAsAllocated(addr); markPublicIpAsAllocated(addr);
} else if (addr.getState() == IpAddress.State.Releasing) { } else if (addr.getState() == IpAddress.State.Releasing) {
// Cleanup all the resources for ip address if there are any, and only then un-assign ip in the system // Cleanup all the resources for ip address if there are any, and only then un-assign ip in the
// system
if (cleanupIpResources(addr.getId(), Account.ACCOUNT_ID_SYSTEM, _accountMgr.getSystemAccount())) { if (cleanupIpResources(addr.getId(), Account.ACCOUNT_ID_SYSTEM, _accountMgr.getSystemAccount())) {
_ipAddressDao.unassignIpAddress(addr.getId()); _ipAddressDao.unassignIpAddress(addr.getId());
} else { } else {
@ -665,7 +675,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
ipToServices.put(ip, services); ipToServices.put(ip, services);
//if IP in allocating state then it will not have any rules attached so skip IPAssoc to network service provider // if IP in allocating state then it will not have any rules attached so skip IPAssoc to network service
// provider
if (ip.getState() == State.Allocating) { if (ip.getState() == State.Allocating) {
continue; continue;
} }
@ -673,18 +684,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
// check if any active rules are applied on the public IP // check if any active rules are applied on the public IP
Set<Purpose> purposes = getPublicIpPurposeInRules(ip, false, includingFirewall); Set<Purpose> purposes = getPublicIpPurposeInRules(ip, false, includingFirewall);
if (purposes == null || purposes.isEmpty()) { if (purposes == null || purposes.isEmpty()) {
// since no active rules are there check if any rules are applied on the public IP but are in revoking state // since no active rules are there check if any rules are applied on the public IP but are in
// revoking state
purposes = getPublicIpPurposeInRules(ip, true, includingFirewall); purposes = getPublicIpPurposeInRules(ip, true, includingFirewall);
if (purposes == null || purposes.isEmpty()) { if (purposes == null || purposes.isEmpty()) {
// IP is not being used for any purpose so skip IPAssoc to network service provider // IP is not being used for any purpose so skip IPAssoc to network service provider
continue; continue;
} else { } else {
if (rulesRevoked) { if (rulesRevoked) {
// no active rules/revoked rules are associated with this public IP, so remove the association with the provider // no active rules/revoked rules are associated with this public IP, so remove the
// association with the provider
ip.setState(State.Releasing); ip.setState(State.Releasing);
} else { } else {
if (ip.getState() == State.Releasing) { if (ip.getState() == State.Releasing) {
// rules are not revoked yet, so don't let the network service provider revoke the IP association // rules are not revoked yet, so don't let the network service provider revoke the IP
// association
// mark IP is allocated so that IP association will not be removed from the provider // mark IP is allocated so that IP association will not be removed from the provider
ip.setState(State.Allocated); ip.setState(State.Allocated);
} }
@ -945,10 +959,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
// In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled // In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled
if (zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) { if (zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " + Service.SourceNat.getName() + " enabled"); throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the "
+ Service.SourceNat.getName() + " enabled");
} }
// Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network, and it // Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network,
// and it
// belongs to the system // belongs to the system
if (zone.getNetworkType() != NetworkType.Basic && network.getAccountId() != ipOwner.getId()) { if (zone.getNetworkType() != NetworkType.Basic && network.getAccountId() != ipOwner.getId()) {
throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP");
@ -1058,7 +1074,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
s_logger.warn("Failed to associate ip address " + ip); s_logger.warn("Failed to associate ip address " + ip);
_ipAddressDao.markAsUnavailable(ip.getId()); _ipAddressDao.markAsUnavailable(ip.getId());
if (!applyIpAssociations(network, true)) { if (!applyIpAssociations(network, true)) {
// if fail to apply ip assciations again, unassign ip address without updating resource count and // if fail to apply ip assciations again, unassign ip address without updating resource
// count and
// generating usage event as there is no need to keep it in the db // generating usage event as there is no need to keep it in the db
_ipAddressDao.unassignIpAddress(ip.getId()); _ipAddressDao.unassignIpAddress(ip.getId());
} }
@ -1112,7 +1129,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return success; return success;
} }
@Override @DB @Override
@DB
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
@ -1178,25 +1196,29 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
NetworkOfferingVO offering = null; NetworkOfferingVO offering = null;
if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOfferingWithSGService) == null) { if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOfferingWithSGService) == null) {
offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOfferingWithSGService, "Offering for Shared Security group enabled networks", TrafficType.Guest, null, true, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true); offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOfferingWithSGService, "Offering for Shared Security group enabled networks", TrafficType.Guest,
null, true, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true);
offering.setState(NetworkOffering.State.Enabled); offering.setState(NetworkOffering.State.Enabled);
_networkOfferingDao.update(offering.getId(), offering); _networkOfferingDao.update(offering.getId(), offering);
} }
if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOffering) == null) { if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOffering) == null) {
offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, null, true, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true); offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, null, true, Availability.Optional,
null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true);
offering.setState(NetworkOffering.State.Enabled); offering.setState(NetworkOffering.State.Enabled);
_networkOfferingDao.update(offering.getId(), offering); _networkOfferingDao.update(offering.getId(), offering);
} }
if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService) == null) { if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService) == null) {
offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM,NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, "Offering for Isolated networks with Source Nat service enabled", TrafficType.Guest, null, false, Availability.Required, null, defaultIsolatedSourceNatEnabledNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, false); offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, "Offering for Isolated networks with Source Nat service enabled",
TrafficType.Guest, null, false, Availability.Required, null, defaultIsolatedSourceNatEnabledNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, false);
offering.setState(NetworkOffering.State.Enabled); offering.setState(NetworkOffering.State.Enabled);
_networkOfferingDao.update(offering.getId(), offering); _networkOfferingDao.update(offering.getId(), offering);
} }
if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOffering) == null) { if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOffering) == null) {
offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, null, true, Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, true); offering = _configMgr.createNetworkOffering(Account.ACCOUNT_ID_SYSTEM, NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, null,
true, Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, true);
offering.setState(NetworkOffering.State.Enabled); offering.setState(NetworkOffering.State.Enabled);
_networkOfferingDao.update(offering.getId(), offering); _networkOfferingDao.update(offering.getId(), offering);
} }
@ -1338,7 +1360,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
try { try {
if (predefined == null || (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && predefined.getBroadcastDomainType() != BroadcastDomainType.Vlan)) { if (predefined == null
|| (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && predefined.getBroadcastDomainType() != BroadcastDomainType.Vlan)) {
List<NetworkVO> configs = _networksDao.listBy(owner.getId(), offering.getId(), plan.getDataCenterId()); List<NetworkVO> configs = _networksDao.listBy(owner.getId(), offering.getId(), plan.getDataCenterId());
if (configs.size() > 0) { if (configs.size() > 0) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
@ -1495,7 +1518,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
nics.add(vo); nics.add(vo);
Integer networkRate = getNetworkRate(config.getId(), vm.getId()); Integer networkRate = getNetworkRate(config.getId(), vm.getId());
vm.addNic(new NicProfile(vo, network.first(), vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network.first()), getNetworkTag(vm.getHypervisorType(), network.first()))); vm.addNic(new NicProfile(vo, network.first(), vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network.first()), getNetworkTag(vm.getHypervisorType(),
network.first())));
} }
if (nics.size() != networks.size()) { if (nics.size() != networks.size()) {
@ -1660,7 +1684,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
private void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, NetworkVO network, NetworkOfferingVO offering) private void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, NetworkVO network, NetworkOfferingVO offering)
throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException {
// If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a Shared source NAT rule, // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a
// Shared source NAT rule,
// associate a source NAT IP (if one isn't already associated with the network) // associate a source NAT IP (if one isn't already associated with the network)
boolean sharedSourceNat = offering.getSharedSourceNat(); boolean sharedSourceNat = offering.getSharedSourceNat();
@ -1737,7 +1762,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
ConcurrentOperationException, ResourceUnavailableException { ConcurrentOperationException, ResourceUnavailableException {
List<NicVO> nics = _nicDao.listByVmId(vmProfile.getId()); List<NicVO> nics = _nicDao.listByVmId(vmProfile.getId());
// we have to implement default nics first - to ensure that default network elements start up first in multiple nics // we have to implement default nics first - to ensure that default network elements start up first in multiple
// nics
// case) // case)
// (need for setting DNS on Dhcp to domR's Ip4 address) // (need for setting DNS on Dhcp to domR's Ip4 address)
Collections.sort(nics, new Comparator<NicVO>() { Collections.sort(nics, new Comparator<NicVO>() {
@ -1933,7 +1959,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
} }
@Deprecated // No one is using this method. @Deprecated
// No one is using this method.
public AccountVO getNetworkOwner(long networkId) { public AccountVO getNetworkOwner(long networkId) {
SearchCriteria<AccountVO> sc = AccountsUsingNetworkSearch.create(); SearchCriteria<AccountVO> sc = AccountsUsingNetworkSearch.create();
sc.setJoinParameters("nc", "config", networkId); sc.setJoinParameters("nc", "config", networkId);
@ -1942,7 +1969,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return accounts.size() != 0 ? accounts.get(0) : null; return accounts.size() != 0 ? accounts.get(0) : null;
} }
@Deprecated // No one is using this method. @Deprecated
// No one is using this method.
public List<NetworkVO> getNetworksforOffering(long offeringId, long dataCenterId, long accountId) { public List<NetworkVO> getNetworksforOffering(long offeringId, long dataCenterId, long accountId) {
return _networksDao.getNetworksForOffering(offeringId, dataCenterId, accountId); return _networksDao.getNetworksForOffering(offeringId, dataCenterId, accountId);
} }
@ -2201,7 +2229,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
// Regular user can create Guest Isolated Source Nat enabled network only // Regular user can create Guest Isolated Source Nat enabled network only
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != Network.GuestType.Isolated && areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))) { if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL
&& (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != Network.GuestType.Isolated
&& areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and network type " throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and network type "
+ Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled"); + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled");
} }
@ -2304,7 +2334,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
// if zone is basic, only Shared network offerings w/o source nat service are allowed // if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(networkOffering.getGuestType() == GuestType.Shared && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))) { if (!(networkOffering.getGuestType() == GuestType.Shared && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + " service are allowed"); throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName()
+ " service are allowed");
} }
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true // In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
@ -2332,7 +2363,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} else if (zone.getNetworkType() == NetworkType.Advanced) { } else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) { if (zone.isSecurityGroupEnabled()) {
//Only Account specific Isolated network with sourceNat service disabled are allowed in security group enabled zone // Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
boolean allowCreation = (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat)); boolean allowCreation = (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat));
if (!allowCreation) { if (!allowCreation) {
throw new InvalidParameterValueException("Only Account specific Isolated network with sourceNat service disabled are allowed in security group enabled zone"); throw new InvalidParameterValueException("Only Account specific Isolated network with sourceNat service disabled are allowed in security group enabled zone");
@ -2391,11 +2423,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
} }
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x limitation, remove after we introduce support for multiple ip ranges // In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network // with different Cidrs for the same Shared network
boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced && networkOffering.getTrafficType() == TrafficType.Guest && (networkOffering.getGuestType() == GuestType.Shared || (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat))); boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced && networkOffering.getTrafficType() == TrafficType.Guest
&& (networkOffering.getGuestType() == GuestType.Shared || (networkOffering.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(networkOffering.getId(), Service.SourceNat)));
if (cidr == null && cidrRequired) { if (cidr == null && cidrRequired) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of type " + Network.GuestType.Shared + " and network of type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled"); throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of type " + Network.GuestType.Shared + " and network of type " + GuestType.Isolated + " with service "
+ Service.SourceNat.getName() + " disabled");
} }
// No cidr can be specified in Basic zone // No cidr can be specified in Basic zone
@ -2574,16 +2609,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (isSystem == null || !isSystem) { if (isSystem == null || !isSystem) {
// Get domain level networks // Get domain level networks
if (domainId != null) { if (domainId != null) {
networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, domainId)); networksToReturn
.addAll(listDomainLevelNetworks(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter,
domainId));
} }
if (!permittedAccounts.isEmpty()) { if (!permittedAccounts.isEmpty()) {
networksToReturn.addAll(listAccountSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, permittedAccounts)); networksToReturn.addAll(listAccountSpecificNetworks(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter,
permittedAccounts));
} else if (domainId == null || listAll) { } else if (domainId == null || listAll) {
networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, path, isRecursive)); networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(
buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter, path,
isRecursive));
} }
} else { } else {
networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, specifyIpRanges), searchFilter); networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, specifyIpRanges),
searchFilter);
} }
if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) { if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) {
@ -2612,7 +2655,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
} }
private SearchCriteria<NetworkVO> buildNetworkSearchCriteria(SearchBuilder<NetworkVO> sb, String keyword, Long id, Boolean isSystem, Long zoneId, String guestIpType, String trafficType, Long physicalNetworkId, String aclType, boolean skipProjectNetworks, Boolean restartRequired, Boolean specifyIpRanges) { private SearchCriteria<NetworkVO> buildNetworkSearchCriteria(SearchBuilder<NetworkVO> sb, String keyword, Long id, Boolean isSystem, Long zoneId, String guestIpType, String trafficType, Long physicalNetworkId,
String aclType, boolean skipProjectNetworks, Boolean restartRequired, Boolean specifyIpRanges) {
SearchCriteria<NetworkVO> sc = sb.create(); SearchCriteria<NetworkVO> sc = sb.create();
if (isSystem != null) { if (isSystem != null) {
@ -2664,7 +2708,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return sc; return sc;
} }
private List<NetworkVO> listDomainLevelNetworks(SearchCriteria<NetworkVO> sc, Filter searchFilter, long domainId) { private List<NetworkVO> listDomainLevelNetworks(SearchCriteria<NetworkVO> sc, Filter searchFilter, long domainId) {
List<Long> networkIds = new ArrayList<Long>(); List<Long> networkIds = new ArrayList<Long>();
Set<Long> allowedDomains = _domainMgr.getDomainParentIds(domainId); Set<Long> allowedDomains = _domainMgr.getDomainParentIds(domainId);
@ -2790,7 +2833,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
private boolean shutdownNetworkElementsAndResources(ReservationContext context, boolean cleanupElements, NetworkVO network) { private boolean shutdownNetworkElementsAndResources(ReservationContext context, boolean cleanupElements, NetworkVO network) {
//1) Cleanup all the rules for the network. If it fails, just log the failure and proceed with shutting down the elements // 1) Cleanup all the rules for the network. If it fails, just log the failure and proceed with shutting down
// the elements
boolean cleanupResult = true; boolean cleanupResult = true;
try { try {
cleanupResult = shutdownNetworkResources(network.getId(), context.getAccount(), context.getCaller().getId()); cleanupResult = shutdownNetworkResources(network.getId(), context.getAccount(), context.getCaller().getId());
@ -2811,7 +2855,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (providersToShutdown.contains(element.getProvider())) { if (providersToShutdown.contains(element.getProvider())) {
try { try {
if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) {
s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network " + getPhysicalNetworkId(network)); s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network "
+ getPhysicalNetworkId(network));
success = false; success = false;
} }
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
@ -2886,7 +2931,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (providersToDestroy.contains(element.getProvider())) { if (providersToDestroy.contains(element.getProvider())) {
try { try {
if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) {
s_logger.warn("Unable to complete destroy of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network " + getPhysicalNetworkId(network)); s_logger.warn("Unable to complete destroy of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network "
+ getPhysicalNetworkId(network));
success = false; success = false;
} }
@ -2968,6 +3014,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
return true; return true;
} }
@Override @Override
/* The rules here is only the same kind of rule, e.g. all load balancing rules or all port forwarding rules */ /* The rules here is only the same kind of rule, e.g. all load balancing rules or all port forwarding rules */
public boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError) throws ResourceUnavailableException { public boolean applyRules(List<? extends FirewallRule> rules, boolean continueOnError) throws ResourceUnavailableException {
@ -3211,7 +3258,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
_networksDao.update(network.getId(), network); _networksDao.update(network.getId(), network);
} }
// This method re-programs the rules/ips for existing network // This method re-programs the rules/ips for existing network
protected boolean reprogramNetworkRules(long networkId, Account caller, NetworkVO network) throws ResourceUnavailableException { protected boolean reprogramNetworkRules(long networkId, Account caller, NetworkVO network) throws ResourceUnavailableException {
boolean success = true; boolean success = true;
@ -3271,7 +3317,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return _networksDao.getActiveNicsIn(networkId); return _networksDao.getActiveNicsIn(networkId);
} }
@Override @Override
public Map<Service, Map<Capability, String>> getNetworkCapabilities(long networkId) { public Map<Service, Map<Capability, String>> getNetworkCapabilities(long networkId) {
@ -3283,7 +3328,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
Service service = Service.getService(instance.getService()); Service service = Service.getService(instance.getService());
NetworkElement element = getElementImplementingProvider(instance.getProvider()); NetworkElement element = getElementImplementingProvider(instance.getProvider());
if (element != null) { if (element != null) {
Map<Service, Map<Capability, String>> elementCapabilities = element.getCapabilities();; Map<Service, Map<Capability, String>> elementCapabilities = element.getCapabilities();
;
if (elementCapabilities != null) { if (elementCapabilities != null) {
networkCapabilities.put(service, elementCapabilities.get(service)); networkCapabilities.put(service, elementCapabilities.get(service));
} }
@ -3307,7 +3353,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
NetworkElement element = getElementImplementingProvider(provider); NetworkElement element = getElementImplementingProvider(provider);
if (element != null) { if (element != null) {
Map<Service, Map<Capability, String>> elementCapabilities = element.getCapabilities();; Map<Service, Map<Capability, String>> elementCapabilities = element.getCapabilities();
;
if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { if (elementCapabilities == null || !elementCapabilities.containsKey(service)) {
throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider); throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider);
@ -3333,13 +3380,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering); throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering);
} }
//FIXME - in post 3.0 we are going to support multiple providers for the same service per network offering, so we have to calculate capabilities for all of them // FIXME - in post 3.0 we are going to support multiple providers for the same service per network offering, so
// we have to calculate capabilities for all of them
String provider = providers.get(0); String provider = providers.get(0);
//FIXME we return the capabilities of the first provider of the service - what if we have multiple providers for same Service? // FIXME we return the capabilities of the first provider of the service - what if we have multiple providers
// for same Service?
NetworkElement element = getElementImplementingProvider(provider); NetworkElement element = getElementImplementingProvider(provider);
if (element != null) { if (element != null) {
Map<Service, Map<Capability, String>> elementCapabilities = element.getCapabilities();; Map<Service, Map<Capability, String>> elementCapabilities = element.getCapabilities();
;
if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { if (elementCapabilities == null || !elementCapabilities.containsKey(service)) {
throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider); throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider);
@ -3439,7 +3489,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return guestNic.getIp4Address(); return guestNic.getIp4Address();
} }
private Nic getNicInNetworkIncludingRemoved(long vmId, long networkId) { private Nic getNicInNetworkIncludingRemoved(long vmId, long networkId) {
return _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(networkId, vmId); return _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(networkId, vmId);
} }
@ -3468,7 +3517,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (createNetwork) { if (createNetwork) {
List<? extends NetworkOffering> offerings = _configMgr.listNetworkOfferings(TrafficType.Guest, false); List<? extends NetworkOffering> offerings = _configMgr.listNetworkOfferings(TrafficType.Guest, false);
PhysicalNetwork physicalNetwork = translateZoneIdToPhysicalNetwork(zoneId); PhysicalNetwork physicalNetwork = translateZoneIdToPhysicalNetwork(zoneId);
network = createGuestNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, owner, false, null, physicalNetwork, zoneId, ACLType.Account, null); network = createGuestNetwork(offerings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, owner, false, null, physicalNetwork, zoneId,
ACLType.Account, null);
if (network == null) { if (network == null) {
s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId);
@ -3578,7 +3628,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return elements; return elements;
} }
@Override @Override
public boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkId) { public boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkId) {
boolean netscalerInNetwork = isProviderForNetwork(Network.Provider.Netscaler, networkId); boolean netscalerInNetwork = isProviderForNetwork(Network.Provider.Netscaler, networkId);
@ -3649,7 +3698,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
// remote access vpn can be enabled only for static nat ip, so this part should never be executed under normal // remote access vpn can be enabled only for static nat ip, so this part should never be executed under normal
// conditions // conditions
// only when ip address failed to be cleaned up as a part of account destroy and was marked as Releasing, this part of // only when ip address failed to be cleaned up as a part of account destroy and was marked as Releasing, this
// part of
// the code would be triggered // the code would be triggered
s_logger.debug("Cleaning up remote access vpns as a part of public IP id=" + ipId + " release..."); s_logger.debug("Cleaning up remote access vpns as a part of public IP id=" + ipId + " release...");
try { try {
@ -3781,7 +3831,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
} }
@Override @DB @Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true) @ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true)
public Network updateGuestNetwork(long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, Long networkOfferingId) { public Network updateGuestNetwork(long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, Long networkOfferingId) {
boolean restartNetwork = false; boolean restartNetwork = false;
@ -3881,7 +3932,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
//1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate states - Shutdown and Implementing // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate
// states - Shutdown and Implementing
boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated); boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated);
if (restartNetwork) { if (restartNetwork) {
if (validStateToShutdown) { if (validStateToShutdown) {
@ -3962,7 +4014,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
Network network = getNetwork(networkId); Network network = getNetwork(networkId);
NetworkOffering ntwkOff = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); NetworkOffering ntwkOff = _configMgr.getNetworkOffering(network.getNetworkOfferingId());
// For default userVm Default network and domR guest/public network, get rate information from the service offering; for other situations get information // For default userVm Default network and domR guest/public network, get rate information from the service
// offering; for other situations get information
// from the network offering // from the network offering
boolean isUserVmsDefaultNetwork = false; boolean isUserVmsDefaultNetwork = false;
boolean isDomRGuestOrPublicNetwork = false; boolean isDomRGuestOrPublicNetwork = false;
@ -4031,7 +4084,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return result; return result;
} }
private String getZoneNetworkDomain(long zoneId) { private String getZoneNetworkDomain(long zoneId) {
return _dcDao.findById(zoneId).getDomain(); return _dcDao.findById(zoneId).getDomain();
} }
@ -4103,7 +4155,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
} }
// static NAT rules can not programmed unless IP is associated with network service provider, so run IP association for // static NAT rules can not programmed unless IP is associated with network service provider, so run IP
// association for
// the network so as to ensure IP is associated before applying rules (in add state) // the network so as to ensure IP is associated before applying rules (in add state)
applyIpAssociations(network, false, continueOnError, publicIps); applyIpAssociations(network, false, continueOnError, publicIps);
@ -4261,7 +4314,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return canIpsUseOffering(publicIps, newNetworkOfferingId); return canIpsUseOffering(publicIps, newNetworkOfferingId);
} }
protected boolean canUpgradeProviders(long oldNetworkOfferingId, long newNetworkOfferingId) { protected boolean canUpgradeProviders(long oldNetworkOfferingId, long newNetworkOfferingId) {
// list of services and providers should be the same // list of services and providers should be the same
Map<Service, Set<Provider>> newServices = getNetworkOfferingServiceProvidersMap(newNetworkOfferingId); Map<Service, Set<Provider>> newServices = getNetworkOfferingServiceProvidersMap(newNetworkOfferingId);
@ -4454,11 +4506,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (newVnetRangeString != null) { if (newVnetRangeString != null) {
if (zone.getNetworkType() == NetworkType.Basic if (zone.getNetworkType() == NetworkType.Basic
|| (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { || (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) {
throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: "+ zone.isSecurityGroupEnabled()); throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: "
+ zone.isSecurityGroupEnabled());
} }
} }
if (tags != null && tags.size() > 1) { if (tags != null && tags.size() > 1) {
throw new InvalidParameterException("Unable to support more than one tag on network yet"); throw new InvalidParameterException("Unable to support more than one tag on network yet");
} }
@ -4545,7 +4597,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
network.setVnet(newVnetRangeString); network.setVnet(newVnetRangeString);
} }
_physicalNetworkDao.update(id, network); _physicalNetworkDao.update(id, network);
if (replaceVnet) { if (replaceVnet) {
@ -4554,7 +4605,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
for (Pair<Integer, Integer> vnetToAdd : vnetsToAdd) { for (Pair<Integer, Integer> vnetToAdd : vnetsToAdd) {
s_logger.debug("Adding vnet range " + vnetToAdd.first() + "-" + vnetToAdd.second() + " for the physicalNetwork id= "+id +" and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); s_logger.debug("Adding vnet range " + vnetToAdd.first() + "-" + vnetToAdd.second() + " for the physicalNetwork id= " + id + " and zone id=" + network.getDataCenterId()
+ " as a part of updatePhysicalNetwork call");
_dcDao.addVnet(network.getDataCenterId(), network.getId(), vnetToAdd.first(), vnetToAdd.second()); _dcDao.addVnet(network.getDataCenterId(), network.getId(), vnetToAdd.first(), vnetToAdd.second());
} }
@ -4578,7 +4630,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
checkIfPhysicalNetworkIsDeletable(physicalNetworkId); checkIfPhysicalNetworkIsDeletable(physicalNetworkId);
// delete vlans for this zone // delete vlans for this zone
List<VlanVO> vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId); List<VlanVO> vlans = _vlanDao.listVlansByPhysicalNetworkId(physicalNetworkId);
for (VlanVO vlan : vlans) { for (VlanVO vlan : vlans) {
@ -4602,10 +4653,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
// delete traffic types // delete traffic types
_pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId); _pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId);
boolean success = _physicalNetworkDao.remove(physicalNetworkId); boolean success = _physicalNetworkDao.remove(physicalNetworkId);
return success; return success;
} }
@ -4625,11 +4674,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
networks.add(2, "there are networks associated to this physical network"); networks.add(2, "there are networks associated to this physical network");
tablesToCheck.add(networks); tablesToCheck.add(networks);
/*List<String> privateIP = new ArrayList<String>(); /*
privateIP.add(0, "op_dc_ip_address_alloc"); * List<String> privateIP = new ArrayList<String>();
privateIP.add(1, "data_center_id"); * privateIP.add(0, "op_dc_ip_address_alloc");
privateIP.add(2, "there are private IP addresses allocated for this zone"); * privateIP.add(1, "data_center_id");
tablesToCheck.add(privateIP);*/ * privateIP.add(2, "there are private IP addresses allocated for this zone");
* tablesToCheck.add(privateIP);
*/
List<String> publicIP = new ArrayList<String>(); List<String> publicIP = new ArrayList<String>();
publicIP.add(0, "user_ip_address"); publicIP.add(0, "user_ip_address");
@ -4637,8 +4688,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
publicIP.add(2, "there are public IP addresses allocated for this physical network"); publicIP.add(2, "there are public IP addresses allocated for this physical network");
tablesToCheck.add(publicIP); tablesToCheck.add(publicIP);
for (List<String> table : tablesToCheck) { for (List<String> table : tablesToCheck) {
String tableName = table.get(0); String tableName = table.get(0);
String column = table.get(1); String column = table.get(1);
@ -4982,7 +5031,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return getPhysicalNetworkServiceProvider(providerId); return getPhysicalNetworkServiceProvider(providerId);
} }
@Override @Override
public long findPhysicalNetworkId(long zoneId, String tag) { public long findPhysicalNetworkId(long zoneId, String tag) {
List<PhysicalNetworkVO> pNtwks = _physicalNetworkDao.listByZone(zoneId); List<PhysicalNetworkVO> pNtwks = _physicalNetworkDao.listByZone(zoneId);
@ -5046,7 +5094,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return offeringsToReturn; return offeringsToReturn;
} }
private boolean cleanupNetworkResources(long networkId, Account caller, long callerUserId) { private boolean cleanupNetworkResources(long networkId, Account caller, long callerUserId) {
boolean success = true; boolean success = true;
Network network = getNetwork(networkId); Network network = getNetwork(networkId);
@ -5107,7 +5154,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return success; return success;
} }
private boolean shutdownNetworkResources(long networkId, Account caller, long callerUserId) { private boolean shutdownNetworkResources(long networkId, Account caller, long callerUserId) {
// This method cleans up network rules on the backend w/o touching them in the DB // This method cleans up network rules on the backend w/o touching them in the DB
boolean success = true; boolean success = true;
@ -5265,7 +5311,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system"); throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system");
} }
Networks.TrafficType trafficType = null; Networks.TrafficType trafficType = null;
if (trafficTypeStr != null && !trafficTypeStr.isEmpty()) { if (trafficTypeStr != null && !trafficTypeStr.isEmpty()) {
try { try {
@ -5278,7 +5323,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (_pNTrafficTypeDao.isTrafficTypeSupported(physicalNetworkId, trafficType)) { if (_pNTrafficTypeDao.isTrafficTypeSupported(physicalNetworkId, trafficType)) {
throw new CloudRuntimeException("This physical network already supports the traffic type: " + trafficType); throw new CloudRuntimeException("This physical network already supports the traffic type: " + trafficType);
} }
//For Storage, Control, Management, Public check if the zone has any other physical network with this traffictype already present // For Storage, Control, Management, Public check if the zone has any other physical network with this
// traffictype already present
// If yes, we cant add these traffics to one more physical network in the zone. // If yes, we cant add these traffics to one more physical network in the zone.
if (TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType) || TrafficType.Storage.equals(trafficType)) { if (TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType) || TrafficType.Storage.equals(trafficType)) {
@ -5290,7 +5336,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (TrafficType.Storage.equals(trafficType)) { if (TrafficType.Storage.equals(trafficType)) {
List<SecondaryStorageVmVO> ssvms = _stnwMgr.getSSVMWithNoStorageNetwork(network.getDataCenterId()); List<SecondaryStorageVmVO> ssvms = _stnwMgr.getSSVMWithNoStorageNetwork(network.getDataCenterId());
if (!ssvms.isEmpty()) { if (!ssvms.isEmpty()) {
StringBuilder sb = new StringBuilder("Cannot add " + trafficType + " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)"); StringBuilder sb = new StringBuilder(
"Cannot add "
+ trafficType
+ " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)");
sb.append("SSVMs:"); sb.append("SSVMs:");
for (SecondaryStorageVmVO ssvm : ssvms) { for (SecondaryStorageVmVO ssvm : ssvms) {
sb.append(ssvm.getInstanceName()).append(":").append(ssvm.getState()); sb.append(ssvm.getInstanceName()).append(":").append(ssvm.getState());
@ -5321,15 +5370,20 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
private String getDefaultXenNetworkLabel(TrafficType trafficType) { private String getDefaultXenNetworkLabel(TrafficType trafficType) {
String xenLabel = null; String xenLabel = null;
switch (trafficType) { switch (trafficType) {
case Public: xenLabel = _configDao.getValue(Config.XenPublicNetwork.key()); case Public:
xenLabel = _configDao.getValue(Config.XenPublicNetwork.key());
break; break;
case Guest: xenLabel = _configDao.getValue(Config.XenGuestNetwork.key()); case Guest:
xenLabel = _configDao.getValue(Config.XenGuestNetwork.key());
break; break;
case Storage: xenLabel = _configDao.getValue(Config.XenStorageNetwork1.key()); case Storage:
xenLabel = _configDao.getValue(Config.XenStorageNetwork1.key());
break; break;
case Management: xenLabel = _configDao.getValue(Config.XenPrivateNetwork.key()); case Management:
xenLabel = _configDao.getValue(Config.XenPrivateNetwork.key());
break; break;
case Control: xenLabel = "cloud_link_local_network"; case Control:
xenLabel = "cloud_link_local_network";
break; break;
} }
return xenLabel; return xenLabel;
@ -5398,7 +5452,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return _pNTrafficTypeDao.listBy(physicalNetworkId); return _pNTrafficTypeDao.listBy(physicalNetworkId);
} }
@Override @Override
public PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType) { public PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType) {
@ -5559,7 +5612,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
private boolean isProviderEnabled(PhysicalNetworkServiceProvider provider) { private boolean isProviderEnabled(PhysicalNetworkServiceProvider provider) {
if (provider == null || provider.getState() != PhysicalNetworkServiceProvider.State.Enabled) { //TODO: check for other states: Shutdown? if (provider == null || provider.getState() != PhysicalNetworkServiceProvider.State.Enabled) { // TODO: check
// for other states: Shutdown?
return false; return false;
} }
return true; return true;
@ -5592,7 +5646,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return true; return true;
} }
@Override @Override
public String getNetworkTag(HypervisorType hType, Network network) { public String getNetworkTag(HypervisorType hType, Network network) {
// no network tag for control traffic type // no network tag for control traffic type
@ -5631,7 +5684,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
physicalNetworkId = pNtwks.get(0).getId(); physicalNetworkId = pNtwks.get(0).getId();
} else { } else {
// locate physicalNetwork with supported traffic type // locate physicalNetwork with supported traffic type
//We can make this assumptions based on the fact that Public/Management/Control traffic types are supported only in one physical network in the zone in 3.0 // We can make this assumptions based on the fact that Public/Management/Control traffic types are
// supported only in one physical network in the zone in 3.0
for (PhysicalNetworkVO pNtwk : pNtwks) { for (PhysicalNetworkVO pNtwk : pNtwks) {
if (_pNTrafficTypeDao.isTrafficTypeSupported(pNtwk.getId(), network.getTrafficType())) { if (_pNTrafficTypeDao.isTrafficTypeSupported(pNtwk.getId(), network.getTrafficType())) {
physicalNetworkId = pNtwk.getId(); physicalNetworkId = pNtwk.getId();
@ -5643,7 +5697,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return physicalNetworkId; return physicalNetworkId;
} }
@Override @Override
public NetworkVO getExclusiveGuestNetwork(long zoneId) { public NetworkVO getExclusiveGuestNetwork(long zoneId) {
List<NetworkVO> networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, zoneId, GuestType.Shared, TrafficType.Guest); List<NetworkVO> networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, zoneId, GuestType.Shared, TrafficType.Guest);
@ -5700,7 +5753,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
for (NetworkOfferingServiceMapVO serviceMap : servicesMap) { for (NetworkOfferingServiceMapVO serviceMap : servicesMap) {
if (svcProviders.containsKey(serviceMap.getService())) { if (svcProviders.containsKey(serviceMap.getService())) {
//FIXME - right now we pick up the first provider from the list, need to add more logic based on provider load, etc // FIXME - right now we pick up the first provider from the list, need to add more logic based on
// provider load, etc
continue; continue;
} }
@ -5824,7 +5878,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} }
servicesSet.delete(servicesSet.toString().length() - 2, servicesSet.toString().length()); servicesSet.delete(servicesSet.toString().length() - 2, servicesSet.toString().length());
throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services: " + servicesSet.toString() + " for Service Provider " + provider.getName()); throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services: " + servicesSet.toString() + " for Service Provider "
+ provider.getName());
} }
} }
for (Service service : enabledServices) { for (Service service : enabledServices) {
@ -5929,13 +5984,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
String value = serviceCapabilities.get(cap); String value = serviceCapabilities.get(cap);
if (value == null || value.isEmpty()) { if (value == null || value.isEmpty()) {
throw new UnsupportedServiceException("Service " + service.getName() + " doesn't have capability " + cap.getName() + " for element=" + element.getName() + " implementing Provider=" + provider.getName()); throw new UnsupportedServiceException("Service " + service.getName() + " doesn't have capability " + cap.getName() + " for element=" + element.getName() + " implementing Provider="
+ provider.getName());
} }
capValue = capValue.toLowerCase(); capValue = capValue.toLowerCase();
if (!value.contains(capValue)) { if (!value.contains(capValue)) {
throw new UnsupportedServiceException("Service " + service.getName() + " doesn't support value " + capValue + " for capability " + cap.getName() + " for element=" + element.getName() + " implementing Provider=" + provider.getName()); throw new UnsupportedServiceException("Service " + service.getName() + " doesn't support value " + capValue + " for capability " + cap.getName() + " for element=" + element.getName()
+ " implementing Provider=" + provider.getName());
} }
} else { } else {
throw new UnsupportedServiceException("Unable to find network element for provider " + provider.getName()); throw new UnsupportedServiceException("Unable to find network element for provider " + provider.getName());

View File

@ -56,4 +56,5 @@ public interface FirewallRulesDao extends GenericDao<FirewallRuleVO, Long> {
List<FirewallRuleVO> listByIpAndNotRevoked(long ipAddressId); List<FirewallRuleVO> listByIpAndNotRevoked(long ipAddressId);
long countRulesByIpId(long sourceIpId); long countRulesByIpId(long sourceIpId);
} }

View File

@ -39,7 +39,8 @@ import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
@Local(value=FirewallRulesDao.class) @DB(txn=false) @Local(value = FirewallRulesDao.class)
@DB(txn = false)
public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> implements FirewallRulesDao { public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> implements FirewallRulesDao {
protected final SearchBuilder<FirewallRuleVO> AllFieldsSearch; protected final SearchBuilder<FirewallRuleVO> AllFieldsSearch;
@ -196,7 +197,8 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
return listBy(sc); return listBy(sc);
} }
@Override @DB @Override
@DB
public FirewallRuleVO persist(FirewallRuleVO firewallRule) { public FirewallRuleVO persist(FirewallRuleVO firewallRule) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
@ -208,7 +210,6 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
return dbfirewallRule; return dbfirewallRule;
} }
public void saveSourceCidrs(FirewallRuleVO firewallRule, List<String> cidrList) { public void saveSourceCidrs(FirewallRuleVO firewallRule, List<String> cidrList) {
if (cidrList == null) { if (cidrList == null) {
return; return;
@ -216,7 +217,6 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
_firewallRulesCidrsDao.persist(firewallRule.getId(), cidrList); _firewallRulesCidrsDao.persist(firewallRule.getId(), cidrList);
} }
@Override @Override
public List<FirewallRuleVO> listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose) { public List<FirewallRuleVO> listByIpPurposeAndProtocolAndNotRevoked(long ipAddressId, Integer startPort, Integer endPort, String protocol, FirewallRule.Purpose purpose) {
SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create(); SearchCriteria<FirewallRuleVO> sc = NotRevokedSearch.create();
@ -270,4 +270,5 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
sc.setParameters("ipAddressId", sourceIpId); sc.setParameters("ipAddressId", sourceIpId);
return customSearch(sc, null).get(0); return customSearch(sc, null).get(0);
} }
} }

View File

@ -25,9 +25,15 @@ import com.cloud.utils.db.GenericDao;
public interface LoadBalancerDao extends GenericDao<LoadBalancerVO, Long> { public interface LoadBalancerDao extends GenericDao<LoadBalancerVO, Long> {
List<Long> listInstancesByLoadBalancer(long loadBalancerId); List<Long> listInstancesByLoadBalancer(long loadBalancerId);
List<LoadBalancerVO> listByIpAddress(long ipAddressId); List<LoadBalancerVO> listByIpAddress(long ipAddressId);
LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort); LoadBalancerVO findByIpAddressAndPublicPort(long ipAddressId, String publicPort);
LoadBalancerVO findByAccountAndName(Long accountId, String name); LoadBalancerVO findByAccountAndName(Long accountId, String name);
List<LoadBalancerVO> listByNetworkId(long networkId); List<LoadBalancerVO> listByNetworkId(long networkId);
List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId); List<LoadBalancerVO> listInTransitionStateByNetworkId(long networkId);
} }

View File

@ -134,4 +134,5 @@ public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> im
sc.setParameters("state", State.Add.toString(), State.Revoke.toString()); sc.setParameters("state", State.Add.toString(), State.Revoke.toString());
return listBy(sc); return listBy(sc);
} }
} }

View File

@ -91,4 +91,5 @@ public interface NetworkDao extends GenericDao<NetworkVO, Long> {
boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap); boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap);
List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType); List<NetworkVO> listByZoneAndTrafficType(long zoneId, TrafficType trafficType);
} }

View File

@ -49,7 +49,8 @@ import com.cloud.utils.db.SequenceFetcher;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
@Local(value=NetworkDao.class) @DB(txn=false) @Local(value = NetworkDao.class)
@DB(txn = false)
public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements NetworkDao { public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements NetworkDao {
final SearchBuilder<NetworkVO> AllFieldsSearch; final SearchBuilder<NetworkVO> AllFieldsSearch;
final SearchBuilder<NetworkVO> AccountSearch; final SearchBuilder<NetworkVO> AccountSearch;
@ -109,7 +110,6 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
AccountNetworkSearch.join("networkSearch", mapJoin, AccountNetworkSearch.entity().getId(), mapJoin.entity().getNetworkId(), JoinBuilder.JoinType.INNER); AccountNetworkSearch.join("networkSearch", mapJoin, AccountNetworkSearch.entity().getId(), mapJoin.entity().getNetworkId(), JoinBuilder.JoinType.INNER);
AccountNetworkSearch.done(); AccountNetworkSearch.done();
ZoneBroadcastUriSearch = createSearchBuilder(); ZoneBroadcastUriSearch = createSearchBuilder();
ZoneBroadcastUriSearch.and("dataCenterId", ZoneBroadcastUriSearch.entity().getDataCenterId(), Op.EQ); ZoneBroadcastUriSearch.and("dataCenterId", ZoneBroadcastUriSearch.entity().getDataCenterId(), Op.EQ);
ZoneBroadcastUriSearch.and("broadcastUri", ZoneBroadcastUriSearch.entity().getBroadcastUri(), Op.EQ); ZoneBroadcastUriSearch.and("broadcastUri", ZoneBroadcastUriSearch.entity().getBroadcastUri(), Op.EQ);
@ -128,7 +128,6 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
CountByOfferingId.and("removed", CountByOfferingId.entity().getRemoved(), Op.NULL); CountByOfferingId.and("removed", CountByOfferingId.entity().getRemoved(), Op.NULL);
CountByOfferingId.done(); CountByOfferingId.done();
PhysicalNetworkSearch = createSearchBuilder(); PhysicalNetworkSearch = createSearchBuilder();
PhysicalNetworkSearch.and("physicalNetworkId", PhysicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ); PhysicalNetworkSearch.and("physicalNetworkId", PhysicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ);
PhysicalNetworkSearch.done(); PhysicalNetworkSearch.done();
@ -184,7 +183,8 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
return listBy(sc); return listBy(sc);
} }
@Override @DB @Override
@DB
public NetworkVO persist(NetworkVO network, boolean gc, Map<String, String> serviceProviderMap) { public NetworkVO persist(NetworkVO network, boolean gc, Map<String, String> serviceProviderMap) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
@ -203,8 +203,8 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
return newNetwork; return newNetwork;
} }
@Override
@Override @DB @DB
public boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap) { public boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
@ -395,4 +395,5 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
return listBy(sc, null); return listBy(sc, null);
} }
} }

View File

@ -79,23 +79,32 @@ import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
@Local(value = NetworkElement.class) @Local(value = NetworkElement.class)
public class CloudZonesNetworkElement extends AdapterBase implements NetworkElement, UserDataServiceProvider { public class CloudZonesNetworkElement extends AdapterBase implements NetworkElement, UserDataServiceProvider {
private static final Logger s_logger = Logger.getLogger(CloudZonesNetworkElement.class); private static final Logger s_logger = Logger.getLogger(CloudZonesNetworkElement.class);
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities(); private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@Inject NetworkDao _networkConfigDao; @Inject
@Inject NetworkManager _networkMgr; NetworkDao _networkConfigDao;
@Inject VirtualNetworkApplianceManager _routerMgr; @Inject
@Inject UserVmManager _userVmMgr; NetworkManager _networkMgr;
@Inject UserVmDao _userVmDao; @Inject
@Inject DomainRouterDao _routerDao; VirtualNetworkApplianceManager _routerMgr;
@Inject ConfigurationManager _configMgr; @Inject
@Inject DataCenterDao _dcDao; UserVmManager _userVmMgr;
@Inject AgentManager _agentManager; @Inject
@Inject ServiceOfferingDao _serviceOfferingDao; UserVmDao _userVmDao;
@Inject
DomainRouterDao _routerDao;
@Inject
ConfigurationManager _configMgr;
@Inject
DataCenterDao _dcDao;
@Inject
AgentManager _agentManager;
@Inject
ServiceOfferingDao _serviceOfferingDao;
private boolean canHandle(DeployDestination dest, TrafficType trafficType) { private boolean canHandle(DeployDestination dest, TrafficType trafficType) {
DataCenterVO dc = (DataCenterVO) dest.getDataCenter(); DataCenterVO dc = (DataCenterVO) dest.getDataCenter();
@ -112,7 +121,8 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
} }
@Override @Override
public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientCapacityException {
if (!canHandle(dest, offering.getTrafficType())) { if (!canHandle(dest, offering.getTrafficType())) {
return false; return false;
} }
@ -121,7 +131,8 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
} }
@Override @Override
public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientCapacityException, ResourceUnavailableException {
return true; return true;
} }
@ -219,7 +230,8 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
cmds.addCommand( cmds.addCommand(
"vmdata", "vmdata",
generateVmDataCommand(nic.getIp4Address(), userData, serviceOffering, zoneName, nic.getIp4Address(), uservm.getVirtualMachine().getHostName(), uservm.getVirtualMachine().getInstanceName(), uservm.getId(), sshPublicKey)); generateVmDataCommand(nic.getIp4Address(), userData, serviceOffering, zoneName, nic.getIp4Address(), uservm.getVirtualMachine().getHostName(), uservm.getVirtualMachine().getInstanceName(),
uservm.getId(), sshPublicKey));
try { try {
_agentManager.send(dest.getHost().getId(), cmds); _agentManager.send(dest.getHost().getId(), cmds);
} catch (OperationTimedoutException e) { } catch (OperationTimedoutException e) {
@ -247,4 +259,5 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
public boolean verifyServicesCombination(List<String> services) { public boolean verifyServicesCombination(List<String> services) {
return true; return true;
} }
} }

View File

@ -55,7 +55,8 @@ import com.cloud.vm.VirtualMachineProfile;
@Local(value = NetworkElement.class) @Local(value = NetworkElement.class)
public class ExternalDhcpElement extends AdapterBase implements NetworkElement, DhcpServiceProvider { public class ExternalDhcpElement extends AdapterBase implements NetworkElement, DhcpServiceProvider {
private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class); private static final Logger s_logger = Logger.getLogger(ExternalDhcpElement.class);
@Inject ExternalDhcpManager _dhcpMgr; @Inject
ExternalDhcpManager _dhcpMgr;
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities(); private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) { private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) {
@ -114,7 +115,6 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement,
return true; return true;
} }
@Override @Override
public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException {
return true; return true;

View File

@ -41,7 +41,6 @@ import com.cloud.api.response.F5LoadBalancerResponse;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO; import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeployDestination;
@ -57,15 +56,15 @@ import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.ExternalLoadBalancerDeviceManager; import com.cloud.network.ExternalLoadBalancerDeviceManager;
import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl;
import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.ExternalLoadBalancerDeviceVO;
import com.cloud.network.NetworkExternalLoadBalancerVO;
import com.cloud.network.NetworkVO;
import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.network.Network.Capability; import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service; import com.cloud.network.Network.Service;
import com.cloud.network.NetworkExternalLoadBalancerVO;
import com.cloud.network.NetworkManager; import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PhysicalNetworkVO;
@ -96,17 +95,28 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class); private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class);
@Inject NetworkManager _networkManager; @Inject
@Inject ConfigurationManager _configMgr; NetworkManager _networkManager;
@Inject NetworkServiceMapDao _ntwkSrvcDao; @Inject
@Inject DataCenterDao _dcDao; ConfigurationManager _configMgr;
@Inject PhysicalNetworkDao _physicalNetworkDao; @Inject
@Inject HostDao _hostDao; NetworkServiceMapDao _ntwkSrvcDao;
@Inject ExternalLoadBalancerDeviceDao _lbDeviceDao; @Inject
@Inject NetworkExternalLoadBalancerDao _networkLBDao; DataCenterDao _dcDao;
@Inject NetworkDao _networkDao; @Inject
@Inject HostDetailsDao _detailsDao; PhysicalNetworkDao _physicalNetworkDao;
@Inject ConfigurationDao _configDao; @Inject
HostDao _hostDao;
@Inject
ExternalLoadBalancerDeviceDao _lbDeviceDao;
@Inject
NetworkExternalLoadBalancerDao _networkLBDao;
@Inject
NetworkDao _networkDao;
@Inject
HostDetailsDao _detailsDao;
@Inject
ConfigurationDao _configDao;
private boolean canHandle(Network config) { private boolean canHandle(Network config) {
if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) { if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) {
@ -114,12 +124,12 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
return false; return false;
} }
return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), Service.Lb, Network.Provider.F5BigIp));
_ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), Service.Lb, Network.Provider.F5BigIp));
} }
@Override @Override
public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientNetworkCapacityException { public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientNetworkCapacityException {
if (!canHandle(guestConfig)) { if (!canHandle(guestConfig)) {
return false; return false;
@ -128,13 +138,15 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
try { try {
return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig); return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig);
} catch (InsufficientCapacityException capacityException) { } catch (InsufficientCapacityException capacityException) {
// TODO: handle out of capacity exception in graceful manner when multiple providers are avaialble for the network // TODO: handle out of capacity exception in graceful manner when multiple providers are avaialble for the
// network
return false; return false;
} }
} }
@Override @Override
public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientNetworkCapacityException, ResourceUnavailableException {
return true; return true;
} }

View File

@ -26,6 +26,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.ejb.Local; import javax.ejb.Local;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.api.commands.AddExternalFirewallCmd; import com.cloud.api.commands.AddExternalFirewallCmd;
@ -41,8 +42,8 @@ import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ConcurrentOperationException;
@ -54,14 +55,14 @@ import com.cloud.host.Host;
import com.cloud.host.HostVO; import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao; import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.Network; import com.cloud.network.ExternalFirewallDeviceManagerImpl;
import com.cloud.network.ExternalFirewallDeviceVO;
import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState; import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.Network;
import com.cloud.network.Network.Capability; import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service; import com.cloud.network.Network.Service;
import com.cloud.network.ExternalFirewallDeviceManagerImpl;
import com.cloud.network.ExternalFirewallDeviceVO;
import com.cloud.network.NetworkExternalFirewallVO; import com.cloud.network.NetworkExternalFirewallVO;
import com.cloud.network.NetworkManager; import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO; import com.cloud.network.NetworkVO;
@ -98,19 +99,32 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities(); private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@Inject NetworkManager _networkManager; @Inject
@Inject HostDao _hostDao; NetworkManager _networkManager;
@Inject ConfigurationManager _configMgr; @Inject
@Inject NetworkOfferingDao _networkOfferingDao; HostDao _hostDao;
@Inject NetworkDao _networksDao; @Inject
@Inject DataCenterDao _dcDao; ConfigurationManager _configMgr;
@Inject PhysicalNetworkDao _physicalNetworkDao; @Inject
@Inject ExternalFirewallDeviceDao _fwDevicesDao; NetworkOfferingDao _networkOfferingDao;
@Inject NetworkExternalFirewallDao _networkFirewallDao; @Inject
@Inject NetworkDao _networkDao; NetworkDao _networksDao;
@Inject NetworkServiceMapDao _ntwkSrvcDao; @Inject
@Inject HostDetailsDao _hostDetailDao; DataCenterDao _dcDao;
@Inject ConfigurationDao _configDao; @Inject
PhysicalNetworkDao _physicalNetworkDao;
@Inject
ExternalFirewallDeviceDao _fwDevicesDao;
@Inject
NetworkExternalFirewallDao _networkFirewallDao;
@Inject
NetworkDao _networkDao;
@Inject
NetworkServiceMapDao _ntwkSrvcDao;
@Inject
HostDetailsDao _hostDetailDao;
@Inject
ConfigurationDao _configDao;
private boolean canHandle(Network network, Service service) { private boolean canHandle(Network network, Service service) {
DataCenter zone = _configMgr.getZone(network.getDataCenterId()); DataCenter zone = _configMgr.getZone(network.getDataCenterId());
@ -135,7 +149,8 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
} }
@Override @Override
public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientNetworkCapacityException { public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientNetworkCapacityException {
DataCenter zone = _configMgr.getZone(network.getDataCenterId()); DataCenter zone = _configMgr.getZone(network.getDataCenterId());
// don't have to implement network is Basic zone // don't have to implement network is Basic zone
@ -151,13 +166,15 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
try { try {
return manageGuestNetworkWithExternalFirewall(true, network); return manageGuestNetworkWithExternalFirewall(true, network);
} catch (InsufficientCapacityException capacityException) { } catch (InsufficientCapacityException capacityException) {
// TODO: handle out of capacity exception in more gracefule manner when multiple providers are present for the network // TODO: handle out of capacity exception in more gracefule manner when multiple providers are present for
// the network
return false; return false;
} }
} }
@Override @Override
public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientNetworkCapacityException, ResourceUnavailableException {
return true; return true;
} }
@ -317,7 +334,8 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
} }
@Override @Override
@Deprecated // should use more generic addNetworkDevice command to add firewall @Deprecated
// should use more generic addNetworkDevice command to add firewall
public Host addExternalFirewall(AddExternalFirewallCmd cmd) { public Host addExternalFirewall(AddExternalFirewallCmd cmd) {
Long zoneId = cmd.getZoneId(); Long zoneId = cmd.getZoneId();
DataCenterVO zone = null; DataCenterVO zone = null;
@ -351,7 +369,8 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan
} }
@Override @Override
@Deprecated // should use more generic listNetworkDevice command @Deprecated
// should use more generic listNetworkDevice command
public List<Host> listExternalFirewalls(ListExternalFirewallsCmd cmd) { public List<Host> listExternalFirewalls(ListExternalFirewallsCmd cmd) {
List<Host> firewallHosts = new ArrayList<Host>(); List<Host> firewallHosts = new ArrayList<Host>();
Long zoneId = cmd.getZoneId(); Long zoneId = cmd.getZoneId();

View File

@ -31,15 +31,12 @@ import javax.ejb.Local;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager;
import com.cloud.agent.AgentManager.OnError;
import com.cloud.agent.api.Answer; import com.cloud.agent.api.Answer;
import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesAnswer;
import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand;
import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.LoadBalancerTO;
import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO;
import com.cloud.agent.manager.Commands;
import com.cloud.api.ApiConstants; import com.cloud.api.ApiConstants;
import com.cloud.api.commands.AddNetscalerLoadBalancerCmd; import com.cloud.api.commands.AddNetscalerLoadBalancerCmd;
import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd; import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd;
@ -51,7 +48,6 @@ import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeployDestination;
@ -67,9 +63,9 @@ import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.ExternalLoadBalancerDeviceManager; import com.cloud.network.ExternalLoadBalancerDeviceManager;
import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl;
import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.ExternalLoadBalancerDeviceVO;
import com.cloud.network.IpAddress;
import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.IpAddress;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.network.Network.Capability; import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider; import com.cloud.network.Network.Provider;
@ -90,8 +86,8 @@ import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.lb.LoadBalancingRule.LbDestination;
import com.cloud.network.resource.NetscalerResource; import com.cloud.network.resource.NetscalerResource;
import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.StaticNat;
import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering;
@ -109,23 +105,37 @@ import com.cloud.vm.VirtualMachineProfile;
import com.google.gson.Gson; import com.google.gson.Gson;
@Local(value = NetworkElement.class) @Local(value = NetworkElement.class)
public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, NetscalerLoadBalancerElementService, ExternalLoadBalancerDeviceManager, IpDeployer, StaticNatServiceProvider { public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, NetscalerLoadBalancerElementService, ExternalLoadBalancerDeviceManager, IpDeployer,
StaticNatServiceProvider {
private static final Logger s_logger = Logger.getLogger(NetscalerElement.class); private static final Logger s_logger = Logger.getLogger(NetscalerElement.class);
@Inject NetworkManager _networkManager; @Inject
@Inject ConfigurationManager _configMgr; NetworkManager _networkManager;
@Inject NetworkServiceMapDao _ntwkSrvcDao; @Inject
@Inject AgentManager _agentMgr; ConfigurationManager _configMgr;
@Inject NetworkManager _networkMgr; @Inject
@Inject HostDao _hostDao; NetworkServiceMapDao _ntwkSrvcDao;
@Inject DataCenterDao _dcDao; @Inject
@Inject ExternalLoadBalancerDeviceDao _lbDeviceDao; AgentManager _agentMgr;
@Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject
@Inject PhysicalNetworkDao _physicalNetworkDao; NetworkManager _networkMgr;
@Inject NetworkDao _networkDao; @Inject
@Inject HostDetailsDao _detailsDao; HostDao _hostDao;
@Inject ConfigurationDao _configDao; @Inject
DataCenterDao _dcDao;
@Inject
ExternalLoadBalancerDeviceDao _lbDeviceDao;
@Inject
NetworkExternalLoadBalancerDao _networkLBDao;
@Inject
PhysicalNetworkDao _physicalNetworkDao;
@Inject
NetworkDao _networkDao;
@Inject
HostDetailsDao _detailsDao;
@Inject
ConfigurationDao _configDao;
private boolean canHandle(Network config, Service service) { private boolean canHandle(Network config, Service service) {
DataCenter zone = _dcDao.findById(config.getDataCenterId()); DataCenter zone = _dcDao.findById(config.getDataCenterId());
@ -137,8 +147,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
return false; return false;
} }
return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), service, Network.Provider.Netscaler));
_ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), service, Network.Provider.Netscaler));
} }
private boolean isBasicZoneNetwok(Network config) { private boolean isBasicZoneNetwok(Network config) {
@ -147,7 +156,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
} }
@Override @Override
public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientNetworkCapacityException { public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientNetworkCapacityException {
if (!canHandle(guestConfig, Service.Lb)) { if (!canHandle(guestConfig, Service.Lb)) {
return false; return false;
@ -162,7 +172,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
} }
@Override @Override
public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientNetworkCapacityException, ResourceUnavailableException {
return true; return true;
} }
@ -256,7 +267,6 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
staticNatCapabilities.put(Capability.ElasticIp, "true"); staticNatCapabilities.put(Capability.ElasticIp, "true");
capabilities.put(Service.StaticNat, staticNatCapabilities); capabilities.put(Service.StaticNat, staticNatCapabilities);
// TODO - Murali, please put correct capabilities here // TODO - Murali, please put correct capabilities here
Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>(); Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>();
firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); firewallCapabilities.put(Capability.TrafficStatistics, "per public ip");
@ -489,7 +499,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
public boolean isReady(PhysicalNetworkServiceProvider provider) { public boolean isReady(PhysicalNetworkServiceProvider provider) {
List<ExternalLoadBalancerDeviceVO> lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.Netscaler.getName()); List<ExternalLoadBalancerDeviceVO> lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.Netscaler.getName());
// true if at-least one Netscaler device is added in to physical network and is in configured (in enabled state) state // true if at-least one Netscaler device is added in to physical network and is in configured (in enabled state)
// state
if (lbDevices != null && !lbDevices.isEmpty()) { if (lbDevices != null && !lbDevices.isEmpty()) {
for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) {
if (lbDevice.getState() == LBDeviceState.Enabled) { if (lbDevice.getState() == LBDeviceState.Enabled) {
@ -652,4 +663,5 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
return false; return false;
} }
} }
} }

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