Commit to try something on removing getZone

This commit is contained in:
Alex Huang 2013-08-26 14:02:34 -07:00
parent 2e5bb63f77
commit 435e74e914
122 changed files with 1615 additions and 2253 deletions

View File

@ -97,8 +97,6 @@ public interface NetworkModel {
List<? extends Network> listAllNetworksInAllZonesByType(Network.GuestType type);
String getGlobalGuestDomainSuffix();
String getStartIpAddress(long networkId);
String getIpInNetwork(long vmId, long networkId);
@ -179,11 +177,6 @@ public interface NetworkModel {
*/
String getAccountNetworkDomain(long accountId, long zoneId);
/**
* @return
*/
String getDefaultNetworkDomain(long zoneId);
/**
* @param ntwkOffId
* @return

View File

@ -69,10 +69,6 @@ public interface RulesService {
boolean enableStaticNat(long ipAddressId, long vmId, long networkId, String vmGuestIp) throws NetworkRuleConflictException, ResourceUnavailableException;
PortForwardingRule getPortForwardigRule(long ruleId);
FirewallRule getFirewallRule(long ruleId);
StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException;
boolean revokeStaticNatRule(long ruleId, boolean apply);
@ -81,8 +77,6 @@ public interface RulesService {
StaticNatRule buildStaticNatRule(FirewallRule rule, boolean forRevoke);
List<String> getSourceCidrs(long ruleId);
boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException;
}

View File

@ -29,27 +29,10 @@ import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.IpAddress;
import com.cloud.network.Network;
import com.cloud.utils.Pair;
public interface VpcService {
/**Returns existing VPC found by id
*
* @param vpcId
* @return
*/
public Vpc getVpc(long vpcId);
/**
* Returns all the Guest networks that are part of VPC
*
* @param vpcId
* @return
*/
public List<? extends Network> getVpcNetworks(long vpcId);
/**
* Persists VPC record in the database
*
@ -63,8 +46,7 @@ public interface VpcService {
* @return
* @throws ResourceAllocationException TODO
*/
public Vpc createVpc(long zoneId, long vpcOffId, long vpcOwnerId, String vpcName, String displayText, String cidr,
String networkDomain) throws ResourceAllocationException;
public Vpc createVpc(long zoneId, long vpcOffId, long vpcOwnerId, String vpcName, String displayText, String cidr, String networkDomain) throws ResourceAllocationException;
/**
@ -113,10 +95,9 @@ public interface VpcService {
* @param vpc
* @return
*/
public List<? extends Vpc> listVpcs(Long id, String vpcName, String displayText,
List<String> supportedServicesStr, String cidr, Long vpcOffId, String state, String accountName, Long domainId,
String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll,
Boolean restartRequired, Map<String, String> tags, Long projectId);
public List<? extends Vpc> listVpcs(Long id, String vpcName, String displayText, List<String> supportedServicesStr, String cidr, Long vpcOffId, String state,
String accountName, Long domainId, String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, Boolean restartRequired,
Map<String, String> tags, Long projectId);
/**
* Starts VPC which includes starting VPC provider and applying all the neworking rules on the backend
@ -128,8 +109,7 @@ public interface VpcService {
* @throws ResourceUnavailableException
* @throws ConcurrentOperationException
*/
boolean startVpc(long vpcId, boolean destroyOnFailure) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException;
boolean startVpc(long vpcId, boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
/**
* Shuts down the VPC which includes shutting down all VPC provider and rules cleanup on the backend
@ -159,7 +139,6 @@ public interface VpcService {
*/
PrivateGateway getVpcPrivateGateway(long id);
/**
* Persists VPC private gateway in the Database.
*
@ -178,9 +157,8 @@ public interface VpcService {
* @throws ConcurrentOperationException
* @throws ResourceAllocationException
*/
public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress,
String gateway, String netmask, long gatewayOwnerId, Boolean isSoruceNat, Long aclId) throws ResourceAllocationException,
ConcurrentOperationException, InsufficientCapacityException;
public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress, String gateway, String netmask, long gatewayOwnerId,
Boolean isSoruceNat, Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException;
/**
* Applies VPC private gateway on the backend, so it becomes functional
@ -262,15 +240,6 @@ public interface VpcService {
public Pair<List<? extends StaticRoute>, Integer> listStaticRoutes(ListStaticRoutesCmd cmd);
/**
* Returns gateway (VPN or Public) existign in the VPC
*
* @param id
* @return
*/
VpcGateway getVpcGateway(long id);
/**
* Associates IP address from the Public network, to the VPC
*
@ -282,7 +251,7 @@ public interface VpcService {
* @throws InsufficientAddressCapacityException
* @throws ConcurrentOperationException
*/
IpAddress associateIPToVpc(long ipId, long vpcId) throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException;
IpAddress associateIPToVpc(long ipId, long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException,
ConcurrentOperationException;
}

View File

@ -29,6 +29,7 @@ import com.cloud.user.Account;
import com.cloud.utils.Pair;
public interface RemoteAccessVpnService {
static final String RemoteAccessVpnClientIpRangeCK = "remote.access.vpn.client.iprange";
RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, String ipRange, boolean openFirewall, long networkId)
throws NetworkRuleConflictException;

View File

@ -16,6 +16,8 @@
// under the License.
package org.apache.cloudstack.api.command.admin.vpc;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
@ -28,7 +30,6 @@ import org.apache.cloudstack.api.response.NetworkACLResponse;
import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
import org.apache.cloudstack.api.response.PrivateGatewayResponse;
import org.apache.cloudstack.api.response.VpcResponse;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
@ -145,8 +146,8 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
}
if (result != null) {
this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
setEntityId(result.getId());
setEntityUuid(result.getUuid());
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private gateway");
}
@ -159,7 +160,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
if (result != null) {
PrivateGatewayResponse response = _responseGenerator.createPrivateGatewayResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private gateway");
}
@ -189,7 +190,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd {
@Override
public Long getSyncObjId() {
Vpc vpc = _vpcService.getVpc(vpcId);
Vpc vpc = _entityMgr.findById(Vpc.class, vpcId);
if (vpc == null) {
throw new InvalidParameterValueException("Invalid id is specified for the vpc");
}

View File

@ -228,7 +228,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd {
return network.getAccountId();
} else if (vpcId != null) {
Vpc vpc = _vpcService.getVpc(getVpcId());
Vpc vpc = _entityMgr.findById(Vpc.class, getVpcId());
if (vpc == null) {
throw new InvalidParameterValueException("Can't find Enabled vpc by id specified");
}

View File

@ -16,6 +16,8 @@
// under the License.
package org.apache.cloudstack.api.command.user.firewall;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
@ -28,8 +30,6 @@ import org.apache.cloudstack.api.response.FirewallRuleResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.rules.PortForwardingRule;
@ -100,7 +100,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd {
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete port forwarding rule");
}
@ -114,7 +114,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd {
@Override
public Long getSyncObjId() {
return _rulesService.getPortForwardigRule(id).getNetworkId();
return _entityMgr.findById(PortForwardingRule.class, id).getNetworkId();
}
@Override

View File

@ -16,6 +16,8 @@
// under the License.
package org.apache.cloudstack.api.command.user.nat;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
@ -28,8 +30,6 @@ import org.apache.cloudstack.api.response.FirewallRuleResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.rules.FirewallRule;
@ -77,7 +77,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd {
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete ip forwarding rule");
}
@ -113,7 +113,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd {
@Override
public Long getSyncObjId() {
return _rulesService.getFirewallRule(id).getNetworkId();
return _entityMgr.findById(FirewallRule.class, id).getNetworkId();
}
@Override

View File

@ -16,12 +16,7 @@
// under the License.
package org.apache.cloudstack.api.command.user.network;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.vpc.NetworkACL;
import com.cloud.network.vpc.Vpc;
import com.cloud.user.Account;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
@ -31,9 +26,13 @@ import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.NetworkACLResponse;
import org.apache.cloudstack.api.response.VpcResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.vpc.NetworkACL;
import com.cloud.network.vpc.Vpc;
import com.cloud.user.Account;
@APICommand(name = "createNetworkACLList", description = "Creates a Network ACL for the given VPC",
responseObject = NetworkACLResponse.class)
@ -101,7 +100,7 @@ public class CreateNetworkACLListCmd extends BaseAsyncCreateCmd {
@Override
public long getEntityOwnerId() {
Vpc vpc = _vpcService.getVpc(getVpcId());
Vpc vpc = _entityMgr.findById(Vpc.class, getVpcId());
if (vpc == null) {
throw new InvalidParameterValueException("Invalid vpcId is given");
}

View File

@ -16,6 +16,8 @@
// under the License.
package org.apache.cloudstack.api.command.user.vpc;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
@ -28,14 +30,13 @@ import org.apache.cloudstack.api.response.PrivateGatewayResponse;
import org.apache.cloudstack.api.response.StaticRouteResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.vpc.StaticRoute;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcGateway;
@APICommand(name = "createStaticRoute", description="Creates a static route", responseObject=StaticRouteResponse.class)
@ -119,11 +120,11 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{
@Override
public long getEntityOwnerId() {
VpcGateway gateway = _vpcService.getVpcGateway(gatewayId);
VpcGateway gateway = _entityMgr.findById(VpcGateway.class, gatewayId);
if (gateway == null) {
throw new InvalidParameterValueException("Invalid gateway id is specified");
}
return _vpcService.getVpc(gateway.getVpcId()).getAccountId();
return _entityMgr.findById(Vpc.class, gateway.getVpcId()).getAccountId();
}
@Override
@ -133,7 +134,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{
@Override
public Long getSyncObjId() {
VpcGateway gateway = _vpcService.getVpcGateway(gatewayId);
VpcGateway gateway = _entityMgr.findById(VpcGateway.class, gatewayId);
if (gateway == null) {
throw new InvalidParameterValueException("Invalid id is specified for the gateway");
}

View File

@ -16,6 +16,8 @@
// under the License.
package org.apache.cloudstack.api.command.user.vpc;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
@ -29,8 +31,6 @@ import org.apache.cloudstack.api.response.VpcResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
@ -124,8 +124,8 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{
Vpc vpc = _vpcService.createVpc(getZoneId(), getVpcOffering(), getEntityOwnerId(), getVpcName(), getDisplayText(),
getCidr(), getNetworkDomain());
if (vpc != null) {
this.setEntityId(vpc.getId());
this.setEntityUuid(vpc.getUuid());
setEntityId(vpc.getId());
setEntityUuid(vpc.getUuid());
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a VPC");
}
@ -135,8 +135,8 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{
public void execute() {
Vpc vpc = null;
try {
if (_vpcService.startVpc(this.getEntityId(), true)) {
vpc = _vpcService.getVpc(getEntityId());
if (_vpcService.startVpc(getEntityId(), true)) {
vpc = _entityMgr.findById(Vpc.class, getEntityId());
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Exception: ", ex);
@ -153,7 +153,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{
if (vpc != null) {
VpcResponse response = _responseGenerator.createVpcResponse(vpc);
response.setResponseName(getCommandName());
this.setResponseObject(response);
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create VPC");
}

View File

@ -16,6 +16,8 @@
// under the License.
package org.apache.cloudstack.api.command.user.vpn;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
@ -26,7 +28,6 @@ import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse;
import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse;
import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.NetworkRuleConflictException;
@ -77,7 +78,7 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd {
@Override
public long getEntityOwnerId() {
Vpc vpc = _vpcService.getVpc(getVpnGateway().getVpcId());
Vpc vpc = _entityMgr.findById(Vpc.class, getVpnGateway().getVpcId());
return vpc.getAccountId();
}
@ -96,8 +97,8 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd {
try {
Site2SiteVpnConnection conn = _s2sVpnService.createVpnConnection(this);
if (conn != null) {
this.setEntityId(conn.getId());
this.setEntityUuid(conn.getUuid());
setEntityId(conn.getId());
setEntityUuid(conn.getUuid());
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create site to site vpn connection");
}
@ -111,11 +112,11 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd {
@Override
public void execute(){
try {
Site2SiteVpnConnection result = _s2sVpnService.startVpnConnection(this.getEntityId());
Site2SiteVpnConnection result = _s2sVpnService.startVpnConnection(getEntityId());
if (result != null) {
Site2SiteVpnConnectionResponse response = _responseGenerator.createSite2SiteVpnConnectionResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create site to site vpn connection");
}

View File

@ -16,6 +16,8 @@
// under the License.
package org.apache.cloudstack.api.command.user.vpn;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
@ -24,7 +26,6 @@ import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse;
import org.apache.cloudstack.api.response.VpcResponse;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.network.Site2SiteVpnGateway;
@ -63,7 +64,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd {
@Override
public long getEntityOwnerId() {
Vpc vpc = _vpcService.getVpc(vpcId);
Vpc vpc = _entityMgr.findById(Vpc.class, vpcId);
return vpc.getAccountId();
}
@ -84,7 +85,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd {
if (result != null) {
Site2SiteVpnGatewayResponse response = _responseGenerator.createSite2SiteVpnGatewayResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create VPN gateway");
}

View File

@ -60,5 +60,10 @@
<artifactId>cloud-framework-ipc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-framework-config</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -21,6 +21,7 @@ import java.util.List;
import java.util.Map;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.framework.config.ConfigKey;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
@ -32,10 +33,10 @@ import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;
import com.cloud.network.NetworkProfile;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkProfile;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.element.DhcpServiceProvider;
import com.cloud.network.element.LoadBalancingServiceProvider;
import com.cloud.network.element.StaticNatServiceProvider;
@ -58,6 +59,16 @@ import com.cloud.vm.VirtualMachineProfile;
*
*/
public interface NetworkOrchestrationService {
static final String NetworkLockTimeoutCK = "network.lock.timeout";
static final String GuestDomainSuffixCK = "guest.domain.suffix";
static final String NetworkThrottlingRateCK = "network.throttling.rate";
static final ConfigKey<Integer> NetworkLockTimeout = new ConfigKey<Integer>(Integer.class, NetworkLockTimeoutCK, "Network", "600",
"Lock wait timeout (seconds) while implementing network", true);
static final ConfigKey<String> GuestDomainSuffix = new ConfigKey<String>(String.class, GuestDomainSuffixCK, "Network", "cloud.internal",
"Default domain name for vms inside virtualized networks fronted by router", true, ConfigKey.Scope.Zone, null);
static final ConfigKey<Integer> NetworkThrottlingRate = new ConfigKey<Integer>("Network", Integer.class, NetworkThrottlingRateCK, "200",
"Default data transfer rate in megabits per second allowed in network.", true, ConfigKey.Scope.Zone);
List<? extends Network> setupNetwork(Account owner, NetworkOffering offering, DeploymentPlan plan, String name, String displayText, boolean isDefault)
throws ConcurrentOperationException;
@ -158,10 +169,6 @@ public interface NetworkOrchestrationService {
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException,
ResourceUnavailableException;
/**
* @param vm
* @param nic TODO
*/
void removeNic(VirtualMachineProfile vm, Nic nic);
/**
@ -171,38 +178,14 @@ public interface NetworkOrchestrationService {
*/
boolean setupDns(Network network, Provider provider);
/**
* @param vmProfile
* @param nic TODO
* @throws ConcurrentOperationException
* @throws ResourceUnavailableException
*/
void releaseNic(VirtualMachineProfile vmProfile, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException;
/**
* @param network
* @param requested
* @param context
* @param vmProfile
* @param prepare TODO
* @return
* @throws InsufficientVirtualNetworkCapcityException
* @throws InsufficientAddressCapacityException
* @throws ConcurrentOperationException
* @throws InsufficientCapacityException
* @throws ResourceUnavailableException
*/
NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfile vmProfile, boolean prepare)
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException,
ResourceUnavailableException;
NetworkProfile convertNetworkToNetworkProfile(long networkId);
/**
* @return
*/
int getNetworkLockTimeout();
boolean restartNetwork(Long networkId, Account callerAccount, User callerUser, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException;

View File

@ -38,6 +38,11 @@
<artifactId>cloud-engine-schema</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-framework-ipc</artifactId>

View File

@ -18,26 +18,21 @@ package com.cloud.agent;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.manager.AgentAttache;
import com.cloud.agent.manager.Commands;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.resource.ServerResource;
import com.cloud.utils.component.Manager;
/**
* AgentManager manages hosts. It directly coordinates between the DAOs and the connections it manages.
*/
public interface AgentManager extends Manager {
public interface AgentManager {
final static String WaitCK = "wait";
public enum TapAgentsAction {
Add,
Del,
Contains,
Add, Del, Contains,
}
/**
@ -109,7 +104,6 @@ public interface AgentManager extends Manager {
*/
int registerForHostEvents(Listener listener, boolean connections, boolean commands, boolean priority);
/**
* Register to listen for initial agent connections.
* @param creator
@ -128,11 +122,10 @@ public interface AgentManager extends Manager {
Answer sendTo(Long dcId, HypervisorType type, Command cmd);
/* working as a lock while agent is being loaded */
public boolean tapLoadingAgents(Long hostId, TapAgentsAction action);
public AgentAttache handleDirectConnectAgent(HostVO host, StartupCommand[] cmds, ServerResource resource, boolean forRebalance) throws ConnectionException;
// public AgentAttache handleDirectConnectAgent(HostVO host, StartupCommand[] cmds, ServerResource resource, boolean forRebalance) throws ConnectionException;
public boolean agentStatusTransitTo(HostVO host, Status.Event e, long msId);

View File

@ -16,6 +16,8 @@
// under the License.
package com.cloud.alert;
import org.apache.cloudstack.framework.config.ConfigKey;
import com.cloud.capacity.CapacityVO;
import com.cloud.utils.component.Manager;
@ -49,6 +51,15 @@ public interface AlertManager extends Manager {
public static final short ALERT_TYPE_LOCAL_STORAGE = 25;
public static final short ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED = 26; // Generated when the resource limit exceeds the limit. Currently used for recurring snapshots only
static final ConfigKey<Double> StorageCapacityThreshold = new ConfigKey<Double>(Double.class, "cluster.storage.capacity.notificationthreshold", "Alert", "0.75",
"Percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available.", true, ConfigKey.Scope.Cluster, null);
static final ConfigKey<Double> CPUCapacityThreshold = new ConfigKey<Double>(Double.class, "cluster.cpu.allocated.capacity.notificationthreshold", "Alert", "0.75",
"Percentage (as a value between 0 and 1) of cpu utilization above which alerts will be sent about low cpu available.", true, ConfigKey.Scope.Cluster, null);
static final ConfigKey<Double> MemoryCapacityThreshold = new ConfigKey<Double>(Double.class, "cluster.memory.allocated.capacity.notificationthreshold", "Alert", "0.75",
"Percentage (as a value between 0 and 1) of memory utilization above which alerts will be sent about low memory available.", true, ConfigKey.Scope.Cluster, null);
static final ConfigKey<Double> StorageAllocatedCapacityThreshold = new ConfigKey<Double>(Double.class, "cluster.storage.allocated.capacity.notificationthreshold", "Alert",
"0.75", "Percentage (as a value between 0 and 1) of allocated storage utilization above which alerts will be sent about low storage available.", true,
ConfigKey.Scope.Cluster, null);
void clearAlert(short alertType, long dataCenterId, long podId);

View File

@ -16,11 +16,11 @@
// under the License.
package com.cloud.capacity;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import com.cloud.host.Host;
import com.cloud.storage.VMTemplateVO;
import com.cloud.utils.component.Manager;
import com.cloud.vm.VirtualMachine;
/**
@ -28,7 +28,17 @@ import com.cloud.vm.VirtualMachine;
* available within the Cloud Stack.
*
*/
public interface CapacityManager extends Manager {
public interface CapacityManager {
static final String CpuOverprovisioningFactorCK = "cpu.overprovisioning.factor";
static final String MemOverprovisioningFactorCK = "mem.overprovisioning.factor";
static final ConfigKey<Float> CpuOverprovisioningFactor = new ConfigKey<Float>(Float.class, CpuOverprovisioningFactorCK, "Advanced", "1.0",
"Used for CPU overprovisioning calculation; available CPU will be (actualCpuCapacity * cpu.overprovisioning.factor)", true, ConfigKey.Scope.Cluster, null);
static final ConfigKey<Float> MemOverprovisioningFactor = new ConfigKey<Float>(Float.class, MemOverprovisioningFactorCK, "Advanced", "1.0",
"Used for memory overprovisioning calculation", true, ConfigKey.Scope.Cluster, null);
public boolean releaseVmCapacity(VirtualMachine vm, boolean moveFromReserved, boolean moveToReservered, Long hostId);
void allocateVmCapacity(VirtualMachine vm, boolean fromLastHost);

View File

@ -18,6 +18,8 @@ package com.cloud.network;
import java.util.List;
import org.apache.cloudstack.framework.config.ConfigKey;
import com.cloud.dc.DataCenter;
import com.cloud.dc.Pod;
import com.cloud.dc.Vlan.VlanType;
@ -36,6 +38,11 @@ import com.cloud.vm.NicProfile;
import com.cloud.vm.VirtualMachineProfile;
public interface IpAddressManager {
static final String UseSystemPublicIpsCK = "use.system.public.ips";
static final ConfigKey<Boolean> UseSystemPublicIps = new ConfigKey<Boolean>("Advanced", Boolean.class, UseSystemPublicIpsCK, "true",
"If true, when account has dedicated public ip range(s), once the ips dedicated to the account have been consumed ips will be acquired from the system pool", true,
ConfigKey.Scope.Account);
/**
* Assigns a new public ip address.
*
@ -52,7 +59,6 @@ public interface IpAddressManager {
* @return
* @throws InsufficientAddressCapacityException
*/
PublicIp
assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isSystem) throws InsufficientAddressCapacityException;

View File

@ -30,7 +30,7 @@ import com.cloud.vm.VirtualMachine;
/**
* Rules Manager manages the network rules created for different networks.
*/
public interface RulesManager extends RulesService {
public interface RulesManager {
boolean applyPortForwardingRulesForNetwork(long networkId, boolean continueOnError, Account caller);

View File

@ -38,7 +38,14 @@ import com.cloud.offering.NetworkOffering;
import com.cloud.user.Account;
public interface VpcManager extends VpcService{
public interface VpcManager {
/**
* Returns all the Guest networks that are part of VPC
*
* @param vpcId
* @return
*/
public List<? extends Network> getVpcNetworks(long vpcId);
/**
* Returns all existing VPCs for a given account

View File

@ -20,6 +20,7 @@ import java.util.List;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import com.cloud.dc.DataCenterVO;
@ -36,6 +37,9 @@ import com.cloud.utils.Pair;
* TemplateManager manages the templates stored on secondary storage. It is responsible for creating private/public templates.
*/
public interface TemplateManager {
static final String AllowPublicUserTemplatesCK = "allow.public.user.templates";
static final ConfigKey<Boolean> AllowPublicUserTemplates = new ConfigKey<Boolean>("Advanced", Boolean.class, AllowPublicUserTemplatesCK, "true",
"If false, users will not be able to create public templates.", true, ConfigKey.Scope.Account);
/**
* Prepares a template for vm creation for a certain storage pool.

View File

@ -58,11 +58,13 @@
<artifactId>cloud-utils</artifactId>
<version>${project.version}</version>
</dependency>
<!--
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-server</artifactId>
<version>${project.version}</version>
</dependency>
-->
</dependencies>
<build>
<plugins>

View File

@ -72,7 +72,6 @@ import com.cloud.agent.api.UnsupportedAnswer;
import com.cloud.agent.transport.Request;
import com.cloud.agent.transport.Response;
import com.cloud.alert.AlertManager;
import com.cloud.configuration.Config;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
@ -91,12 +90,10 @@ import com.cloud.host.Status.Event;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.hypervisor.kvm.discoverer.KvmDummyResourceBase;
import com.cloud.resource.Discoverer;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceState;
import com.cloud.resource.ServerResource;
import com.cloud.storage.resource.DummySecondaryStorageResource;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
@ -185,14 +182,13 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
"Interval to send application level pings to make sure the connection is still working", false);
protected final ConfigKey<Float> PingTimeout = new ConfigKey<Float>(Float.class, "ping.timeout", "Advance", "2.5",
"Multiplier to ping.interval before announcing an agent has timed out", true);
protected final ConfigKey<Integer> Wait = new ConfigKey<Integer>(Integer.class, "wait", "Advance", "1800",
"Time in seconds to wait for control commands to return", true);
protected final ConfigKey<Integer> AlertWait = new ConfigKey<Integer>(Integer.class, "alert.wait", "Advance", "1800",
"Seconds to wait before alerting on a disconnected agent", true);
protected final ConfigKey<Integer> DirectAgentLoadSize = new ConfigKey<Integer>(Integer.class, "direct.agent.load.size", "Advance", "16",
"The number of direct agents to load each time", false);
protected final ConfigKey<Integer> DirectAgentPoolSize = new ConfigKey<Integer>(Integer.class, "direct.agent.pool.size", "Advance", "500",
"Default size for DirectAgentPool", false);
static final ConfigKey<Integer> Wait = new ConfigKey<Integer>("Advanced", Integer.class, WaitCK, "1800", "Time in seconds to wait for control commands to return", true);
protected ConfigValue<Integer> _port;
@ -642,8 +638,6 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
params.put("ipaddress", host.getPrivateIpAddress());
params.put("secondary.storage.vm", "false");
params.put("max.template.iso.size", _configDao.getValue(Config.MaxTemplateAndIsoSize.toString()));
params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
try {
resource.configure(host.getName(), params);
@ -699,9 +693,9 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
protected AgentAttache createAttacheForDirectConnect(HostVO host, ServerResource resource)
throws ConnectionException {
if (resource instanceof DummySecondaryStorageResource || resource instanceof KvmDummyResourceBase) {
return new DummyAttache(this, host.getId(), false);
}
// if (resource instanceof DummySecondaryStorageResource || resource instanceof KvmDummyResourceBase) {
// return new DummyAttache(this, host.getId(), false);
// }
s_logger.debug("create DirectAgentAttache for " + host.getId());
DirectAgentAttache attache = new DirectAgentAttache(this, host.getId(), resource, host.isInMaintenanceStates(), this);
@ -1401,7 +1395,6 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
disconnectInternal(hostId, event, false);
}
@Override
public AgentAttache handleDirectConnectAgent(HostVO host, StartupCommand[] cmds, ServerResource resource, boolean forRebalance) throws ConnectionException {
AgentAttache attache;

View File

@ -66,7 +66,6 @@ import com.cloud.agent.api.TransferAgentCommand;
import com.cloud.agent.transport.Request;
import com.cloud.agent.transport.Request.Version;
import com.cloud.agent.transport.Response;
import com.cloud.api.ApiDBUtils;
import com.cloud.cluster.ClusterManager;
import com.cloud.cluster.ClusterManagerListener;
import com.cloud.cluster.ClusterServicePdu;
@ -86,7 +85,6 @@ import com.cloud.host.Status;
import com.cloud.host.Status.Event;
import com.cloud.resource.ServerResource;
import com.cloud.serializer.GsonHelper;
import com.cloud.storage.resource.DummySecondaryStorageResource;
import com.cloud.utils.DateUtil;
import com.cloud.utils.Profiler;
import com.cloud.utils.concurrency.NamedThreadFactory;
@ -141,7 +139,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust
protected final ConfigKey<Integer> LoadSize = new ConfigKey<Integer>(Integer.class, "direct.agent.load.size", "Advanced", "16",
"How many agents to connect to in each round", true);
protected final ConfigKey<Integer> ScanInterval = new ConfigKey<Integer>(Integer.class, "direct.agent.scan.interval", "Advanced", "90",
"Interval between scans to load agents", false);
"Interval between scans to load agents", false, ConfigKey.Scope.Global, 1000);
protected ConfigValue<Boolean> _agentLBEnabled;
@ -158,7 +156,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust
s_logger.info("Configuring ClusterAgentManagerImpl. management server node id(msid): " + _nodeId);
_loadSize = _configDepot.get(LoadSize);
_directAgentScanInterval = _configDepot.get(ScanInterval).setMultiplier(1000);
_directAgentScanInterval = _configDepot.get(ScanInterval);
_agentLBEnabled = _configDepot.get(EnableLB);
_connectedAgentsThreshold = _configDepot.get(ConnectedAgentThreshold);
@ -293,9 +291,9 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust
@Override
protected AgentAttache createAttacheForDirectConnect(HostVO host, ServerResource resource) {
if (resource instanceof DummySecondaryStorageResource) {
return new DummyAttache(this, host.getId(), false);
}
// if (resource instanceof DummySecondaryStorageResource) {
// return new DummyAttache(this, host.getId(), false);
// }
s_logger.debug("create ClusteredDirectAgentAttache for " + host.getId());
final DirectAgentAttache attache = new ClusteredDirectAgentAttache(this, host.getId(), _nodeId, resource, host.isInMaintenanceStates(), this);
AgentAttache old = null;
@ -565,7 +563,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust
}
if (agent == null) {
AgentUnavailableException ex = new AgentUnavailableException("Host with specified id is not in the right state: " + host.getStatus(), hostId);
ex.addProxyObject(ApiDBUtils.findHostById(hostId).getUuid());
ex.addProxyObject(_entityMgr.findById(Host.class, hostId).getUuid());
throw ex;
}

View File

@ -17,24 +17,26 @@
package com.cloud.network;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.apache.cloudstack.framework.events.EventBus;
import org.apache.cloudstack.framework.events.EventBusException;
import com.cloud.event.EventCategory;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.network.Network.Event;
import com.cloud.network.Network.State;
import com.cloud.network.dao.NetworkDao;
import com.cloud.server.ManagementServer;
import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.fsm.StateListener;
import org.apache.cloudstack.framework.events.EventBus;
import org.apache.cloudstack.framework.events.EventBusException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class NetworkStateListener implements StateListener<State, Event, Network> {
@ -46,8 +48,8 @@ public class NetworkStateListener implements StateListener<State, Event, Network
private static final Logger s_logger = Logger.getLogger(NetworkStateListener.class);
public NetworkStateListener(UsageEventDao usageEventDao, NetworkDao networkDao) {
this._usageEventDao = usageEventDao;
this._networkDao = networkDao;
_usageEventDao = usageEventDao;
_networkDao = networkDao;
}
@Override
@ -72,7 +74,7 @@ public class NetworkStateListener implements StateListener<State, Event, Network
String resourceName = getEntityFromClassName(Network.class.getName());
org.apache.cloudstack.framework.events.Event eventMsg = new org.apache.cloudstack.framework.events.Event(
ManagementServer.Name,
"management-server",
EventCategory.RESOURCE_STATE_CHANGE_EVENT.getName(),
event,
resourceName,

View File

@ -43,6 +43,10 @@ import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationSe
import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.framework.config.ConfigDepot;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigValue;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
@ -87,8 +91,6 @@ import com.cloud.agent.manager.Commands;
import com.cloud.agent.manager.allocator.HostAllocator;
import com.cloud.alert.AlertManager;
import com.cloud.capacity.CapacityManager;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterDetailsVO;
import com.cloud.dc.DataCenter;
@ -129,7 +131,6 @@ import com.cloud.hypervisor.HypervisorGuru;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.network.Network;
import com.cloud.network.NetworkModel;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.rules.RulesManager;
@ -137,14 +138,11 @@ import com.cloud.offering.DiskOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Cluster;
import com.cloud.resource.ResourceManager;
import com.cloud.server.ConfigurationServer;
import com.cloud.server.ManagementServer;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StoragePool;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Volume;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.VolumeVO;
@ -154,18 +152,14 @@ import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.Journal;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.InjectConfig;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
@ -180,7 +174,6 @@ import com.cloud.vm.ItWorkVO.Step;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.NicIpAliasDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.VMInstanceDao;
@ -190,7 +183,7 @@ import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
@Local(value = VirtualMachineManager.class)
public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, Listener {
public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, Listener, Configurable {
private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class);
@Inject
@ -210,8 +203,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Inject
protected VMTemplateDao _templateDao;
@Inject
protected AccountDao _accountDao;
@Inject
protected DomainDao _domainDao;
@Inject
protected ItWorkDao _workDao;
@ -222,8 +213,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Inject
protected NicDao _nicsDao;
@Inject
protected AccountManager _accountMgr;
@Inject
protected HostDao _hostDao;
@Inject
protected AlertManager _alertMgr;
@ -234,8 +223,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Inject
protected VolumeDao _volsDao;
@Inject
protected ConfigurationManager _configMgr;
@Inject
protected HighAvailabilityManager _haMgr;
@Inject
protected HostPodDao _podDao;
@ -254,21 +241,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Inject
protected VMSnapshotDao _vmSnapshotDao;
@Inject
protected ResourceLimitService _resourceLimitMgr;
@Inject
protected RulesManager rulesMgr;
@Inject
protected AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Inject
protected ConfigurationServer _configServer;
@Inject
protected ManagementServer _mgmtServer;
@Inject
protected IPAddressDao _publicIpAddressDao;
@Inject
protected NicIpAliasDao _nicIpAliasDao;
@Inject
protected EntityManager _entityMgr;
@Inject
ConfigDepot _configDepot;
protected List<HostAllocator> _hostAllocators;
@ -286,9 +265,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Inject
protected ResourceManager _resourceMgr;
@Inject
protected SnapshotManager _snapshotMgr;
@Inject
protected VMSnapshotManager _vmSnapshotMgr = null;
@Inject
@ -307,17 +283,46 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
Map<VirtualMachine.Type, VirtualMachineGuru> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru>();
protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine;
ScheduledExecutorService _executor = null;
protected int _operationTimeout;
static final ConfigKey<Integer> StartRetry = new ConfigKey<Integer>(Integer.class, "start.retry", "Advanced", "10", "Number of times to retry create and start commands", true);
static final ConfigKey<Integer> VmOpWaitInterval = new ConfigKey<Integer>("Advanced", Integer.class, "vm.op.wait.interval", "120",
"Time (in seconds) to wait before checking if a previous operation has succeeded", true);
protected int _retry;
static final ConfigKey<Integer> VmOpLockStateRetry = new ConfigKey<Integer>("Advanced", Integer.class, "vm.op.lock.state.retry", "5",
"Times to retry locking the state of a VM for operations, -1 means forever", true);
static final ConfigKey<Long> VmOpCleanupInterval = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cleanup.interval", "86400",
"Interval to run the thread that cleans up the vm operations (in seconds)", false);
static final ConfigKey<Long> VmOpCleanupWait = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cleanup.wait", "3600",
"Time (in seconds) to wait before cleanuping up any vm work items", true);
static final ConfigKey<Long> VmOpCancelInterval = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cancel.interval", "3600",
"Time (in seconds) to wait before cancelling a operation", false);
static final ConfigKey<Boolean> VmDestroyForcestop = new ConfigKey<Boolean>("Advanced", Boolean.class, "vm.destroy.forcestop", "false",
"On destroy, force-stop takes this value ", true);
static final ConfigKey<Integer> ClusterDeltaSyncInterval = new ConfigKey<Integer>("Advanced", Integer.class, "sync.interval", "60", "Cluster Delta sync interval in seconds",
false);
ScheduledExecutorService _executor = null;
@InjectConfig(key = AgentManager.WaitCK)
protected ConfigValue<Integer> _operationTimeout;
@InjectConfig(key = "start.retry")
protected ConfigValue<Integer> _retry;
protected long _nodeId;
protected long _cleanupWait;
protected long _cleanupInterval;
protected long _cancelWait;
protected long _opWaitInterval;
protected int _lockStateRetry;
protected boolean _forceStop;
@InjectConfig(key = "vm.op.cleanup.wait")
protected ConfigValue<Long> _cleanupWait;
@InjectConfig(key = "vm.op.cleanup.interval")
protected ConfigValue<Long> _cleanupInterval;
@InjectConfig(key = "vm.op.cancel.interval")
protected ConfigValue<Long> _cancelWait;
@InjectConfig(key = "vm.op.wait.interval")
protected ConfigValue<Integer> _opWaitInterval;
@InjectConfig(key = "vm.op.lock.state.retry")
protected ConfigValue<Integer> _lockStateRetry;
@InjectConfig(key = "vm.destroy.forcestop")
protected ConfigValue<Boolean> _forceStop;
@InjectConfig(key = "sync.interval")
protected ConfigValue<Integer> _syncInterval;
@Override
public void registerGuru(VirtualMachine.Type type, VirtualMachineGuru guru) {
@ -328,13 +333,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
@DB
public void allocate(String vmInstanceName,
VirtualMachineTemplate template,
ServiceOffering serviceOffering,
Pair<? extends DiskOffering, Long> rootDiskOffering,
LinkedHashMap<? extends DiskOffering, Long> dataDiskOfferings,
LinkedHashMap<? extends Network, ? extends NicProfile> auxiliaryNetworks,
DeploymentPlan plan,
public void allocate(String vmInstanceName, VirtualMachineTemplate template, ServiceOffering serviceOffering, Pair<? extends DiskOffering, Long> rootDiskOffering,
LinkedHashMap<? extends DiskOffering, Long> dataDiskOfferings, LinkedHashMap<? extends Network, ? extends NicProfile> auxiliaryNetworks, DeploymentPlan plan,
HypervisorType hyperType) throws InsufficientCapacityException {
VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName);
@ -393,12 +393,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
@Override
public void allocate(String vmInstanceName,
VirtualMachineTemplate template,
ServiceOffering serviceOffering,
LinkedHashMap<? extends Network, ? extends NicProfile> networks,
DeploymentPlan plan,
HypervisorType hyperType) throws InsufficientCapacityException {
public void allocate(String vmInstanceName, VirtualMachineTemplate template, ServiceOffering serviceOffering, LinkedHashMap<? extends Network, ? extends NicProfile> networks,
DeploymentPlan plan, HypervisorType hyperType) throws InsufficientCapacityException {
allocate(vmInstanceName, template, serviceOffering, new Pair<DiskOffering, Long>(serviceOffering, null), null, networks, plan, hyperType);
}
@ -498,7 +494,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public boolean start() {
_executor.scheduleAtFixedRate(new CleanupTask(), _cleanupInterval, _cleanupInterval, TimeUnit.SECONDS);
_executor.scheduleAtFixedRate(new CleanupTask(), _cleanupInterval.value(), _cleanupInterval.value(), TimeUnit.SECONDS);
cancelWorkItems(_nodeId);
return true;
}
@ -510,21 +506,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException {
Map<String, String> params = _configDao.getConfiguration(xmlParams);
_retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 10);
ReservationContextImpl.init(_entityMgr);
VirtualMachineProfileImpl.init(_entityMgr);
_cancelWait = NumbersUtil.parseLong(params.get(Config.VmOpCancelInterval.key()), 3600);
_cleanupWait = NumbersUtil.parseLong(params.get(Config.VmOpCleanupWait.key()), 3600);
_cleanupInterval = NumbersUtil.parseLong(params.get(Config.VmOpCleanupInterval.key()), 86400) * 1000;
_opWaitInterval = NumbersUtil.parseLong(params.get(Config.VmOpWaitInterval.key()), 120) * 1000;
_lockStateRetry = NumbersUtil.parseInt(params.get(Config.VmOpLockStateRetry.key()), 5);
_operationTimeout = NumbersUtil.parseInt(params.get(Config.Wait.key()), 1800) * 2;
_forceStop = Boolean.parseBoolean(params.get(Config.VmDestroyForcestop.key()));
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
_nodeId = ManagementServerNode.getManagementServerId();
@ -572,13 +556,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
return true;
}
if (vo.getSecondsTaskIsInactive() > _cancelWait) {
if (vo.getSecondsTaskIsInactive() > _cancelWait.value()) {
s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive());
return false;
}
try {
Thread.sleep(_opWaitInterval);
Thread.sleep(_opWaitInterval.value());
} catch (InterruptedException e) {
s_logger.info("Waiting for " + vm + " but is interrupted");
throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted");
@ -594,7 +578,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
long vmId = vm.getId();
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId());
int retry = _lockStateRetry;
int retry = _lockStateRetry.value();
while (retry-- != 0) {
Transaction txn = Transaction.currentTxn();
Ternary<VMInstanceVO, ReservationContext, ItWorkVO> result = null;
@ -682,14 +666,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
@Override
public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params) throws InsufficientCapacityException, ConcurrentOperationException,
ResourceUnavailableException {
advanceStart(vmUuid, params, null);
}
@Override
public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
CallContext cctxt = CallContext.current();
Account account = cctxt.getCallingAccount();
User caller = cctxt.getCallingUser();
@ -709,7 +693,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
VMInstanceVO startedVm = null;
ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId());
VMTemplateVO template = _templateDao.findById(vm.getTemplateId());
VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, vm.getTemplateId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Trying to deploy VM, vm has dcId: " + vm.getDataCenterId() + " and podId: " + vm.getPodIdToDeployIn());
@ -717,8 +701,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), vm.getPodIdToDeployIn(), null, null, null, null, ctx);
if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("advanceStart: DeploymentPlan is provided, using dcId:" + planToDeploy.getDataCenterId() + ", podId: " + planToDeploy.getPodId() + ", clusterId: "
+ planToDeploy.getClusterId() + ", hostId: " + planToDeploy.getHostId() + ", poolId: " + planToDeploy.getPoolId());
s_logger.debug("advanceStart: DeploymentPlan is provided, using dcId:" + planToDeploy.getDataCenterId() + ", podId: " + planToDeploy.getPodId() + ", clusterId: " +
planToDeploy.getClusterId() + ", hostId: " + planToDeploy.getHostId() + ", poolId: " + planToDeploy.getPoolId());
}
plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(),
planToDeploy.getPoolId(), planToDeploy.getPhysicalNetworkId(), ctx);
@ -745,7 +729,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
boolean reuseVolume = true;
DataCenterDeployment originalPlan = plan;
int retry = _retry;
int retry = _retry.value();
while (retry-- != 0) { // It's != so that it can match -1.
if (reuseVolume) {
@ -778,13 +762,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// cannot satisfy the plan passed in to the
// planner
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot satisfy the deployment plan passed in since the ready Root volume is in different cluster. volume's cluster: "
+ rootVolClusterId
+ ", cluster specified: " + clusterIdSpecified);
s_logger.debug("Cannot satisfy the deployment plan passed in since the ready Root volume is in different cluster. volume's cluster: " +
rootVolClusterId + ", cluster specified: " + clusterIdSpecified);
}
throw new ResourceUnavailableException(
"Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for "
+ vm, Cluster.class, clusterIdSpecified);
"Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for " + vm,
Cluster.class, clusterIdSpecified);
}
}
plan = new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(),
@ -792,8 +775,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
} else {
plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId(), null, ctx);
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId
+ " , and clusterId: " + rootVolClusterId);
s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId +
" , and clusterId: " + rootVolClusterId);
}
planChangedByVolume = true;
}
@ -807,8 +790,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
dest = _dpMgr.planDeployment(vmProfile, plan, avoids);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException(
"Unable to create deployment, affinity rules associted to the VM conflict");
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
@ -820,8 +802,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
reuseVolume = false;
continue;
}
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile,
DataCenter.class, plan.getDataCenterId(), areAffinityGroupsAssociated(vmProfile));
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId(),
areAffinityGroupsAssociated(vmProfile));
}
if (dest != null) {
@ -835,13 +817,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
//storing the value of overcommit in the vm_details table for doing a capacity check in case the cluster overcommit ratio is changed.
if (_uservmDetailsDao.findDetail(vm.getId(),"cpuOvercommitRatio") == null && ((Float.parseFloat(cluster_detail_cpu.getValue()) > 1f || Float.parseFloat(cluster_detail_ram.getValue()) > 1f)) ){
if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") == null &&
((Float.parseFloat(cluster_detail_cpu.getValue()) > 1f || Float.parseFloat(cluster_detail_ram.getValue()) > 1f))) {
UserVmDetailVO vmDetail_cpu = new UserVmDetailVO(vm.getId(), "cpuOvercommitRatio", cluster_detail_cpu.getValue());
UserVmDetailVO vmDetail_ram = new UserVmDetailVO(vm.getId(), "memoryOvercommitRatio", cluster_detail_ram.getValue());
_uservmDetailsDao.persist(vmDetail_cpu);
_uservmDetailsDao.persist(vmDetail_ram);
}
else if (_uservmDetailsDao.findDetail(vm.getId(),"cpuOvercommitRatio") != null) {
} else if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") != null) {
UserVmDetailVO vmDetail_cpu = _uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio");
vmDetail_cpu.setValue(cluster_detail_cpu.getValue());
UserVmDetailVO vmDetail_ram = _uservmDetailsDao.findDetail(vm.getId(), "memoryOvercommitRatio");
@ -880,7 +862,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
cmds = new Commands(Command.OnError.Stop);
cmds.addCommand(new StartCommand(vmTO, dest.getHost(), _mgmtServer.getExecuteInSequence()));
cmds.addCommand(new StartCommand(vmTO, dest.getHost(), getExecuteInSequence()));
vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx);
@ -922,7 +904,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.info("The guru did not like the answers so stopping " + vm);
}
StopCommand cmd = new StopCommand(vm, _mgmtServer.getExecuteInSequence());
StopCommand cmd = new StopCommand(vm, getExecuteInSequence());
StopAnswer answer = (StopAnswer)_agentMgr.easySend(destHostId, cmd);
if (answer == null || !answer.getResult()) {
s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers"));
@ -994,8 +976,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
if (startedVm == null) {
throw new CloudRuntimeException("Unable to start instance '" + vm.getHostName()
+ "' (" + vm.getUuid() + "), see management server log for details");
throw new CloudRuntimeException("Unable to start instance '" + vm.getHostName() + "' (" + vm.getUuid() + "), see management server log for details");
}
}
@ -1022,9 +1003,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
protected boolean getExecuteInSequence() {
return false;
}
protected boolean sendStop(VirtualMachineGuru guru, VirtualMachineProfile profile, boolean force) {
VirtualMachine vm = profile.getVirtualMachine();
StopCommand stop = new StopCommand(vm, _mgmtServer.getExecuteInSequence());
StopCommand stop = new StopCommand(vm, getExecuteInSequence());
try {
Answer answer = _agentMgr.send(vm.getHostId(), stop);
if (!answer.getResult()) {
@ -1217,7 +1202,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
vmGuru.prepareStop(profile);
StopCommand stop = new StopCommand(vm, _mgmtServer.getExecuteInSequence());
StopCommand stop = new StopCommand(vm, getExecuteInSequence());
boolean stopped = false;
StopAnswer answer = null;
try {
@ -1344,7 +1329,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.debug("Destroying vm " + vm);
}
advanceStop(vm, _forceStop);
advanceStop(vm, _forceStop.value());
if (!_vmSnapshotMgr.deleteAllVMSnapshots(vm.getId(), null)) {
s_logger.debug("Unable to delete all snapshots for " + vm);
@ -1566,9 +1551,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_networkMgr.rollbackNicForMigration(vmSrc, profile);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName()
+ " in zone "
+ dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs.");
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " +
fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " +
dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm)), null);
} catch (AgentUnavailableException ae) {
@ -1598,13 +1583,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
if (pool != null) {
// Check if pool is accessible from the destination host and disk offering with which the volume was
// created is compliant with the pool type.
if (_poolHostDao.findByPoolHost(pool.getId(), host.getId()) == null ||
pool.isLocal() != diskOffering.getUseLocalStorage()) {
if (_poolHostDao.findByPoolHost(pool.getId(), host.getId()) == null || pool.isLocal() != diskOffering.getUseLocalStorage()) {
// Cannot find a pool for the volume. Throw an exception.
throw new CloudRuntimeException("Cannot migrate volume " + volume + " to storage pool " + pool +
" while migrating vm to host " + host + ". Either the pool is not accessible from the " +
"host or because of the offering with which the volume is created it cannot be placed on " +
"the given pool.");
throw new CloudRuntimeException("Cannot migrate volume " + volume + " to storage pool " + pool + " while migrating vm to host " + host +
". Either the pool is not accessible from the " +
"host or because of the offering with which the volume is created it cannot be placed on " + "the given pool.");
} else if (pool.getId() == currentPool.getId()) {
// If the pool to migrate too is the same as current pool, remove the volume from the list of
// volumes to be migrated.
@ -1613,14 +1596,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
} else {
// Find a suitable pool for the volume. Call the storage pool allocator to find the list of pools.
DiskProfile diskProfile = new DiskProfile(volume, diskOffering, profile.getHypervisorType());
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(),
host.getClusterId(), host.getId(), null, null);
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), null, null);
ExcludeList avoid = new ExcludeList();
boolean currentPoolAvailable = false;
for (StoragePoolAllocator allocator : _storagePoolAllocators) {
List<StoragePool> poolList = allocator.allocateToPool(diskProfile, profile, plan, avoid,
StoragePoolAllocator.RETURN_UPTO_ALL);
List<StoragePool> poolList = allocator.allocateToPool(diskProfile, profile, plan, avoid, StoragePoolAllocator.RETURN_UPTO_ALL);
if (poolList != null && !poolList.isEmpty()) {
// Volume needs to be migrated. Pick the first pool from the list. Add a mapping to migrate the
// volume to a pool only if it is required; that is the current pool on which the volume resides
@ -1637,9 +1618,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
if (!currentPoolAvailable && !volumeToPool.containsKey(volume)) {
// Cannot find a pool for the volume. Throw an exception.
throw new CloudRuntimeException("Cannot find a storage pool which is available for volume " +
volume + " while migrating virtual machine " + profile.getVirtualMachine() + " to host " +
host);
throw new CloudRuntimeException("Cannot find a storage pool which is available for volume " + volume + " while migrating virtual machine " +
profile.getVirtualMachine() + " to host " + host);
}
}
}
@ -1647,8 +1627,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
return volumeToPool;
}
private <T extends VMInstanceVO> void moveVmToMigratingState(T vm, Long hostId, ItWorkVO work)
throws ConcurrentOperationException {
private <T extends VMInstanceVO> void moveVmToMigratingState(T vm, Long hostId, ItWorkVO work) throws ConcurrentOperationException {
// Put the vm in migrating state.
try {
if (!changeState(vm, Event.MigrationRequested, hostId, work, Step.Migrating)) {
@ -1661,8 +1640,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
private <T extends VMInstanceVO> void moveVmOutofMigratingStateOnSuccess(T vm, Long hostId, ItWorkVO work)
throws ConcurrentOperationException {
private <T extends VMInstanceVO> void moveVmOutofMigratingStateOnSuccess(T vm, Long hostId, ItWorkVO work) throws ConcurrentOperationException {
// Put the vm in running state.
try {
if (!changeState(vm, Event.OperationSucceeded, hostId, work, Step.Started)) {
@ -1696,8 +1674,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// If none of the volumes have to be migrated, fail the call. Administrator needs to make a call for migrating
// a vm and not migrating a vm with storage.
if (volumeToPool.isEmpty()) {
throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost +
" to destination host " + destHost + " doesn't involve migrating the volumes.");
throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destHost +
" doesn't involve migrating the volumes.");
}
short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
@ -1749,9 +1727,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(), "Unable to migrate vm " +
vm.getInstanceName() + " from host " + srcHost.getName() + " in zone " + dc.getName() +
" and pod " + dc.getName(), "Migrate Command failed. Please check logs.");
_alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + srcHost.getName() +
" in zone " + dc.getName() + " and pod " + dc.getName(),
"Migrate Command failed. Please check logs.");
try {
_agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
stateTransitTo(vm, Event.OperationFailed, srcHostId);
@ -1842,8 +1820,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
dest = _dpMgr.planDeployment(profile, plan, excludes);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException(
"Unable to create deployment, affinity rules associted to the VM conflict");
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
if (dest != null) {
@ -1888,7 +1865,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
public void run() {
s_logger.trace("VM Operation Thread Running");
try {
_workDao.cleanup(_cleanupWait);
_workDao.cleanup(_cleanupWait.value());
} catch (Exception e) {
s_logger.error("VM Operations failed due to ", e);
}
@ -1950,11 +1927,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
public Command cleanup(VirtualMachine vm) {
return new StopCommand(vm, _mgmtServer.getExecuteInSequence());
return new StopCommand(vm, getExecuteInSequence());
}
public Command cleanup(String vmName) {
return new StopCommand(vmName, _mgmtServer.getExecuteInSequence());
return new StopCommand(vmName, getExecuteInSequence());
}
public Commands fullHostSync(final long hostId, StartupRoutingCommand startup) {
@ -2109,11 +2086,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
}
if ((info == null && (vm.getState() == State.Running || vm.getState() == State.Starting))
|| (info != null && (info.state == State.Running && vm.getState() == State.Starting)))
{
s_logger.info("Found vm " + vm.getInstanceName() + " in inconsistent state. " + vm.getState() + " on CS while " + (info == null ? "Stopped" : "Running")
+ " on agent");
if ((info == null && (vm.getState() == State.Running || vm.getState() == State.Starting)) ||
(info != null && (info.state == State.Running && vm.getState() == State.Starting))) {
s_logger.info("Found vm " + vm.getInstanceName() + " in inconsistent state. " + vm.getState() + " on CS while " + (info == null ? "Stopped" : "Running") +
" on agent");
info = new AgentVmInfo(vm.getInstanceName(), vm, State.Stopped);
// Bug 13850- grab outstanding work item if any for this VM state so that we mark it as DONE after we change VM state, else it will remain pending
@ -2149,9 +2125,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.warn("Unable to update state of the VM due to exception " + e.getMessage());
e.printStackTrace();
}
}
else if (info != null && (vm.getState() == State.Stopped || vm.getState() == State.Stopping
|| vm.isRemoved() || vm.getState() == State.Destroyed || vm.getState() == State.Expunging)) {
} else if (info != null &&
(vm.getState() == State.Stopped || vm.getState() == State.Stopping || vm.isRemoved() || vm.getState() == State.Destroyed || vm.getState() == State.Expunging)) {
Host host = _hostDao.findByGuid(info.getHostUuid());
if (host != null) {
s_logger.warn("Stopping a VM which is stopped/stopping/destroyed/expunging " + info.name);
@ -2169,8 +2144,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.warn("Unable to stop a VM due to " + e.getMessage());
}
}
}
else
} else
// host id can change
if (info != null && vm.getState() == State.Running) {
// check for host id changes
@ -2306,18 +2280,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
HostVO hostVO = _hostDao.findById(vm.getHostId());
String hostDesc = "name: " + hostVO.getName() + " (id:" + hostVO.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(alertType, vm.getDataCenterId(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getInstanceName() + ", id: " + vm.getId() + ") stopped on host "
+ hostDesc
+ " due to storage failure", "Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" + vm.getHostId()
+ "] stopped due to storage failure.");
_alertMgr.sendAlert(alertType, vm.getDataCenterId(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getInstanceName() + ", id: " + vm.getId() + ") stopped on host " +
hostDesc + " due to storage failure",
"Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" + vm.getHostId() + "] stopped due to storage failure.");
}
if (trackExternalChange) {
if (serverState == State.Starting) {
if (vm.getHostId() != null && vm.getHostId() != hostId) {
s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId
+ ", skip status sync for vm: "
+ vm.getInstanceName());
s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId +
", skip status sync for vm: " + vm.getInstanceName());
return null;
}
}
@ -2341,9 +2313,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
if (trackExternalChange) {
if (serverState == State.Starting) {
if (vm.getHostId() != null && vm.getHostId() != hostId) {
s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId
+ ", skip status sync for vm: "
+ vm.getInstanceName());
s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId +
", skip status sync for vm: " + vm.getInstanceName());
return null;
}
}
@ -2358,8 +2329,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
//
if (vm.getHostId() == null || hostId != vm.getHostId()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("detected host change when VM " + vm + " is at running state, VM could be live-migrated externally from host " + vm.getHostId()
+ " to host " + hostId);
s_logger.debug("detected host change when VM " + vm + " is at running state, VM could be live-migrated externally from host " + vm.getHostId() +
" to host " + hostId);
}
stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, hostId);
@ -2485,8 +2456,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
List<NicVO> nics = _nicsDao.listByVmId(profile.getId());
for (NicVO nic : nics) {
Network network = _networkModel.getNetwork(nic.getNetworkId());
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null,
_networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(profile.getHypervisorType(), network));
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkModel.isSecurityGroupSupportedInNetwork(network),
_networkModel.getNetworkTag(profile.getHypervisorType(), network));
profile.addNic(nicProfile);
}
@ -2604,15 +2575,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
// initiate the cron job
ClusterSyncCommand syncCmd = new ClusterSyncCommand(Integer.parseInt(Config.ClusterDeltaSyncInterval.getDefaultValue()), clusterId);
ClusterSyncCommand syncCmd = new ClusterSyncCommand(_syncInterval.value(), clusterId);
try {
long seq_no = _agentMgr.send(agentId, new Commands(syncCmd), this);
s_logger.debug("Cluster VM sync started with jobid " + seq_no);
} catch (AgentUnavailableException e) {
s_logger.fatal("The Cluster VM sync process failed for cluster id " + clusterId + " with ", e);
}
}
else { // for others KVM and VMWare
} else { // for others KVM and VMWare
StartupRoutingCommand startup = (StartupRoutingCommand)cmd;
Commands commands = fullHostSync(agentId, startup);
@ -2658,7 +2628,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
try {
lock.addRef();
List<VMInstanceVO> instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (_operationTimeout * 1000)), State.Starting, State.Stopping);
List<VMInstanceVO> instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (_operationTimeout.value() * 1000)), State.Starting, State.Stopping);
for (VMInstanceVO instance : instances) {
State state = instance.getState();
if (state == State.Stopping) {
@ -2712,19 +2682,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// Check that the VM is stopped / running
if (!(vmInstance.getState().equals(State.Stopped) || vmInstance.getState().equals(State.Running))) {
s_logger.warn("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState()
+ "; make sure the virtual machine is stopped/running");
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState() +
"; make sure the virtual machine is stopped/running");
}
// Check if the service offering being upgraded to is what the VM is already running with
if (vmInstance.getServiceOfferingId() == newServiceOffering.getId()) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested " +
"service offering (" + newServiceOffering.getName() + ")");
s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested " + "service offering (" + newServiceOffering.getName() + ")");
}
throw new InvalidParameterValueException("Not upgrading vm " + vmInstance.toString() + " since it already " +
"has the requested service offering (" + newServiceOffering.getName() + ")");
throw new InvalidParameterValueException("Not upgrading vm " + vmInstance.toString() + " since it already " + "has the requested service offering (" +
newServiceOffering.getName() + ")");
}
ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId());
@ -2741,10 +2710,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// Check that the service offering being upgraded to has the same storage pool preference as the VM's current service
// offering
if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString()
+ ", cannot switch between local storage and shared storage service offerings. Current offering " +
"useLocalStorage=" + currentServiceOffering.getUseLocalStorage()
+ ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage());
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() +
", cannot switch between local storage and shared storage service offerings. Current offering " + "useLocalStorage=" +
currentServiceOffering.getUseLocalStorage() + ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage());
}
// if vm is a system vm, check if it is a system service offering, if yes return with error as it cannot be used for user vms
@ -2754,19 +2722,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// Check that there are enough resources to upgrade the service offering
if (!isVirtualMachineUpgradable(vmInstance, newServiceOffering)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine, not enough resources available " +
"for an offering of " + newServiceOffering.getCpu() + " cpu(s) at "
+ newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory");
throw new InvalidParameterValueException("Unable to upgrade virtual machine, not enough resources available " + "for an offering of " + newServiceOffering.getCpu() +
" cpu(s) at " + newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory");
}
// Check that the service offering being upgraded to has all the tags of the current service offering
List<String> currentTags = StringUtils.csvTagsToList(currentServiceOffering.getTags());
List<String> newTags = StringUtils.csvTagsToList(newServiceOffering.getTags());
if (!newTags.containsAll(currentTags)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering " +
"does not have all the tags of the "
+ "current service offering. Current service offering tags: " + currentTags + "; " + "new service " +
"offering tags: " + newTags);
throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering " + "does not have all the tags of the " +
"current service offering. Current service offering tags: " + currentTags + "; " + "new service " + "offering tags: " +
newTags);
}
}
@ -2782,13 +2748,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
@Override
public NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException {
public NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
CallContext cctx = CallContext.current();
s_logger.debug("Adding vm " + vm + " to network " + network + "; requested nic profile " + requested);
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(User.UID_SYSTEM),
_accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM));
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
@ -2818,9 +2784,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.debug("Nic is plugged successfully for vm " + vm + " in network " + network + ". Vm is a part of network now");
long isDefault = (nic.isDefaultNic()) ? 1 : 0;
// insert nic's Id into DB as resource_name
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmVO.getAccountId(),
vmVO.getDataCenterId(), vmVO.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(),
null, isDefault, VirtualMachine.class.getName(), vmVO.getUuid());
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmVO.getAccountId(), vmVO.getDataCenterId(), vmVO.getId(),
Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vmVO.getUuid());
return nic;
} else {
s_logger.warn("Failed to plug nic to the vm " + vm + " in network " + network);
@ -2828,8 +2793,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
} finally {
if (!result) {
s_logger.debug("Removing nic " + nic + " from vm " + vmProfile.getVirtualMachine()
+ " as nic plug failed on the backend");
s_logger.debug("Removing nic " + nic + " from vm " + vmProfile.getVirtualMachine() + " as nic plug failed on the backend");
_networkMgr.removeNic(vmProfile, _nicsDao.findById(nic.getId()));
}
}
@ -2838,8 +2802,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
return _networkMgr.createNicForVm(network, requested, context, vmProfile, false);
} else {
s_logger.warn("Unable to add vm " + vm + " to network " + network);
throw new ResourceUnavailableException("Unable to add vm " + vm + " to network, is not in the right state",
DataCenter.class, vm.getDataCenterId());
throw new ResourceUnavailableException("Unable to add vm " + vm + " to network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
}
@ -2853,13 +2816,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
public boolean removeNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext cctx = CallContext.current();
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
NetworkVO network = _networkDao.findById(nic.getNetworkId());
ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(User.UID_SYSTEM),
_accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM));
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null,
null, null, null);
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
@ -2875,14 +2837,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// if specified nic is associated with PF/LB/Static NAT
if (rulesMgr.listAssociatedRulesForGuestNic(nic).size() > 0) {
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network
+ ", nic has associated Port forwarding or Load balancer or Static NAT rules.");
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network + ", nic has associated Port forwarding or Load balancer or Static NAT rules.");
}
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(),
_networkModel.getNetworkRate(network.getId(), vm.getId()),
_networkModel.isSecurityGroupSupportedInNetwork(network),
_networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()),
_networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
//1) Unplug the nic
if (vm.getState() == State.Running) {
@ -2892,17 +2851,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
if (result) {
s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
long isDefault = (nic.isDefaultNic()) ? 1 : 0;
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(),
vm.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null,
isDefault, VirtualMachine.class.getName(), vm.getUuid());
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), Long.toString(nic.getId()),
network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid());
} else {
s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
return false;
}
} else if (vm.getState() != State.Stopped) {
s_logger.warn("Unable to remove vm " + vm + " from network " + network);
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state",
DataCenter.class, vm.getDataCenterId());
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
//2) Release the nic
@ -2918,12 +2875,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
@Override
@DB
public boolean removeVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext cctx = CallContext.current();
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(User.UID_SYSTEM),
_accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM));
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null,
null, null, null);
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
@ -2967,10 +2923,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
try {
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(),
_networkModel.getNetworkRate(network.getId(), vm.getId()),
_networkModel.isSecurityGroupSupportedInNetwork(network),
_networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()),
_networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
//1) Unplug the nic
if (vm.getState() == State.Running) {
@ -2985,8 +2939,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
} else if (vm.getState() != State.Stopped) {
s_logger.warn("Unable to remove vm " + vm + " from network " + network);
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state",
DataCenter.class, vm.getDataCenterId());
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
//2) Release the nic
@ -3033,8 +2986,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
dest = _dpMgr.planDeployment(profile, plan, excludes);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException(
"Unable to create deployment, affinity rules associted to the VM conflict");
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
if (dest != null) {
@ -3193,9 +3145,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName()
+ " in zone "
+ dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs.");
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " +
fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " +
dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException ae) {
@ -3215,8 +3167,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException,
ResourceUnavailableException,
InsufficientCapacityException {
ResourceUnavailableException, InsufficientCapacityException {
boolean result = true;
VMInstanceVO router = _vmDao.findById(vm.getId());
@ -3233,21 +3184,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
result = false;
}
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to plug nic for router " + vm.getName() + " in network " + network,
dest.getHost().getId(), e);
throw new AgentUnavailableException("Unable to plug nic for router " + vm.getName() + " in network " + network, dest.getHost().getId(), e);
}
} else {
s_logger.warn("Unable to apply PlugNic, vm " + router + " is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to apply PlugNic on the backend," +
" vm " + vm + " is not in the right state", DataCenter.class, router.getDataCenterId());
throw new ResourceUnavailableException("Unable to apply PlugNic on the backend," + " vm " + vm + " is not in the right state", DataCenter.class,
router.getDataCenterId());
}
return result;
}
public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm,
ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException {
public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException,
ResourceUnavailableException {
boolean result = true;
VMInstanceVO router = _vmDao.findById(vm.getId());
@ -3265,22 +3215,25 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
result = false;
}
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to unplug nic from rotuer " + router + " from network " + network,
dest.getHost().getId(), e);
throw new AgentUnavailableException("Unable to unplug nic from rotuer " + router + " from network " + network, dest.getHost().getId(), e);
}
} else if (router.getState() == State.Stopped || router.getState() == State.Stopping) {
s_logger.debug("Vm " + router.getInstanceName() + " is in " + router.getState() +
", so not sending unplug nic command to the backend");
s_logger.debug("Vm " + router.getInstanceName() + " is in " + router.getState() + ", so not sending unplug nic command to the backend");
} else {
s_logger.warn("Unable to apply unplug nic, Vm " + router + " is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to apply unplug nic on the backend," +
" vm " + router + " is not in the right state", DataCenter.class, router.getDataCenterId());
throw new ResourceUnavailableException("Unable to apply unplug nic on the backend," + " vm " + router + " is not in the right state", DataCenter.class,
router.getDataCenterId());
}
return result;
}
@InjectConfig(key = CapacityManager.CpuOverprovisioningFactorCK)
ConfigValue<Float> _cpuOverprovisioningFactor;
@InjectConfig(key = CapacityManager.MemOverprovisioningFactorCK)
ConfigValue<Float> _memOverprovisioningFactor;
@Override
public VMInstanceVO reConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException,
ConcurrentOperationException {
@ -3290,14 +3243,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
ServiceOffering newServiceOffering = _entityMgr.findById(ServiceOffering.class, newServiceofferingId);
HostVO hostVo = _hostDao.findById(vm.getHostId());
Float memoryOvercommitRatio = Float.parseFloat(_configServer.getConfigValue(Config.MemOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(),
hostVo.getClusterId()));
Float cpuOvercommitRatio = Float.parseFloat(_configServer.getConfigValue(Config.CPUOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(),
hostVo.getClusterId()));
Float memoryOvercommitRatio = _memOverprovisioningFactor.valueIn(hostVo.getClusterId());
Float cpuOvercommitRatio = _cpuOverprovisioningFactor.valueIn(hostVo.getClusterId());
long minMemory = (long)(newServiceOffering.getRamSize() / memoryOvercommitRatio);
ScaleVmCommand reconfigureCmd = new ScaleVmCommand(vm.getInstanceName(), newServiceOffering.getCpu(),
(int)(newServiceOffering.getSpeed() / cpuOvercommitRatio), newServiceOffering.getSpeed(), minMemory * 1024L * 1024L,
newServiceOffering.getRamSize() * 1024L * 1024L, newServiceOffering.getLimitCpuUse());
ScaleVmCommand reconfigureCmd = new ScaleVmCommand(vm.getInstanceName(), newServiceOffering.getCpu(), (int)(newServiceOffering.getSpeed() / cpuOvercommitRatio),
newServiceOffering.getSpeed(), minMemory * 1024L * 1024L, newServiceOffering.getRamSize() * 1024L * 1024L, newServiceOffering.getLimitCpuUse());
Long dstHostId = vm.getHostId();
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Running, vm.getType(), vm.getId());
@ -3339,4 +3289,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
}
@Override
public String getConfigComponentName() {
return VirtualMachineManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {ClusterDeltaSyncInterval, StartRetry, VmDestroyForcestop, VmOpCancelInterval, VmOpCleanupInterval, VmOpCleanupWait, VmOpLockStateRetry,
VmOpWaitInterval};
}
}

View File

@ -45,7 +45,23 @@ import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.MigrateWithStorageAnswer;
import com.cloud.agent.api.MigrateWithStorageCommand;
import com.cloud.agent.api.MigrateWithStorageCompleteAnswer;
import com.cloud.agent.api.MigrateWithStorageCompleteCommand;
import com.cloud.agent.api.MigrateWithStorageReceiveAnswer;
import com.cloud.agent.api.MigrateWithStorageReceiveCommand;
import com.cloud.agent.api.MigrateWithStorageSendAnswer;
import com.cloud.agent.api.MigrateWithStorageSendCommand;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.ScaleVmAnswer;
import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.capacity.CapacityManager;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
@ -60,6 +76,7 @@ import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuru;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.offering.ServiceOffering;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.storage.DiskOfferingVO;
@ -85,6 +102,7 @@ import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshotManager;
public class VirtualMachineManagerImplTest {
@ -95,8 +113,6 @@ public class VirtualMachineManagerImplTest {
@Mock
Account _account;
@Mock
AccountManager _accountMgr;
@Mock
ConfigurationManager _configMgr;
@Mock
CapacityManager _capacityMgr;
@ -141,8 +157,6 @@ public class VirtualMachineManagerImplTest {
@Mock
ItWorkVO _work;
@Mock
ConfigurationServer _configServer;
@Mock
HostVO hostVO;
@Mock
UserVmDetailVO _vmDetailVO;
@ -191,9 +205,6 @@ public class VirtualMachineManagerImplTest {
_vmMgr._templateDao = _templateDao;
_vmMgr._volsDao = _volsDao;
_vmMgr.volumeMgr = _storageMgr;
_vmMgr._accountDao = _accountDao;
_vmMgr._accountMgr = _accountMgr;
_vmMgr._configMgr = _configMgr;
_vmMgr._capacityMgr = _capacityMgr;
_vmMgr._hostDao = _hostDao;
_vmMgr._nodeId = 1L;
@ -209,7 +220,6 @@ public class VirtualMachineManagerImplTest {
_vmMgr._hvGuruMgr = _hvGuruMgr;
_vmMgr._vmSnapshotMgr = _vmSnapshotMgr;
_vmMgr._vmDao = _vmInstanceDao;
_vmMgr._configServer = _configServer;
_vmMgr._uservmDetailsDao = _vmDetailsDao;
_vmMgr._entityMgr = _entityMgr;
@ -256,9 +266,9 @@ public class VirtualMachineManagerImplTest {
doReturn(hostVO).when(_hostDao).findById(1L);
doReturn(1L).when(_vmInstance).getDataCenterId();
doReturn(1L).when(hostVO).getClusterId();
when(_configServer.getConfigValue(Config.EnableDynamicallyScaleVm.key(), Config.ConfigurationParameterScope.zone.toString(), 1L)).thenReturn("true");
when(_configServer.getConfigValue(Config.MemOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(), 1L)).thenReturn("1.0");
when(_configServer.getConfigValue(Config.CPUOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(), 1L)).thenReturn("1.0");
when(_configMgr.getConfigValue(Config.EnableDynamicallyScaleVm.key(), Config.Scope.zone.toString(), 1L)).thenReturn("true");
when(_configMgr.getConfigValue(Config.MemOverprovisioningFactor.key(), Config.Scope.cluster.toString(), 1L)).thenReturn("1.0");
when(_configMgr.getConfigValue(Config.CPUOverprovisioningFactor.key(), Config.Scope.cluster.toString(), 1L)).thenReturn("1.0");
ScaleVmCommand reconfigureCmd = new ScaleVmCommand("myVmName", newServiceOffering.getCpu(),
newServiceOffering.getSpeed(), newServiceOffering.getSpeed(), newServiceOffering.getRamSize(), newServiceOffering.getRamSize(),
newServiceOffering.getLimitCpuUse());
@ -334,8 +344,8 @@ public class VirtualMachineManagerImplTest {
// Mock the vm guru and the user vm object that gets returned.
_vmMgr._vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru>();
UserVmManagerImpl userVmManager = mock(UserVmManagerImpl.class);
_vmMgr.registerGuru(VirtualMachine.Type.User, userVmManager);
// UserVmManagerImpl userVmManager = mock(UserVmManagerImpl.class);
// _vmMgr.registerGuru(VirtualMachine.Type.User, userVmManager);
// Mock the iteration over all the volumes of an instance.
Iterator<VolumeVO> volumeIterator = mock(Iterator.class);

View File

@ -38,6 +38,11 @@
<artifactId>cloud-framework-ipc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-framework-config</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-framework-db</artifactId>

View File

@ -22,7 +22,9 @@ import java.util.Map;
import javax.ejb.Local;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigKey.Scope;
import org.apache.cloudstack.framework.config.ScopedConfigStorage;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.GenericDaoBase;
@ -30,9 +32,8 @@ import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
@Component
@Local(value=ClusterDetailsDao.class)
public class ClusterDetailsDaoImpl extends GenericDaoBase<ClusterDetailsVO, Long> implements ClusterDetailsDao {
public class ClusterDetailsDaoImpl extends GenericDaoBase<ClusterDetailsVO, Long> implements ClusterDetailsDao, ScopedConfigStorage {
protected final SearchBuilder<ClusterDetailsVO> ClusterSearch;
protected final SearchBuilder<ClusterDetailsVO> DetailSearch;
@ -88,7 +89,7 @@ public class ClusterDetailsDaoImpl extends GenericDaoBase<ClusterDetailsVO, Long
@Override
public void deleteDetails(long clusterId) {
SearchCriteria sc = ClusterSearch.create();
SearchCriteria<ClusterDetailsVO> sc = ClusterSearch.create();
sc.setParameters("clusterId", clusterId);
List<ClusterDetailsVO> results = search(sc, null);
@ -130,4 +131,14 @@ public class ClusterDetailsDaoImpl extends GenericDaoBase<ClusterDetailsVO, Long
txn.commit();
}
@Override
public Scope getScope() {
return ConfigKey.Scope.Cluster;
}
@Override
public String getConfigValue(long id, ConfigKey<?> key) {
ClusterDetailsVO vo = findDetail(id, key.key());
return vo == null ? null : vo.getValue();
}
}

View File

@ -22,7 +22,9 @@ import java.util.Map;
import javax.ejb.Local;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigKey.Scope;
import org.apache.cloudstack.framework.config.ScopedConfigStorage;
import com.cloud.dc.DcDetailVO;
import com.cloud.utils.db.GenericDaoBase;
@ -30,9 +32,8 @@ import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
@Component
@Local(value=DcDetailsDao.class)
public class DcDetailsDaoImpl extends GenericDaoBase<DcDetailVO, Long> implements DcDetailsDao {
public class DcDetailsDaoImpl extends GenericDaoBase<DcDetailVO, Long> implements DcDetailsDao, ScopedConfigStorage {
protected final SearchBuilder<DcDetailVO> DcSearch;
protected final SearchBuilder<DcDetailVO> DetailSearch;
@ -71,7 +72,7 @@ public class DcDetailsDaoImpl extends GenericDaoBase<DcDetailVO, Long> implement
@Override
public void deleteDetails(long dcId) {
SearchCriteria sc = DcSearch.create();
SearchCriteria<DcDetailVO> sc = DcSearch.create();
sc.setParameters("dcId", dcId);
List<DcDetailVO> results = search(sc, null);
@ -94,4 +95,16 @@ public class DcDetailsDaoImpl extends GenericDaoBase<DcDetailVO, Long> implement
}
txn.commit();
}
@Override
public Scope getScope() {
return ConfigKey.Scope.Zone;
}
@Override
public String getConfigValue(long id, ConfigKey<?> key) {
DcDetailVO vo = findDetail(id, key.key());
return vo == null ? null : vo.getValue();
}
}

View File

@ -22,19 +22,19 @@ import java.util.Map;
import javax.ejb.Local;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigKey.Scope;
import org.apache.cloudstack.framework.config.ScopedConfigStorage;
import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO;
import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
import org.springframework.stereotype.Component;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
@Component
@Local(value = StoragePoolDetailsDao.class)
public class StoragePoolDetailsDaoImpl extends GenericDaoBase<StoragePoolDetailVO, Long> implements
StoragePoolDetailsDao {
public class StoragePoolDetailsDaoImpl extends GenericDaoBase<StoragePoolDetailVO, Long> implements StoragePoolDetailsDao, ScopedConfigStorage {
protected final SearchBuilder<StoragePoolDetailVO> PoolSearch;
@ -83,4 +83,15 @@ public class StoragePoolDetailsDaoImpl extends GenericDaoBase<StoragePoolDetailV
return findOneIncludingRemovedBy(sc);
}
@Override
public Scope getScope() {
return ConfigKey.Scope.StoragePool;
}
@Override
public String getConfigValue(long id, ConfigKey<?> key) {
StoragePoolDetailVO vo = findDetail(id, key.key());
return vo == null ? null : vo.getValue();
}
}

View File

@ -17,6 +17,7 @@
package com.cloud.user;
import java.util.Map;
import com.cloud.utils.db.GenericDao;

View File

@ -22,19 +22,20 @@ import java.util.Map;
import javax.ejb.Local;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigKey.Scope;
import org.apache.cloudstack.framework.config.ScopedConfigStorage;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.SearchCriteriaService;
import com.cloud.utils.db.Transaction;
@Component
@Local(value = {AccountDetailsDao.class})
public class AccountDetailsDaoImpl extends GenericDaoBase<AccountDetailVO, Long> implements AccountDetailsDao {
public class AccountDetailsDaoImpl extends GenericDaoBase<AccountDetailVO, Long> implements AccountDetailsDao, ScopedConfigStorage {
protected final SearchBuilder<AccountDetailVO> accountSearch;
protected AccountDetailsDaoImpl() {
@ -93,4 +94,15 @@ public class AccountDetailsDaoImpl extends GenericDaoBase<AccountDetailVO, Long>
oldDetails.putAll(details);
persist(accountId, oldDetails);
}
@Override
public Scope getScope() {
return ConfigKey.Scope.Account;
}
@Override
public String getConfigValue(long id, ConfigKey<?> key) {
AccountDetailVO vo = findDetail(id, key.key());
return vo == null ? null : vo.getValue();
}
}

View File

@ -21,7 +21,18 @@ package org.apache.cloudstack.framework.config;
*
*/
public interface ConfigDepot {
/**
* Retrieves the global configuration value for key.
* @param key name of the key to retrieve.
* @return global configuration value even if the key is scoped
*/
<T> ConfigValue<T> get(ConfigKey<T> key);
<T> ScopedConfigValue<T> getScopedValue(ConfigKey<T> key);
/**
* Retrieves a ConfigValue by its name
* @param name name of the config
* @return ConfigValue
*/
ConfigValue<?> get(String name);
}

View File

@ -16,15 +16,21 @@
// under the License.
package org.apache.cloudstack.framework.config;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import org.apache.cloudstack.framework.config.ConfigKey.Scope;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import com.cloud.utils.component.ConfigInjector;
import com.cloud.utils.component.SystemIntegrityChecker;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.exception.CloudRuntimeException;
/**
* ConfigDepotImpl implements the ConfigDepot and ConfigDepotAdmin interface.
@ -39,8 +45,6 @@ import com.cloud.utils.db.EntityManager;
*
* TODO:
* - Move the rest of the changes to the config table to here.
* - Implement ScopedConfigValue
* - Move the code to set scoped configuration values to here.
* - Add the code to mark the rows in configuration table without
* the corresponding keys to be null.
* - Move all of the configurations to using ConfigDepot
@ -48,28 +52,33 @@ import com.cloud.utils.db.EntityManager;
* - Figure out the correct categories.
*
*/
class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin {
class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin, SystemIntegrityChecker, ConfigInjector {
@Inject
EntityManager _entityMgr;
@Inject
ConfigurationDao _configDao;
@Inject
List<Configurable> _configurables;
@Inject
List<ScopedConfigStorage> _scopedStorage;
HashMap<String, ConfigKey<?>> _allKeys = new HashMap<String, ConfigKey<?>>(1007);
public ConfigDepotImpl() {
}
@Override
public <T> ConfigValue<T> get(ConfigKey<T> config) {
if (config.scope() == Scope.Global) {
return new ConfigValue<T>(_entityMgr, config);
} else {
for (ScopedConfigStorage storage : _scopedStorage) {
if (storage.getScope() == config.scope()) {
return new ConfigValue<T>(_entityMgr, config, storage);
}
}
throw new CloudRuntimeException("Unable to find config storage for this scope: " + config.scope());
}
@Override
public <T> ScopedConfigValue<T> getScopedValue(ConfigKey<T> config) {
assert (config.scope() != null) : "Did you notice the configuration you're trying to retrieve is not scoped?";
return new ScopedConfigValue<T>(_entityMgr, config);
}
@Override
@ -103,4 +112,37 @@ class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin {
public List<String> getComponentsInDepot() {
return new ArrayList<String>();
}
@Override
public void check() {
for (Configurable configurable : _configurables) {
for (ConfigKey<?> key : configurable.getConfigKeys()) {
if (_allKeys.containsKey(key.key())) {
throw new CloudRuntimeException("Configurable " + configurable.getConfigComponentName() + " is adding a key that has been added before: " + key.toString());
}
_allKeys.put(key.key(), key);
}
}
}
@Override
public void inject(Field field, Object obj, String key) {
ConfigKey<?> configKey = _allKeys.get(key);
try {
field.set(obj, get(configKey));
} catch (IllegalArgumentException e) {
throw new CloudRuntimeException("Unable to inject configuration due to ", e);
} catch (IllegalAccessException e) {
throw new CloudRuntimeException("Unable to inject configuration due to ", e);
}
}
@Override
public ConfigValue<?> get(String name) {
ConfigKey<?> configKey = _allKeys.get(name);
if (configKey == null) {
throw new CloudRuntimeException("Unable to find a registered config key for " + name);
}
return get(configKey);
}
}

View File

@ -16,7 +16,8 @@
// under the License.
package org.apache.cloudstack.framework.config;
import com.cloud.org.Grouping;
import com.cloud.utils.exception.CloudRuntimeException;
/**
* ConfigKey supplants the original Config.java. It is just a class
@ -25,6 +26,10 @@ import com.cloud.org.Grouping;
*/
public class ConfigKey<T> {
public static enum Scope {
Global, Zone, Cluster, StoragePool, Account
}
private final String _category;
public String category() {
@ -35,7 +40,7 @@ public class ConfigKey<T> {
return _type;
}
public String key() {
public final String key() {
return _name;
}
@ -47,7 +52,7 @@ public class ConfigKey<T> {
return _description;
}
public Class<? extends Grouping> scope() {
public Scope scope() {
return _scope;
}
@ -64,11 +69,19 @@ public class ConfigKey<T> {
private final String _name;
private final String _defaultValue;
private final String _description;
private final Class<? extends Grouping> _scope; // Parameter can be at different levels (Zone/cluster/pool/account), by default every parameter is at global
private final Scope _scope; // Parameter can be at different levels (Zone/cluster/pool/account), by default every parameter is at global
private final boolean _isDynamic;
private final T _multiplier;
public ConfigKey(Class<T> type, String name, String category, String defaultValue, String description, boolean isDynamic,
Class<? extends Grouping> scope) {
public ConfigKey(String category, Class<T> type, String name, String defaultValue, String description, boolean isDynamic, Scope scope) {
this(type, name, category, defaultValue, description, isDynamic, scope, null);
}
public ConfigKey(String category, Class<T> type, String name, String defaultValue, String description, boolean isDynamic) {
this(type, name, category, defaultValue, description, isDynamic, Scope.Global, null);
}
public ConfigKey(Class<T> type, String name, String category, String defaultValue, String description, boolean isDynamic, Scope scope, T multiplier) {
_category = category;
_type = type;
_name = name;
@ -76,9 +89,32 @@ public class ConfigKey<T> {
_description = description;
_scope = scope;
_isDynamic = isDynamic;
_multiplier = multiplier;
}
public ConfigKey(Class<T> type, String name, String category, String defaultValue, String description, boolean isDynamic) {
this(type, name, category, defaultValue, description, isDynamic, null);
this(type, name, category, defaultValue, description, isDynamic, Scope.Global, null);
}
public T multiplier() {
return _multiplier;
}
@Override
public int hashCode() {
return _name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ConfigKey) {
ConfigKey<?> that = (ConfigKey<?>)obj;
return this._name.equals(that._name);
} else if (obj instanceof String) {
String key = (String)obj;
return key.equals(_name);
}
throw new CloudRuntimeException("Comparing ConfigKey to " + obj.toString());
}
}

View File

@ -16,6 +16,8 @@
// under the License.
package org.apache.cloudstack.framework.config;
import java.sql.Date;
import org.apache.cloudstack.config.Configuration;
import com.cloud.utils.db.EntityManager;
@ -31,48 +33,66 @@ public class ConfigValue<T> {
ConfigKey<T> _config;
EntityManager _entityMgr;
Number _multiplier;
T _value;
ScopedConfigStorage _storage;
public ConfigValue(EntityManager entityMgr, ConfigKey<T> config) {
_entityMgr = entityMgr;
_config = config;
_multiplier = 1;
}
protected ConfigValue(EntityManager entityMgr, ConfigKey<T> key, ScopedConfigStorage storage) {
this(entityMgr, key);
_storage = storage;
}
public ConfigKey<T> getConfigKey() {
return _config;
}
public ConfigValue<T> setMultiplier(Number multiplier) { // Convience method
_multiplier = multiplier;
return this;
}
@SuppressWarnings("unchecked")
public T value() {
if (_value == null || _config.isDynamic()) {
Configuration vo = _entityMgr.findById(Configuration.class, _config.key());
String value = vo != null ? vo.getValue() : _config.defaultValue();
Class<T> type = _config.type();
if (type.isAssignableFrom(Boolean.class)) {
_value = (T)Boolean.valueOf(value);
} else if (type.isAssignableFrom(Integer.class)) {
_value = (T)new Integer((Integer.parseInt(value) * _multiplier.intValue()));
} else if (type.isAssignableFrom(Long.class)) {
_value = (T)new Long(Long.parseLong(value) * _multiplier.longValue());
} else if (type.isAssignableFrom(Short.class)) {
_value = (T)new Short(Short.parseShort(value));
} else if (type.isAssignableFrom(String.class)) {
_value = (T)value;
} else if (type.isAssignableFrom(Float.class)) {
_value = (T)new Float(Float.parseFloat(value) * _multiplier.floatValue());
} else {
throw new CloudRuntimeException("Unsupported data type for config values: " + type);
}
_value = valueOf(vo != null ? vo.getValue() : _config.defaultValue());
}
return _value;
}
public T valueIn(long id) {
String value = _storage.getConfigValue(id, _config);
if (value == null) {
return value();
} else {
return valueOf(value);
}
}
@SuppressWarnings("unchecked")
protected T valueOf(String value) {
Class<T> type = _config.type();
if (type.isAssignableFrom(Boolean.class)) {
return (T)Boolean.valueOf(value);
} else if (type.isAssignableFrom(Integer.class)) {
return (T)new Integer((Integer.parseInt(value) * ((Number)_config.multiplier()).intValue()));
} else if (type.isAssignableFrom(Long.class)) {
return (T)new Long(Long.parseLong(value) * ((Number)_config.multiplier()).longValue());
} else if (type.isAssignableFrom(Short.class)) {
return (T)new Short(Short.parseShort(value));
} else if (type.isAssignableFrom(String.class)) {
return (T)value;
} else if (type.isAssignableFrom(Float.class)) {
return (T)new Float(Float.parseFloat(value) * ((Number)_config.multiplier()).floatValue());
} else if (type.isAssignableFrom(Double.class)) {
return (T)new Double(Double.parseDouble(value));
} else if (type.isAssignableFrom(String.class)) {
return (T)value;
} else if (type.isAssignableFrom(Date.class)) {
return (T)Date.valueOf(value);
} else if (type.isAssignableFrom(Character.class)) {
return (T)new Character(value.charAt(0));
} else {
throw new CloudRuntimeException("Unsupported data type for config values: " + type);
}
}
}

View File

@ -80,7 +80,7 @@ public class ConfigurationVO implements Configuration {
this(key.category(), "DEFAULT", component, key.key(), key.defaultValue(), key.description());
defaultValue = key.defaultValue();
dynamic = key.isDynamic();
scope = key.scope() != null ? key.scope().getName() : null;
scope = key.scope() != null ? key.scope().toString() : null;
}
@Override

View File

@ -1,43 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.framework.config;
import com.cloud.dc.DataCenter;
import com.cloud.dc.Pod;
import com.cloud.org.Cluster;
import com.cloud.org.Grouping;
import com.cloud.utils.db.EntityManager;
public class ScopedConfigValue<T> extends ConfigValue<T> {
public T getValueForScope(long scopeId) {
// TODO: In order to complete this the details for zone, pod, cluster
// needs to have interfaces. Then you can use the EntityManager to
// retrieve those information.
Class<? extends Grouping> scope = _config.scope();
if (scope == DataCenter.class) {
} else if (scope == Pod.class) {
} else if (scope == Cluster.class) {
}
return null;
}
protected ScopedConfigValue(EntityManager entityMgr, ConfigKey<T> key) {
super(entityMgr, key);
}
}

View File

@ -62,6 +62,7 @@ import com.cloud.cluster.ManagementServerHost;
import com.cloud.utils.DateUtil;
import com.cloud.utils.Predicate;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.InjectConfig;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
@ -80,9 +81,9 @@ import com.cloud.utils.mgmt.JmxUtil;
public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, ClusterManagerListener, Configurable {
// Advanced
private static final ConfigKey<Long> JobExpireMinutes = new ConfigKey<Long>(Long.class, "job.expire.minutes", "Advanced", "1440",
"Time (in minutes) for async-jobs to be kept in system", true, null);
private static final ConfigKey<Long> JobCancelThresholdMinutes = new ConfigKey<Long>(Long.class, "job.cancel.threshold.minutes", "Advanced",
"60", "Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", true, null);
"Time (in minutes) for async-jobs to be kept in system", true, ConfigKey.Scope.Global, 60l);
private static final ConfigKey<Long> JobCancelThresholdMinutes = new ConfigKey<Long>(Long.class, "job.cancel.threshold.minutes", "Advanced", "60",
"Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", true, ConfigKey.Scope.Global, 60l);
private static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class);
@ -105,7 +106,9 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager,
@Inject
private ConfigDepot _configDepot;
@InjectConfig(key = "job.expire.minutes")
private ConfigValue<Long> _jobExpireSeconds; // 1 day
@InjectConfig(key = "job.cancel.threshold.minutes")
private ConfigValue<Long> _jobCancelThresholdSeconds; // 1 hour (for cancelling the jobs blocking other jobs)
private volatile long _executionRunNumber = 1;
@ -878,8 +881,8 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager,
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_jobExpireSeconds = _configDepot.get(JobExpireMinutes).setMultiplier(60);
_jobCancelThresholdSeconds = _configDepot.get(JobCancelThresholdMinutes).setMultiplier(60);
_jobExpireSeconds = _configDepot.get(JobExpireMinutes);
_jobCancelThresholdSeconds = _configDepot.get(JobCancelThresholdMinutes);
try {
final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties");

View File

@ -19,6 +19,15 @@
package com.cloud.network.guru;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.CreateVnsNetworkAnswer;
import com.cloud.agent.api.CreateVnsNetworkCommand;
@ -35,9 +44,9 @@ import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.BigSwitchVnsDeviceVO;
import com.cloud.network.Network;
import com.cloud.network.NetworkProfile;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.State;
import com.cloud.network.NetworkProfile;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.PhysicalNetwork.IsolationMethod;
@ -51,18 +60,8 @@ import com.cloud.user.Account;
import com.cloud.user.dao.AccountDao;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.log4j.Logger;
import javax.ejb.Local;
import javax.inject.Inject;
@Local(value = NetworkGuru.class)
public class BigSwitchVnsGuestNetworkGuru extends GuestNetworkGuru {
@ -161,8 +160,7 @@ public class BigSwitchVnsGuestNetworkGuru extends GuestNetworkGuru {
implemented.setCidr(network.getCidr());
}
String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId,
network.getAccountId(), context.getReservationId(), canUseSystemGuestVlan(network.getAccountId()));
String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), context.getReservationId(), _useSystemGuestVlans.valueIn(network.getAccountId()));
if (vnet == null) {
throw new InsufficientVirtualNetworkCapcityException("Unable to allocate vnet as a " +
"part of network " + network + " implement ", DataCenter.class, dcId);

View File

@ -27,11 +27,10 @@ import com.cloud.network.Network;
import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.router.VirtualRouter;
import com.cloud.user.Account;
import com.cloud.utils.component.Manager;
import com.cloud.utils.net.Ip;
import com.cloud.vm.VirtualMachineProfile.Param;
public interface InternalLoadBalancerVMManager extends Manager, InternalLoadBalancerVMService{
public interface InternalLoadBalancerVMManager {
//RAM/CPU for the system offering used by Internal LB VMs
public static final int DEFAULT_INTERNALLB_VM_RAMSIZE = 128; // 128 MB
public static final int DEFAULT_INTERNALLB_VM_CPU_MHZ = 256; // 256 MHz

View File

@ -27,9 +27,10 @@ import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.ConfigDepot;
import org.apache.cloudstack.framework.config.ConfigValue;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO;
import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao;
@ -79,6 +80,7 @@ import com.cloud.network.lb.LoadBalancingRule.LbDestination;
import com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy;
import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
import com.cloud.network.lb.LoadBalancingRulesManager;
import com.cloud.network.router.VirtualNetworkApplianceManager;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.RedundantState;
import com.cloud.network.router.VirtualRouter.Role;
@ -117,12 +119,9 @@ import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDao;
@Component
@Local(value = { InternalLoadBalancerVMManager.class, InternalLoadBalancerVMService.class})
public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements
InternalLoadBalancerVMManager, VirtualMachineGuru {
private static final Logger s_logger = Logger
.getLogger(InternalLoadBalancerVMManagerImpl.class);
public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements InternalLoadBalancerVMManager, InternalLoadBalancerVMService, VirtualMachineGuru {
private static final Logger s_logger = Logger.getLogger(InternalLoadBalancerVMManagerImpl.class);
static final private String _internalLbVmNamePrefix = "b";
private String _instance;
@ -151,6 +150,8 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements
@Inject VMTemplateDao _templateDao;
@Inject ResourceManager _resourceMgr;
@Inject ConfigurationServer _configServer;
@Inject
ConfigDepot _configDepot;
@Override
public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile,
@ -343,6 +344,13 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements
public void prepareStop(VirtualMachineProfile profile) {
}
static ConfigValue<Integer> _networkLockTimeout;
static ConfigValue<String> _routerTemplateXen;
static ConfigValue<String> _routerTemplateKvm;
static ConfigValue<String> _routerTemplateVmware;
static ConfigValue<String> _routerTemplateHyperV;
static ConfigValue<String> _routerTemplateLxc;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
final Map<String, String> configs = _configDao.getConfiguration("AgentManager", params);
@ -351,6 +359,13 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements
_instance = "DEFAULT";
}
_networkLockTimeout = _configDepot.get(NetworkOrchestrationService.NetworkLockTimeout);
_routerTemplateXen = _configDepot.get(VirtualNetworkApplianceManager.RouterTemplateXen);
_routerTemplateKvm = _configDepot.get(VirtualNetworkApplianceManager.RouterTemplateKvm);
_routerTemplateVmware = _configDepot.get(VirtualNetworkApplianceManager.RouterTemplateVmware);
_routerTemplateHyperV = _configDepot.get(VirtualNetworkApplianceManager.RouterTemplateHyperV);
_routerTemplateLxc = _configDepot.get(VirtualNetworkApplianceManager.RouterTemplateLxc);
_mgmtHost = configs.get("host");
_mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
@ -587,7 +602,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements
InsufficientCapacityException, ResourceUnavailableException {
List<DomainRouterVO> internalLbVms = new ArrayList<DomainRouterVO>();
Network lock = _networkDao.acquireInLockTable(guestNetwork.getId(), _ntwkMgr.getNetworkLockTimeout());
Network lock = _networkDao.acquireInLockTable(guestNetwork.getId(), _networkLockTimeout.value());
if (lock == null) {
throw new ConcurrentOperationException("Unable to lock network " + guestNetwork.getId());
}
@ -740,19 +755,19 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements
} String templateName = null;
switch (hType) {
case XenServer:
templateName = _configServer.getConfigValue(Config.RouterTemplateXen.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateXen.valueIn(dest.getDataCenter().getId());
break;
case KVM:
templateName = _configServer.getConfigValue(Config.RouterTemplateKVM.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateKvm.valueIn(dest.getDataCenter().getId());
break;
case VMware:
templateName = _configServer.getConfigValue(Config.RouterTemplateVmware.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateVmware.valueIn(dest.getDataCenter().getId());
break;
case Hyperv:
templateName = _configServer.getConfigValue(Config.RouterTemplateHyperv.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateHyperV.valueIn(dest.getDataCenter().getId());
break;
case LXC:
templateName = _configServer.getConfigValue(Config.RouterTemplateLXC.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateLxc.valueIn(dest.getDataCenter().getId());
break;
default: break;
}

View File

@ -19,10 +19,7 @@ package com.cloud.network.guru;
import javax.ejb.Local;
import javax.inject.Inject;
import com.cloud.event.ActionEventUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.context.CallContext;
@ -30,6 +27,7 @@ import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.event.ActionEventUtils;
import com.cloud.event.EventTypes;
import com.cloud.event.EventVO;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
@ -45,7 +43,6 @@ import com.cloud.offering.NetworkOffering;
import com.cloud.user.Account;
import com.cloud.vm.ReservationContext;
@Component
@Local(value=NetworkGuru.class)
public class OvsGuestNetworkGuru extends GuestNetworkGuru {
private static final Logger s_logger = Logger.getLogger(OvsGuestNetworkGuru.class);
@ -96,8 +93,7 @@ public class OvsGuestNetworkGuru extends GuestNetworkGuru {
protected void allocateVnet(Network network, NetworkVO implemented, long dcId,
long physicalNetworkId, String reservationId) throws InsufficientVirtualNetworkCapcityException {
if (network.getBroadcastUri() == null) {
String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), reservationId,
canUseSystemGuestVlan(network.getAccountId()));
String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), reservationId, _useSystemGuestVlans.valueIn(network.getAccountId()));
if (vnet == null) {
throw new InsufficientVirtualNetworkCapcityException("Unable to allocate vnet as a part of network " + network + " implement ", DataCenter.class, dcId);
}

View File

@ -1,26 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.agent.manager;
import com.cloud.agent.Listener;
public interface AgentMonitorService extends Listener {
public Long getAgentPingTime(long agentId);
public void pingBy(long agentId);
public void signalStop();
}

View File

@ -38,13 +38,20 @@ import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.sun.mail.smtp.SMTPMessage;
import com.sun.mail.smtp.SMTPSSLTransport;
import com.sun.mail.smtp.SMTPTransport;
import org.apache.cloudstack.framework.config.ConfigDepot;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigValue;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.alert.dao.AlertDao;
import com.cloud.api.ApiDBUtils;
import com.cloud.capacity.Capacity;
@ -67,25 +74,17 @@ import com.cloud.dc.dao.HostPodDao;
import com.cloud.event.AlertGenerator;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.org.Grouping.AllocationState;
import com.cloud.resource.ResourceManager;
import com.cloud.server.ConfigurationServer;
import com.cloud.storage.StorageManager;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchCriteria;
import com.sun.mail.smtp.SMTPMessage;
import com.sun.mail.smtp.SMTPSSLTransport;
import com.sun.mail.smtp.SMTPTransport;
@Component
@Local(value={AlertManager.class})
public class AlertManagerImpl extends ManagerBase implements AlertManager {
public class AlertManagerImpl extends ManagerBase implements AlertManager, Configurable {
private static final Logger s_logger = Logger.getLogger(AlertManagerImpl.class.getName());
private static final Logger s_alertsLogger = Logger.getLogger("org.apache.cloudstack.alerts");
@ -96,28 +95,27 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
private EmailAlert _emailAlert;
@Inject private AlertDao _alertDao;
@Inject private HostDao _hostDao;
@Inject protected StorageManager _storageMgr;
@Inject protected CapacityManager _capacityMgr;
@Inject private CapacityDao _capacityDao;
@Inject private DataCenterDao _dcDao;
@Inject private HostPodDao _podDao;
@Inject private ClusterDao _clusterDao;
@Inject private VolumeDao _volumeDao;
@Inject private IPAddressDao _publicIPAddressDao;
@Inject private DataCenterIpAddressDao _privateIPAddressDao;
@Inject private PrimaryDataStoreDao _storagePoolDao;
@Inject private ConfigurationDao _configDao;
@Inject private ResourceManager _resourceMgr;
@Inject private ConfigurationManager _configMgr;
@Inject ConfigurationServer _configServer;
@Inject
protected ConfigDepot _configDepot;
private Timer _timer = null;
private float _cpuOverProvisioningFactor = 1;
private long _capacityCheckPeriod = 60L * 60L * 1000L; // one hour by default
private double _memoryCapacityThreshold = 0.75;
private double _cpuCapacityThreshold = 0.75;
private double _storageCapacityThreshold = 0.75;
private double _storageAllocCapacityThreshold = 0.75;
private ConfigValue<Double> _memoryCapacityThreshold;
private ConfigValue<Double> _cpuCapacityThreshold;
private ConfigValue<Double> _storageCapacityThreshold;
private ConfigValue<Double> _storageAllocCapacityThreshold;
private double _publicIPCapacityThreshold = 0.75;
private double _privateIPCapacityThreshold = 0.75;
private double _secondaryStorageCapacityThreshold = 0.75;
@ -152,11 +150,6 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
_emailAlert = new EmailAlert(emailAddresses, smtpHost, smtpPort, useAuth, smtpUsername, smtpPassword, emailSender, smtpDebug);
String storageCapacityThreshold = _configDao.getValue(Config.StorageCapacityThreshold.key());
String cpuCapacityThreshold = _configDao.getValue(Config.CPUCapacityThreshold.key());
String memoryCapacityThreshold = _configDao.getValue(Config.MemoryCapacityThreshold.key());
String storageAllocCapacityThreshold = _configDao.getValue(Config.StorageAllocatedCapacityThreshold.key());
String publicIPCapacityThreshold = _configDao.getValue(Config.PublicIpCapacityThreshold.key());
String privateIPCapacityThreshold = _configDao.getValue(Config.PrivateIpCapacityThreshold.key());
String secondaryStorageCapacityThreshold = _configDao.getValue(Config.SecondaryStorageCapacityThreshold.key());
@ -164,18 +157,11 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
String directNetworkPublicIpCapacityThreshold = _configDao.getValue(Config.DirectNetworkPublicIpCapacityThreshold.key());
String localStorageCapacityThreshold = _configDao.getValue(Config.LocalStorageCapacityThreshold.key());
if (storageCapacityThreshold != null) {
_storageCapacityThreshold = Double.parseDouble(storageCapacityThreshold);
}
if (storageAllocCapacityThreshold != null) {
_storageAllocCapacityThreshold = Double.parseDouble(storageAllocCapacityThreshold);
}
if (cpuCapacityThreshold != null) {
_cpuCapacityThreshold = Double.parseDouble(cpuCapacityThreshold);
}
if (memoryCapacityThreshold != null) {
_memoryCapacityThreshold = Double.parseDouble(memoryCapacityThreshold);
}
_storageCapacityThreshold = _configDepot.get(StorageCapacityThreshold);
_cpuCapacityThreshold = _configDepot.get(CPUCapacityThreshold);
_memoryCapacityThreshold = _configDepot.get(MemoryCapacityThreshold);
_storageAllocCapacityThreshold = _configDepot.get(StorageAllocatedCapacityThreshold);
if (publicIPCapacityThreshold != null) {
_publicIPCapacityThreshold = Double.parseDouble(publicIPCapacityThreshold);
}
@ -195,10 +181,6 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
_localStorageCapacityThreshold = Double.parseDouble(localStorageCapacityThreshold);
}
_capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_STORAGE, _storageCapacityThreshold);
_capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, _storageAllocCapacityThreshold);
_capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_CPU, _cpuCapacityThreshold);
_capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_MEMORY, _memoryCapacityThreshold);
_capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP, _publicIPCapacityThreshold);
_capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_PRIVATE_IP, _privateIPCapacityThreshold);
_capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_SECONDARY_STORAGE, _secondaryStorageCapacityThreshold);
@ -214,14 +196,6 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
_capacityCheckPeriod = Long.parseLong(Config.CapacityCheckPeriod.getDefaultValue());
}
String cpuOverProvisioningFactorStr = configs.get("cpu.overprovisioning.factor");
if (cpuOverProvisioningFactorStr != null) {
_cpuOverProvisioningFactor = NumbersUtil.parseFloat(cpuOverProvisioningFactorStr,1);
if(_cpuOverProvisioningFactor < 1){
_cpuOverProvisioningFactor = 1;
}
}
_timer = new Timer("CapacityChecker");
return true;
@ -504,19 +478,6 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
}
}
private float getOverProvisioningFactor(long clusterId, short capacityType) {
float overProvisioinigFactor = 1f;
switch (capacityType) {
case Capacity.CAPACITY_TYPE_CPU:
overProvisioinigFactor = Float.parseFloat(_configServer.getConfigValue(Config.CPUOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(), clusterId));
break;
case Capacity.CAPACITY_TYPE_MEMORY:
overProvisioinigFactor = Float.parseFloat(_configServer.getConfigValue(Config.MemOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(), clusterId));
break;
}
return overProvisioinigFactor;
}
public void checkForAlerts(){
recalculateCapacity();
@ -582,16 +543,16 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
switch (capacityType) {
case Capacity.CAPACITY_TYPE_STORAGE:
capacity.add(getUsedStats(capacityType, cluster.getDataCenterId(), cluster.getPodId(), cluster.getId()));
threshold = Double.parseDouble(_configServer.getConfigValue(Config.StorageCapacityThreshold.key(), Config.ConfigurationParameterScope.cluster.toString(), cluster.getId()));
threshold = _storageCapacityThreshold.valueIn(cluster.getId());
break;
case Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED:
threshold = Double.parseDouble(_configServer.getConfigValue(Config.StorageAllocatedCapacityThreshold.key(), Config.ConfigurationParameterScope.cluster.toString(), cluster.getId()));
threshold = _storageAllocCapacityThreshold.valueIn(cluster.getId());
break;
case Capacity.CAPACITY_TYPE_CPU:
threshold = Double.parseDouble(_configServer.getConfigValue(Config.CPUCapacityThreshold.key(), Config.ConfigurationParameterScope.cluster.toString(), cluster.getId()));
threshold = _cpuCapacityThreshold.valueIn(cluster.getId());
break;
case Capacity.CAPACITY_TYPE_MEMORY:
threshold = Double.parseDouble(_configServer.getConfigValue(Config.MemoryCapacityThreshold.key(), Config.ConfigurationParameterScope.cluster.toString(), cluster.getId()));
threshold = _memoryCapacityThreshold.valueIn(cluster.getId());
break;
default:
threshold = _capacityTypeThresholdMap.get(capacityType);
@ -897,4 +858,14 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
double megaBytes = (bytes / (1024 * 1024));
return _dfWhole.format(megaBytes);
}
@Override
public String getConfigComponentName() {
return AlertManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {CPUCapacityThreshold, MemoryCapacityThreshold, StorageAllocatedCapacityThreshold, StorageCapacityThreshold};
}
}

View File

@ -103,6 +103,7 @@ import com.cloud.api.query.vo.TemplateJoinVO;
import com.cloud.api.query.vo.UserAccountJoinVO;
import com.cloud.api.query.vo.UserVmJoinVO;
import com.cloud.api.query.vo.VolumeJoinVO;
import com.cloud.capacity.CapacityManager;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity;
@ -1047,7 +1048,7 @@ public class ApiDBUtils {
}
public static float getCpuOverprovisioningFactor() {
String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key());
String opFactor = _configDao.getValue(CapacityManager.CpuOverprovisioningFactorCK);
float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1);
return cpuOverprovisioningFactor;
}

View File

@ -842,7 +842,6 @@ public class ApiResponseHelper implements ResponseGenerator {
public static List<CapacityResponse> getDataCenterCapacityResponse(Long zoneId) {
List<SummedCapacity> capacities = ApiDBUtils.getCapacityByClusterPodZone(zoneId, null, null);
Set<CapacityResponse> capacityResponses = new HashSet<CapacityResponse>();
float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor();
for (SummedCapacity capacity : capacities) {
CapacityResponse capacityResponse = new CapacityResponse();

View File

@ -28,8 +28,9 @@ import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.PublishScope;
@ -71,7 +72,6 @@ import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
@ -83,27 +83,18 @@ import com.cloud.utils.db.Transaction;
import com.cloud.utils.fsm.StateListener;
import com.cloud.vm.UserVmDetailVO;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.UserVmDetailVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshot;
import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
@Component
@Local(value = CapacityManager.class)
public class CapacityManagerImpl extends ManagerBase implements CapacityManager, StateListener<State, VirtualMachine.Event, VirtualMachine>, Listener, ResourceListener {
public class CapacityManagerImpl extends ManagerBase implements CapacityManager, StateListener<State, VirtualMachine.Event, VirtualMachine>, Listener, ResourceListener,
Configurable {
private static final Logger s_logger = Logger.getLogger(CapacityManagerImpl.class);
@Inject
CapacityDao _capacityDao;
@ -932,4 +923,14 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
}
return false;
}
@Override
public String getConfigComponentName() {
return CapacityManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {CpuOverprovisioningFactor, MemOverprovisioningFactor};
}
}

View File

@ -23,6 +23,7 @@ import java.util.StringTokenizer;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.framework.config.ConfigKey;
import com.cloud.agent.AgentManager;
import com.cloud.consoleproxy.ConsoleProxyManager;
@ -50,25 +51,21 @@ public enum Config {
AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null),
AlertSMTPUsername("Alert", ManagementServer.class, String.class, "alert.smtp.username", null, "Username for SMTP authentication (applies only if alert.smtp.useAuth is true).", null),
CapacityCheckPeriod("Alert", ManagementServer.class, Integer.class, "capacity.check.period", "300000", "The interval in milliseconds between capacity checks", null),
StorageAllocatedCapacityThreshold("Alert", ManagementServer.class, Float.class, "cluster.storage.allocated.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of allocated storage utilization above which alerts will be sent about low storage available.", null, ConfigurationParameterScope.cluster.toString()),
StorageCapacityThreshold("Alert", ManagementServer.class, Float.class, "cluster.storage.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available.", null, ConfigurationParameterScope.cluster.toString()),
CPUCapacityThreshold("Alert", ManagementServer.class, Float.class, "cluster.cpu.allocated.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of cpu utilization above which alerts will be sent about low cpu available.", null, ConfigurationParameterScope.cluster.toString()),
MemoryCapacityThreshold("Alert", ManagementServer.class, Float.class, "cluster.memory.allocated.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of memory utilization above which alerts will be sent about low memory available.", null, ConfigurationParameterScope.cluster.toString()),
PublicIpCapacityThreshold("Alert", ManagementServer.class, Float.class, "zone.virtualnetwork.publicip.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of public IP address space utilization above which alerts will be sent.", null),
PrivateIpCapacityThreshold("Alert", ManagementServer.class, Float.class, "pod.privateip.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of private IP address space utilization above which alerts will be sent.", null),
SecondaryStorageCapacityThreshold("Alert", ManagementServer.class, Float.class, "zone.secstorage.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of secondary storage utilization above which alerts will be sent about low storage available.", null),
VlanCapacityThreshold("Alert", ManagementServer.class, Float.class, "zone.vlan.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of Zone Vlan utilization above which alerts will be sent about low number of Zone Vlans.", null),
DirectNetworkPublicIpCapacityThreshold("Alert", ManagementServer.class, Float.class, "zone.directnetwork.publicip.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of Direct Network Public Ip Utilization above which alerts will be sent about low number of direct network public ips.", null),
LocalStorageCapacityThreshold("Alert", ManagementServer.class, Float.class, "cluster.localStorage.capacity.notificationthreshold", "0.75", "Percentage (as a value between 0 and 1) of local storage utilization above which alerts will be sent about low local storage available.", null),
StorageAllocatedCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "pool.storage.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of allocated storage utilization above which allocators will disable using the pool for low allocated storage available.", null, ConfigurationParameterScope.zone.toString()),
StorageCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "pool.storage.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of storage utilization above which allocators will disable using the pool for low storage available.", null, ConfigurationParameterScope.zone.toString()),
CPUCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "cluster.cpu.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of cpu utilization above which allocators will disable using the cluster for low cpu available. Keep the corresponding notification threshold lower than this to be notified beforehand.", null, ConfigurationParameterScope.cluster.toString()),
MemoryCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "cluster.memory.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of memory utilization above which allocators will disable using the cluster for low memory available. Keep the corresponding notification threshold lower than this to be notified beforehand.", null, ConfigurationParameterScope.cluster.toString()),
StorageAllocatedCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "pool.storage.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of allocated storage utilization above which allocators will disable using the pool for low allocated storage available.", null, ConfigKey.Scope.Zone.toString()),
StorageCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "pool.storage.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of storage utilization above which allocators will disable using the pool for low storage available.", null, ConfigKey.Scope.Zone.toString()),
CPUCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "cluster.cpu.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of cpu utilization above which allocators will disable using the cluster for low cpu available. Keep the corresponding notification threshold lower than this to be notified beforehand.", null, ConfigKey.Scope.Cluster.toString()),
MemoryCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "cluster.memory.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of memory utilization above which allocators will disable using the cluster for low memory available. Keep the corresponding notification threshold lower than this to be notified beforehand.", null, ConfigKey.Scope.Cluster.toString()),
// Storage
StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null, ConfigurationParameterScope.zone.toString()),
StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null, ConfigKey.Scope.Zone.toString()),
StorageStatsInterval("Storage", ManagementServer.class, String.class, "storage.stats.interval", "60000", "The interval (in milliseconds) when storage stats (per host) are retrieved from agents.", null),
MaxVolumeSize("Storage", ManagementServer.class, Integer.class, "storage.max.volume.size", "2000", "The maximum size for a volume (in GB).", null),
StorageCacheReplacementLRUTimeInterval("Storage", ManagementServer.class, Integer.class, "storage.cache.replacement.lru.interval", "30", "time interval for unused data on cache storage (in days).", null),
@ -96,13 +93,10 @@ public enum Config {
GuestVlanBits("Network", ManagementServer.class, Integer.class, "guest.vlan.bits", "12", "The number of bits to reserve for the VLAN identifier in the guest subnet.", null),
//MulticastThrottlingRate("Network", ManagementServer.class, Integer.class, "multicast.throttling.rate", "10", "Default multicast rate in megabits per second allowed.", null),
NetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in network.", null, ConfigurationParameterScope.zone.toString()),
GuestDomainSuffix("Network", AgentManager.class, String.class, "guest.domain.suffix", "cloud.internal", "Default domain name for vms inside virtualized networks fronted by router", null, ConfigurationParameterScope.zone.toString()),
DirectNetworkNoDefaultRoute("Network", ManagementServer.class, Boolean.class, "direct.network.no.default.route", "false", "Direct Network Dhcp Server should not send a default route", "true/false"),
OvsTunnelNetwork("Network", ManagementServer.class, Boolean.class, "sdn.ovs.controller", "false", "Enable/Disable Open vSwitch SDN controller for L2-in-L3 overlay networks", null),
OvsTunnelNetworkDefaultLabel("Network", ManagementServer.class, String.class, "sdn.ovs.controller.default.label", "cloud-public", "Default network label to be used when fetching interface for GRE endpoints", null),
VmNetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "vm.network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in User vm's default network.", null),
NetworkLockTimeout("Network", ManagementServer.class, Integer.class, "network.lock.timeout", "600", "Lock wait timeout (seconds) while implementing network", null),
SecurityGroupWorkCleanupInterval("Network", ManagementServer.class, Integer.class, "network.securitygroups.work.cleanup.interval", "120", "Time interval (seconds) in which finished work is cleaned up from the work table", null),
SecurityGroupWorkerThreads("Network", ManagementServer.class, Integer.class, "network.securitygroups.workers.pool.size", "50", "Number of worker threads processing the security group update work queue", null),
@ -115,7 +109,6 @@ public enum Config {
//VPN
RemoteAccessVpnPskLength("Network", AgentManager.class, Integer.class, "remote.access.vpn.psk.length", "24", "The length of the ipsec preshared key (minimum 8, maximum 256)", null),
RemoteAccessVpnClientIpRange("Network", AgentManager.class, String.class, "remote.access.vpn.client.iprange", "10.1.2.1-10.1.2.8", "The range of ips to be allocated to remote access vpn clients. The first ip in the range is used by the VPN server", null, ConfigurationParameterScope.account.toString()),
RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null),
Site2SiteVpnConnectionPerVpnGatewayLimit("Network", ManagementServer.class, Integer.class, "site2site.vpn.vpngateway.connection.limit", "4", "The maximum number of VPN connection per VPN gateway", null),
Site2SiteVpnSubnetsPerCustomerGatewayLimit("Network", ManagementServer.class, Integer.class, "site2site.vpn.customergateway.subnets.limit", "10", "The maximum number of subnets per customer gateway", null),
@ -151,7 +144,6 @@ public enum Config {
JobCancelThresholdMinutes("Advanced", ManagementServer.class, String.class, "job.cancel.threshold.minutes", "60", "Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", null),
EventPurgeInterval("Advanced", ManagementServer.class, Integer.class, "event.purge.interval", "86400", "The interval (in seconds) to wait before running the event purge thread", null),
AccountCleanupInterval("Advanced", ManagementServer.class, Integer.class, "account.cleanup.interval", "86400", "The interval (in seconds) between cleanup for removed accounts", null),
AllowPublicUserTemplates("Advanced", ManagementServer.class, Integer.class, "allow.public.user.templates", "true", "If false, users will not be able to create public templates.", null, ConfigurationParameterScope.account.toString()),
InstanceName("Advanced", AgentManager.class, String.class, "instance.name", "VM", "Name of the deployment instance.", "instanceName"),
ExpungeDelay("Advanced", UserVmManager.class, Integer.class, "expunge.delay", "86400", "Determines how long (in seconds) to wait before actually expunging destroyed vm. The default value = the default value of expunge.interval", null),
ExpungeInterval("Advanced", UserVmManager.class, Integer.class, "expunge.interval", "86400", "The interval (in seconds) to wait before running the expunge thread.", null),
@ -164,27 +156,18 @@ public enum Config {
IntegrationAPIPort("Advanced", ManagementServer.class, Integer.class, "integration.api.port", null, "Defaul API port", null),
InvestigateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "investigate.retry.interval", "60", "Time (in seconds) between VM pings when agent is disconnected", null),
MigrateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "migrate.retry.interval", "120", "Time (in seconds) between migration retries", null),
ClusterDeltaSyncInterval("Advanced", AgentManager.class, Integer.class, "sync.interval", "60", "Cluster Delta sync interval in seconds", null),
RouterCpuMHz("Advanced", NetworkOrchestrationService.class, Integer.class, "router.cpu.mhz", String.valueOf(VpcVirtualNetworkApplianceManager.DEFAULT_ROUTER_CPU_MHZ), "Default CPU speed (MHz) for router VM.", null),
RestartRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "restart.retry.interval", "600", "Time (in seconds) between retries to restart a vm", null),
RouterStatsInterval("Advanced", NetworkOrchestrationService.class, Integer.class, "router.stats.interval", "300", "Interval (in seconds) to report router statistics.", null),
ExternalNetworkStatsInterval("Advanced", NetworkOrchestrationService.class, Integer.class, "external.network.stats.interval", "300", "Interval (in seconds) to report external network statistics.", null),
RouterCheckInterval("Advanced", NetworkOrchestrationService.class, Integer.class, "router.check.interval", "30", "Interval (in seconds) to report redundant router status.", null),
RouterCheckPoolSize("Advanced", NetworkOrchestrationService.class, Integer.class, "router.check.poolsize", "10", "Numbers of threads using to check redundant router status.", null),
RouterTemplateXen("Advanced", NetworkOrchestrationService.class, String.class, "router.template.xen", "SystemVM Template (XenServer)", "Name of the default router template on Xenserver.", null, ConfigurationParameterScope.zone.toString()),
RouterTemplateKVM("Advanced", NetworkOrchestrationService.class, String.class, "router.template.kvm", "SystemVM Template (KVM)", "Name of the default router template on KVM.", null, ConfigurationParameterScope.zone.toString()),
RouterTemplateVmware("Advanced", NetworkOrchestrationService.class, String.class, "router.template.vmware", "SystemVM Template (vSphere)", "Name of the default router template on Vmware.", null, ConfigurationParameterScope.zone.toString()),
RouterTemplateHyperv("Advanced", NetworkOrchestrationService.class, String.class, "router.template.hyperv", "SystemVM Template (HyperV)", "Name of the default router template on Hyperv.", null, ConfigurationParameterScope.zone.toString()),
RouterTemplateLXC("Advanced", NetworkOrchestrationService.class, String.class, "router.template.lxc", "SystemVM Template (LXC)", "Name of the default router template on LXC.", null, ConfigurationParameterScope.zone.toString()),
RouterExtraPublicNics("Advanced", NetworkOrchestrationService.class, Integer.class, "router.extra.public.nics", "2", "specify extra public nics used for virtual router(up to 5)", "0-5"),
StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null),
EnableDynamicallyScaleVm("Advanced", ManagementServer.class, Boolean.class, "enable.dynamic.scale.vm", "false", "Enables/Diables dynamically scaling a vm", null, ConfigurationParameterScope.zone.toString()),
ScaleRetry("Advanced", ManagementServer.class, Integer.class, "scale.retry", "2", "Number of times to retry scaling up the vm", null),
StopRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "stop.retry.interval", "600", "Time in seconds between retries to stop or destroy a vm" , null),
StorageCleanupInterval("Advanced", StorageManager.class, Integer.class, "storage.cleanup.interval", "86400", "The interval (in seconds) to wait before running the storage cleanup thread.", null),
StorageCleanupEnabled("Advanced", StorageManager.class, Boolean.class, "storage.cleanup.enabled", "true", "Enables/disables the storage cleanup thread.", null),
UpdateWait("Advanced", AgentManager.class, Integer.class, "update.wait", "600", "Time to wait (in seconds) before alerting on a updating agent", null),
Wait("Advanced", AgentManager.class, Integer.class, "wait", "1800", "Time in seconds to wait for control commands to return", null),
XapiWait("Advanced", AgentManager.class, Integer.class, "xapiwait", "600", "Time (in seconds) to wait for XAPI to return", null),
MigrateWait("Advanced", AgentManager.class, Integer.class, "migratewait", "3600", "Time (in seconds) to wait for VM migrate finish", null),
HAWorkers("Advanced", AgentManager.class, Integer.class, "ha.workers", "5", "Number of ha worker threads.", null),
@ -194,8 +177,6 @@ public enum Config {
SystemVMAutoReserveCapacity("Advanced", ManagementServer.class, Boolean.class, "system.vm.auto.reserve.capacity", "true", "Indicates whether or not to automatically reserver system VM standby capacity.", null),
SystemVMDefaultHypervisor("Advanced", ManagementServer.class, String.class, "system.vm.default.hypervisor", null, "Hypervisor type used to create system vm", null),
SystemVMRandomPassword("Advanced", ManagementServer.class, Boolean.class, "system.vm.random.password", "false", "Randomize system vm password the first time management server starts", null),
CPUOverprovisioningFactor("Advanced", ManagementServer.class, String.class, "cpu.overprovisioning.factor", "1", "Used for CPU overprovisioning calculation; available CPU will be (actualCpuCapacity * cpu.overprovisioning.factor)", null, ConfigurationParameterScope.cluster.toString()),
MemOverprovisioningFactor("Advanced", ManagementServer.class, String.class, "mem.overprovisioning.factor", "1", "Used for memory overprovisioning calculation", null, ConfigurationParameterScope.cluster.toString()),
LinkLocalIpNums("Advanced", ManagementServer.class, Integer.class, "linkLocalIp.nums", "10", "The number of link local ip that needed by domR(in power of 2)", null),
HypervisorList("Advanced", ManagementServer.class, String.class, "hypervisor.list", HypervisorType.Hyperv + "," + HypervisorType.KVM + "," + HypervisorType.XenServer + "," + HypervisorType.VMware + "," + HypervisorType.BareMetal + "," + HypervisorType.Ovm + "," + HypervisorType.LXC, "The list of hypervisors that this deployment will use.", "hypervisorList"),
ManagementHostIPAdr("Advanced", ManagementServer.class, String.class, "host", "localhost", "The ip address of management server", null),
@ -213,15 +194,6 @@ public enum Config {
AlertPurgeInterval("Advanced", ManagementServer.class, Integer.class, "alert.purge.interval", "86400", "The interval (in seconds) to wait before running the alert purge thread", null),
AlertPurgeDelay("Advanced", ManagementServer.class, Integer.class, "alert.purge.delay", "0", "Alerts older than specified number days will be purged. Set this value to 0 to never delete alerts", null),
HostReservationReleasePeriod("Advanced", ManagementServer.class, Integer.class, "host.reservation.release.period", "300000", "The interval in milliseconds between host reservation release checks", null),
UseSystemPublicIps("Advanced", ManagementServer.class, Boolean.class, "use.system.public.ips", "true",
"If true, when account has dedicated public ip range(s), once the ips dedicated to the account have been" +
" consumed ips will be acquired from the system pool",
null, ConfigurationParameterScope.account.toString()),
UseSystemGuestVlans("Advanced", ManagementServer.class, Boolean.class, "use.system.guest.vlans", "true",
"If true, when account has dedicated guest vlan range(s), once the vlans dedicated to the account have been" +
" consumed vlans will be allocated from the system pool",
null, ConfigurationParameterScope.account.toString()),
// LB HealthCheck Interval.
LBHealthCheck("Advanced", ManagementServer.class, String.class, "healthcheck.update.interval", "600",
"Time Interval to fetch the LB health check states (in sec)", null),
@ -235,7 +207,6 @@ public enum Config {
VmStatsInterval("Advanced", ManagementServer.class, Integer.class, "vm.stats.interval", "60000", "The interval (in milliseconds) when vm stats are retrieved from agents.", null),
VmDiskStatsInterval("Advanced", ManagementServer.class, Integer.class, "vm.disk.stats.interval", "0", "Interval (in seconds) to report vm disk statistics.", null),
VmTransitionWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.tranisition.wait.interval", "3600", "Time (in seconds) to wait before taking over a VM in transition state", null),
VmDestroyForcestop("Advanced", ManagementServer.class, Boolean.class, "vm.destroy.forcestop", "false", "On destroy, force-stop takes this value ", null),
VmDiskThrottlingIopsReadRate("Advanced", ManagementServer.class, Integer.class, "vm.disk.throttling.iops_read_rate", "0", "Default disk I/O read rate in requests per second allowed in User vm's disk.", null),
VmDiskThrottlingIopsWriteRate("Advanced", ManagementServer.class, Integer.class, "vm.disk.throttling.iops_write_rate", "0", "Default disk I/O writerate in requests per second allowed in User vm's disk.", null),
VmDiskThrottlingBytesReadRate("Advanced", ManagementServer.class, Integer.class, "vm.disk.throttling.bytes_read_rate", "0", "Default disk I/O read rate in bytes per second allowed in User vm's disk.", null),
@ -328,12 +299,6 @@ public enum Config {
EncryptionIV("Hidden", ManagementServer.class, String.class, "security.encryption.iv", null, "base64 encoded IV data", null),
RouterRamSize("Hidden", NetworkOrchestrationService.class, Integer.class, "router.ram.size", "128", "Default RAM for router VM (in MB).", null),
VmOpWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.op.wait.interval", "120", "Time (in seconds) to wait before checking if a previous operation has succeeded", null),
VmOpLockStateRetry("Advanced", ManagementServer.class, Integer.class, "vm.op.lock.state.retry", "5", "Times to retry locking the state of a VM for operations", "-1 means try forever"),
VmOpCleanupInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.interval", "86400", "Interval to run the thread that cleans up the vm operations (in seconds)", "Seconds"),
VmOpCleanupWait("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.wait", "3600", "Time (in seconds) to wait before cleanuping up any vm work items", "Seconds"),
VmOpCancelInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cancel.interval", "3600", "Time (in seconds) to wait before cancelling a operation", "Seconds"),
DefaultPageSize("Advanced", ManagementServer.class, Long.class, "default.page.size", "500", "Default page size for API list* commands", null),
TaskCleanupRetryInterval("Advanced", ManagementServer.class, Integer.class, "task.cleanup.retry.interval", "600", "Time (in seconds) to wait before retrying cleanup of tasks if the cleanup failed previously. 0 means to never retry.", "Seconds"),
@ -355,7 +320,6 @@ public enum Config {
//disabling lb as cluster sync does not work with distributed cluster
SubDomainNetworkAccess("Advanced", NetworkOrchestrationService.class, Boolean.class, "allow.subdomain.network.access", "true", "Allow subdomains to use networks dedicated to their parent domain(s)", null),
UseExternalDnsServers("Advanced", NetworkOrchestrationService.class, Boolean.class, "use.external.dns", "false", "Bypass internal dns, use external dns1 and dns2", null, ConfigurationParameterScope.zone.toString()),
EncodeApiResponse("Advanced", ManagementServer.class, Boolean.class, "encode.api.response", "false", "Do URL encoding for the api response, false by default", null),
DnsBasicZoneUpdates("Advanced", NetworkOrchestrationService.class, String.class, "network.dns.basiczone.updates", "all", "This parameter can take 2 values: all (default) and pod. It defines if DHCP/DNS requests have to be send to all dhcp servers in cloudstack, or only to the one in the same pod", "all,pod"),
@ -436,8 +400,7 @@ public enum Config {
CloudDnsName("Advanced", ManagementServer.class, String.class, "cloud.dns.name", null, "DNS name of the cloud for the GSLB service", null),
BlacklistedRoutes("Advanced", VpcManager.class, String.class, "blacklisted.routes", null, "Routes that are blacklisted, can not be used for Static Routes creation for the VPC Private Gateway",
"routes", ConfigurationParameterScope.zone.toString()),
"routes", ConfigKey.Scope.Zone.toString()),
InternalLbVmServiceOfferingId("Advanced", ManagementServer.class, String.class, "internallbvm.service.offering", null, "Uuid of the service offering used by internal lb vm; if NULL - default system internal lb offering will be used", null),
ExecuteInSequence("Advanced", ManagementServer.class, Boolean.class, "execute.in.sequence.hypervisor.commands", "false", "If set to true, StartCommand, StopCommand, CopyCommand will be synchronized on the agent side." +
" If set to false, these commands become asynchronous. Default value is false.", null),
@ -455,21 +418,13 @@ public enum Config {
private final String _range;
private final String _scope; // Parameter can be at different levels (Zone/cluster/pool/account), by default every parameter is at global
public static enum ConfigurationParameterScope {
global,
zone,
cluster,
storagepool,
account
}
private static final HashMap<String, List<Config>> _scopeLevelConfigsMap = new HashMap<String, List<Config>>();
static {
_scopeLevelConfigsMap.put(ConfigurationParameterScope.zone.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigurationParameterScope.cluster.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigurationParameterScope.storagepool.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigurationParameterScope.account.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigurationParameterScope.global.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigKey.Scope.Zone.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigKey.Scope.Cluster.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigKey.Scope.StoragePool.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigKey.Scope.Account.toString(), new ArrayList<Config>());
_scopeLevelConfigsMap.put(ConfigKey.Scope.Global.toString(), new ArrayList<Config>());
for (Config c : Config.values()) {
//Creating group of parameters per each level (zone/cluster/pool/account)
@ -517,7 +472,7 @@ public enum Config {
_defaultValue = defaultValue;
_description = description;
_range = range;
_scope = ConfigurationParameterScope.global.toString();
_scope = ConfigKey.Scope.Global.toString();
}
private Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range, String scope) {
_category = category;

View File

@ -71,6 +71,8 @@ import org.apache.cloudstack.config.Configuration;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigValue;
import org.apache.cloudstack.framework.config.ConfigurationVO;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.region.PortableIp;
@ -90,6 +92,7 @@ import org.apache.log4j.Logger;
import com.cloud.alert.AlertManager;
import com.cloud.api.ApiDBUtils;
import com.cloud.capacity.CapacityManager;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.AccountVlanMapVO;
@ -359,10 +362,10 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
private void weightBasedParametersForValidation() {
weightBasedParametersForValidation = new HashSet<String>();
weightBasedParametersForValidation.add(Config.CPUCapacityThreshold.key());
weightBasedParametersForValidation.add(Config.StorageAllocatedCapacityThreshold.key());
weightBasedParametersForValidation.add(Config.StorageCapacityThreshold.key());
weightBasedParametersForValidation.add(Config.MemoryCapacityThreshold.key());
weightBasedParametersForValidation.add(AlertManager.CPUCapacityThreshold.key());
weightBasedParametersForValidation.add(AlertManager.StorageAllocatedCapacityThreshold.key());
weightBasedParametersForValidation.add(AlertManager.StorageCapacityThreshold.key());
weightBasedParametersForValidation.add(AlertManager.MemoryCapacityThreshold.key());
weightBasedParametersForValidation.add(Config.PublicIpCapacityThreshold.key());
weightBasedParametersForValidation.add(Config.PrivateIpCapacityThreshold.key());
weightBasedParametersForValidation.add(Config.SecondaryStorageCapacityThreshold.key());
@ -381,8 +384,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
private void overProvisioningFactorsForValidation() {
overprovisioningFactorsForValidation = new HashSet<String>();
overprovisioningFactorsForValidation.add(Config.MemOverprovisioningFactor.key());
overprovisioningFactorsForValidation.add(Config.CPUOverprovisioningFactor.key());
overprovisioningFactorsForValidation.add(CapacityManager.MemOverprovisioningFactor.key());
overprovisioningFactorsForValidation.add(CapacityManager.CpuOverprovisioningFactor.key());
overprovisioningFactorsForValidation.add(Config.StorageOverprovisioningFactor.key());
}
@ -444,9 +447,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
// if scope is mentioned as global or not mentioned then it is normal
// global parameter updation
if (scope != null && !scope.isEmpty()
&& !Config.ConfigurationParameterScope.global.toString().equalsIgnoreCase(scope)) {
switch (Config.ConfigurationParameterScope.valueOf(scope)) {
case zone:
&& !ConfigKey.Scope.Global.toString().equalsIgnoreCase(scope)) {
switch (ConfigKey.Scope.valueOf(scope)) {
case Zone:
DataCenterVO zone = _zoneDao.findById(resourceId);
if (zone == null) {
throw new InvalidParameterValueException("unable to find zone by id " + resourceId);
@ -460,7 +463,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
_dcDetailsDao.update(dcDetailVO.getId(), dcDetailVO);
}
break;
case cluster:
case Cluster:
ClusterVO cluster = _clusterDao.findById(resourceId);
if (cluster == null) {
throw new InvalidParameterValueException("unable to find cluster by id " + resourceId);
@ -475,7 +478,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
}
break;
case storagepool:
case StoragePool:
StoragePoolVO pool = _storagePoolDao.findById(resourceId);
if (pool == null) {
throw new InvalidParameterValueException("unable to find storage pool by id " + resourceId);
@ -491,7 +494,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
}
break;
case account:
case Account:
AccountVO account = _accountDao.findById(resourceId);
if (account == null) {
throw new InvalidParameterValueException("unable to find account by id " + resourceId);
@ -655,22 +658,22 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
int paramCountCheck = 0;
if (zoneId != null) {
scope = Config.ConfigurationParameterScope.zone.toString();
scope = ConfigKey.Scope.Zone.toString();
id = zoneId;
paramCountCheck++;
}
if (clusterId != null) {
scope = Config.ConfigurationParameterScope.cluster.toString();
scope = ConfigKey.Scope.Cluster.toString();
id = clusterId;
paramCountCheck++;
}
if (accountId != null) {
scope = Config.ConfigurationParameterScope.account.toString();
scope = ConfigKey.Scope.Account.toString();
id = accountId;
paramCountCheck++;
}
if (storagepoolId != null) {
scope = Config.ConfigurationParameterScope.storagepool.toString();
scope = ConfigKey.Scope.StoragePool.toString();
id = storagepoolId;
paramCountCheck++;
}
@ -4624,6 +4627,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
}
}
@InjectConfig(key = NetworkOrchestrationService.NetworkThrottlingRateCK)
ConfigValue<Integer> _networkThrottlingRate;
@Override
public Integer getNetworkOfferingNetworkRate(long networkOfferingId, Long dataCenterId) {
@ -4637,8 +4643,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
if (no.getRateMbps() != null) {
networkRate = no.getRateMbps();
} else {
networkRate = Integer.parseInt(_configServer.getConfigValue(Config.NetworkThrottlingRate.key(),
Config.ConfigurationParameterScope.zone.toString(), dataCenterId));
networkRate = _networkThrottlingRate.valueIn(dataCenterId);
}
// networkRate is unsigned int in netowrkOfferings table, and can't be
@ -4761,8 +4766,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
// for domain router service offering, get network rate from
if (offering.getSystemVmType() != null
&& offering.getSystemVmType().equalsIgnoreCase(VirtualMachine.Type.DomainRouter.toString())) {
networkRate = Integer.parseInt(_configServer.getConfigValue(Config.NetworkThrottlingRate.key(),
Config.ConfigurationParameterScope.zone.toString(), dataCenterId));
networkRate = _networkThrottlingRate.valueIn(dataCenterId);
} else {
networkRate = Integer.parseInt(_configDao.getValue(Config.VmNetworkThrottlingRate.key()));
}

View File

@ -21,18 +21,21 @@ import java.util.Map;
import javax.inject.Inject;
import org.apache.cloudstack.framework.config.ConfigValue;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.configuration.Config;
import com.cloud.offering.ServiceOffering;
import com.cloud.server.ConfigurationServer;
import com.cloud.storage.dao.VMTemplateDetailsDao;
import com.cloud.utils.Pair;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.InjectConfig;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
@ -48,6 +51,9 @@ public abstract class HypervisorGuruBase extends AdapterBase implements Hypervis
@Inject NicSecondaryIpDao _nicSecIpDao;
@Inject ConfigurationServer _configServer;
@InjectConfig(key = UserVmManager.EnableDynamicallyScaleVmCK)
ConfigValue<Boolean> _enableDynamicallyScaleVm;
protected HypervisorGuruBase() {
super();
}
@ -124,7 +130,7 @@ public abstract class HypervisorGuruBase extends AdapterBase implements Hypervis
// Workaround to make sure the TO has the UUID we need for Niciri integration
VMInstanceVO vmInstance = _virtualMachineDao.findById(to.getId());
// check if XStools/VMWare tools are present in the VM and dynamic scaling feature is enabled (per zone/global)
Boolean isDynamicallyScalable = vmInstance.isDynamicallyScalable() && Boolean.parseBoolean(_configServer.getConfigValue(Config.EnableDynamicallyScaleVm.key(), Config.ConfigurationParameterScope.zone.toString(), vm.getDataCenterId()));
Boolean isDynamicallyScalable = vmInstance.isDynamicallyScalable() && _enableDynamicallyScaleVm.valueIn(vm.getDataCenterId());
to.setEnableDynamicallyScaleVm(isDynamicallyScalable);
to.setUuid(vmInstance.getUuid());

View File

@ -34,6 +34,9 @@ import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigValue;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpDao;
@ -43,7 +46,6 @@ import org.apache.cloudstack.region.Region;
import com.cloud.agent.AgentManager;
import com.cloud.alert.AlertManager;
import com.cloud.api.ApiDBUtils;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.AccountVlanMapVO;
@ -123,7 +125,6 @@ import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.offerings.dao.NetworkOfferingDetailsDao;
import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
import com.cloud.org.Grouping;
import com.cloud.server.ConfigurationServer;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.ResourceLimitService;
@ -133,6 +134,7 @@ import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.Journal;
import com.cloud.utils.Pair;
import com.cloud.utils.component.InjectConfig;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
@ -158,9 +160,12 @@ import com.cloud.vm.dao.NicSecondaryIpDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
public class IpAddressManagerImpl extends ManagerBase implements IpAddressManager {
public class IpAddressManagerImpl extends ManagerBase implements IpAddressManager, Configurable {
private static final Logger s_logger = Logger.getLogger(IpAddressManagerImpl.class);
@InjectConfig(key = UseSystemPublicIpsCK)
ConfigValue<Boolean> _useSystemPublicIps;
@Inject
NetworkOrchestrationService _networkMgr = null;
@Inject
@ -206,8 +211,6 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@Inject
NetworkOfferingDetailsDao _ntwkOffDetailsDao;
@Inject
ConfigurationServer _configServer;
@Inject
AccountGuestVlanMapDao _accountGuestVlanMapDao;
@Inject
DataCenterVnetDao _datacenterVnetDao;
@ -724,9 +727,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
// If all the dedicated IPs of the owner are in use fetch an IP from the system pool
if (addrs.size() == 0 && fetchFromDedicatedRange) {
// Verify if account is allowed to acquire IPs from the system
boolean useSystemIps = Boolean.parseBoolean(_configServer.getConfigValue(Config.UseSystemPublicIps.key(),
Config.ConfigurationParameterScope.account.toString(),
owner.getId()));
boolean useSystemIps = _useSystemPublicIps.valueIn(owner.getId());
if (useSystemIps && nonDedicatedVlanDbIds != null && !nonDedicatedVlanDbIds.isEmpty()) {
fetchFromDedicatedRange = false;
sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray());
@ -1917,4 +1918,14 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
ipaddr = acquireGuestIpAddress(network, requestedIp);
return ipaddr;
}
@Override
public String getConfigComponentName() {
return IpAddressManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {UseSystemPublicIps};
}
}

View File

@ -205,7 +205,6 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel {
SearchBuilder<NicVO> NicForTrafficTypeSearch;
private String _networkDomain;
private boolean _allowSubdomainNetworkAccess;
private Map<String, String> _configs;
@ -969,11 +968,6 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel {
return networkDomain;
}
@Override
public String getGlobalGuestDomainSuffix() {
return _networkDomain;
}
@Override
public String getStartIpAddress(long networkId) {
List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(networkId);
@ -1596,11 +1590,6 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel {
return _networksDao.listByVpc(vpcId);
}
@Override
public String getDefaultNetworkDomain(long zoneId) {
return _configServer.getConfigValue(Config.GuestDomainSuffix.key(), Config.ConfigurationParameterScope.zone.toString(), zoneId);
}
@Override
public List<Provider> getNtwkOffDistinctProviders(long ntkwOffId) {
List<String> providerNames = _ntwkOfferingSrvcDao.getDistinctProviders(ntkwOffId);
@ -1900,7 +1889,6 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel {
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_configs = _configDao.getConfiguration("Network", params);
_networkDomain = _configs.get(Config.GuestDomainSuffix.key());
_allowSubdomainNetworkAccess = Boolean.valueOf(_configs.get(Config.SubDomainNetworkAccess.key()));
_executeInSequenceNtwkElmtCmd = Boolean.valueOf(_configs.get(Config.ExecuteInSequenceNetworkElementCommands.key()));

View File

@ -293,6 +293,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
NetworkACLDao _networkACLDao;
@Inject
IpAddressManager _ipAddrMgr;
@Inject
EntityManager _entityMgr;
int _cidrLimit;
boolean _allowSubdomainNetworkAccess;
@ -1930,7 +1932,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
//perform below validation if the network is vpc network
if (network.getVpcId() != null && networkOfferingId != null) {
Vpc vpc = _vpcMgr.getVpc(network.getVpcId());
Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
_vpcMgr.validateNtwkOffForNtwkInVpc(networkId, networkOfferingId, null, null, vpc, null, _accountMgr.getAccount(network.getAccountId()), null);
}

View File

@ -25,9 +25,6 @@ import java.util.Set;
import javax.ejb.Local;
import javax.inject.Inject;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.vpc.*;
import com.cloud.network.vpc.dao.VpcGatewayDao;
import org.apache.log4j.Logger;
import com.cloud.dc.DataCenter;
@ -46,16 +43,26 @@ import com.cloud.network.Site2SiteVpnConnection;
import com.cloud.network.Site2SiteVpnGateway;
import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.Site2SiteVpnGatewayDao;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.network.router.VpcVirtualNetworkApplianceManager;
import com.cloud.network.vpc.NetworkACLItem;
import com.cloud.network.vpc.NetworkACLItemDao;
import com.cloud.network.vpc.NetworkACLItemVO;
import com.cloud.network.vpc.PrivateGateway;
import com.cloud.network.vpc.StaticRouteProfile;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcGateway;
import com.cloud.network.vpc.VpcManager;
import com.cloud.network.vpc.dao.VpcGatewayDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.Type;
import com.cloud.vm.VirtualMachineProfile;
@ -82,6 +89,8 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
VpcGatewayDao _vpcGatewayDao;
@Inject
NetworkACLItemDao _networkACLItemDao;
@Inject
EntityManager _entityMgr;
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@ -330,7 +339,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
List<DomainRouterVO> routers = _vpcRouterMgr.getVpcRouters(gateway.getVpcId());
if (routers == null || routers.isEmpty()) {
s_logger.debug(this.getName() + " element doesn't need to create Private gateway on the backend; VPC virtual " +
s_logger.debug(getName() + " element doesn't need to create Private gateway on the backend; VPC virtual " +
"router doesn't exist in the vpc id=" + gateway.getVpcId());
return true;
}
@ -365,7 +374,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
List<DomainRouterVO> routers = _vpcRouterMgr.getVpcRouters(gateway.getVpcId());
if (routers == null || routers.isEmpty()) {
s_logger.debug(this.getName() + " element doesn't need to delete Private gateway on the backend; VPC virtual " +
s_logger.debug(getName() + " element doesn't need to delete Private gateway on the backend; VPC virtual " +
"router doesn't exist in the vpc id=" + gateway.getVpcId());
return true;
}
@ -393,7 +402,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
if (canHandle) {
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
if (routers == null || routers.isEmpty()) {
s_logger.debug(this.getName() + " element doesn't need to associate ip addresses on the backend; VPC virtual " +
s_logger.debug(getName() + " element doesn't need to associate ip addresses on the backend; VPC virtual " +
"router doesn't exist in the network " + network.getId());
return true;
}
@ -479,7 +488,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
}
Long vpcId = ip.getVpcId();
Vpc vpc = _vpcMgr.getVpc(vpcId);
Vpc vpc = _entityMgr.findById(Vpc.class, vpcId);
if (!_ntwkModel.isProviderEnabledInZone(vpc.getZoneId(), Provider.VPCVirtualRouter.getName())) {
throw new ResourceUnavailableException("VPC provider is not enabled in zone " + vpc.getZoneId(),
@ -507,7 +516,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
}
Long vpcId = ip.getVpcId();
Vpc vpc = _vpcMgr.getVpc(vpcId);
Vpc vpc = _entityMgr.findById(Vpc.class, vpcId);
if (!_ntwkModel.isProviderEnabledInZone(vpc.getZoneId(), Provider.VPCVirtualRouter.getName())) {
throw new ResourceUnavailableException("VPC provider is not enabled in zone " + vpc.getZoneId(),

View File

@ -139,8 +139,8 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
// Get a vlan tag
int vlanTag;
if (config.getBroadcastUri() == null) {
String vnet = _dcDao.allocateVnet(zone.getId(), config.getPhysicalNetworkId(), config.getAccountId(),
context.getReservationId(), canUseSystemGuestVlan(config.getAccountId()));
String vnet = _dcDao.allocateVnet(zone.getId(), config.getPhysicalNetworkId(), config.getAccountId(), context.getReservationId(),
_useSystemGuestVlans.valueIn(config.getAccountId()));
try {
vlanTag = Integer.parseInt(vnet);

View File

@ -27,6 +27,9 @@ import org.apache.log4j.Logger;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigValue;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import com.cloud.configuration.Config;
@ -66,6 +69,7 @@ import com.cloud.server.ConfigurationServer;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.InjectConfig;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
@ -78,7 +82,7 @@ import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.NicDao;
@Local(value = NetworkGuru.class)
public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGuru, Configurable {
private static final Logger s_logger = Logger.getLogger(GuestNetworkGuru.class);
@Inject
protected NetworkOrchestrationService _networkMgr;
@ -104,6 +108,13 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
IpAddressManager _ipAddrMgr;
Random _rand = new Random(System.currentTimeMillis());
static final ConfigKey<Boolean> UseSystemGuestVlans = new ConfigKey<Boolean>("Advanced", Boolean.class, "use.system.guest.vlans", "true",
"If true, when account has dedicated guest vlan range(s), once the vlans dedicated to the account have been consumed vlans will be allocated from the system pool", false,
ConfigKey.Scope.Account);
@InjectConfig(key = "use.system.guest.vlans")
ConfigValue<Boolean> _useSystemGuestVlans;
private static final TrafficType[] _trafficTypes = {TrafficType.Guest};
// Currently set to anything except STT for the Nicira integration.
@ -159,11 +170,6 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
return _isolationMethods;
}
public boolean canUseSystemGuestVlan(long accountId) {
return Boolean.parseBoolean(_configServer.getConfigValue(Config.UseSystemGuestVlans.key(),
Config.ConfigurationParameterScope.account.toString(), accountId));
}
protected abstract boolean canHandle(NetworkOffering offering, final NetworkType networkType, PhysicalNetwork physicalNetwork);
@Override
@ -269,8 +275,7 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
protected void allocateVnet(Network network, NetworkVO implemented, long dcId,
long physicalNetworkId, String reservationId) throws InsufficientVirtualNetworkCapcityException {
if (network.getBroadcastUri() == null) {
String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), reservationId,
canUseSystemGuestVlan(network.getAccountId()));
String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), reservationId, _useSystemGuestVlans.valueIn(network.getAccountId()));
if (vnet == null) {
throw new InsufficientVirtualNetworkCapcityException("Unable to allocate vnet as a " +
"part of network " + network + " implement ", DataCenter.class, dcId);
@ -434,4 +439,14 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
networkProfile.setDns1(dc.getDns1());
networkProfile.setDns2(dc.getDns2());
}
@Override
public String getConfigComponentName() {
return GuestNetworkGuru.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {UseSystemGuestVlans};
}
}

View File

@ -16,6 +16,11 @@
// under the License.
package com.cloud.network.router;
import java.util.List;
import java.util.Map;
import org.apache.cloudstack.framework.config.ConfigKey;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
@ -30,20 +35,33 @@ import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.StaticNat;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.uservm.UserVm;
import com.cloud.utils.component.Manager;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicProfile;
import com.cloud.vm.VirtualMachineProfile;
import java.util.List;
import java.util.Map;
/**
* NetworkManager manages the network for the different end users.
*
*/
public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkApplianceService{
static final String RouterTemplateXenCK = "router.template.xen";
static final String RouterTemplateKvmCK = "router.template.kvm";
static final String RouterTemplateVmwareCK = "router.template.vmware";
static final String RouterTemplateHyperVCK = "router.template.hyperv";
static final String RouterTemplateLxcCK = "router.template.lxc";
static final ConfigKey<String> RouterTemplateXen = new ConfigKey<String>(String.class, RouterTemplateXenCK, "Advanced", "SystemVM Template (XenServer)",
"Name of the default router template on Xenserver.", true, ConfigKey.Scope.Zone, null);
static final ConfigKey<String> RouterTemplateKvm = new ConfigKey<String>(String.class, RouterTemplateKvmCK, "Advanced", "SystemVM Template (KVM)",
"Name of the default router template on KVM.", true, ConfigKey.Scope.Zone, null);
static final ConfigKey<String> RouterTemplateVmware = new ConfigKey<String>(String.class, RouterTemplateVmwareCK, "Advanced", "SystemVM Template (vSphere)",
"Name of the default router template on Vmware.", true, ConfigKey.Scope.Zone, null);
static final ConfigKey<String> RouterTemplateHyperV = new ConfigKey<String>(String.class, RouterTemplateHyperVCK, "Advanced", "SystemVM Template (HyperV)",
"Name of the default router template on Hyperv.", true, ConfigKey.Scope.Zone, null);
static final ConfigKey<String> RouterTemplateLxc = new ConfigKey<String>(String.class, RouterTemplateLxcCK, "Advanced", "SystemVM Template (LXC)",
"Name of the default router template on LXC.", true, ConfigKey.Scope.Zone, null);
public static final int DEFAULT_ROUTER_VM_RAMSIZE = 128; // 128M
public static final int DEFAULT_ROUTER_CPU_MHZ = 500; // 500 MHz
public static final boolean USE_POD_VLAN = false;

View File

@ -47,6 +47,9 @@ import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.context.ServerContexts;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.ConfigDepot;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.ConfigValue;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
@ -218,6 +221,7 @@ import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.StringUtils;
import com.cloud.utils.component.InjectConfig;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
@ -363,6 +367,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
NetworkService _networkSvc;
@Inject
IpAddressManager _ipAddrMgr;
@Inject
ConfigDepot _configDepot;
int _routerRamSize;
@ -635,9 +641,28 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
}
}
@InjectConfig(key = RouterTemplateXenCK)
ConfigValue<String> _routerTemplateXen;
@InjectConfig(key = RouterTemplateKvmCK)
ConfigValue<String> _routerTemplateKvm;
@InjectConfig(key = RouterTemplateVmwareCK)
ConfigValue<String> _routerTemplateVmware;
@InjectConfig(key = RouterTemplateHyperVCK)
ConfigValue<String> _routerTemplateHyperV;
@InjectConfig(key = RouterTemplateLxcCK)
ConfigValue<String> _routerTemplateLxc;
@InjectConfig(key = NetworkOrchestrationService.NetworkLockTimeoutCK)
ConfigValue<Integer> _networkLockTimeout;
@InjectConfig(key = "use.external.dns")
ConfigValue<Boolean> _useExternalDnsServers;
static final ConfigKey<Boolean> UseExternalDnsServers = new ConfigKey<Boolean>(Boolean.class, "use.external.dns", "Advanced", "false",
"Bypass internal dns, use external dns1 and dns2", true, ConfigKey.Scope.Zone, null);
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_useExternalDnsServers = _configDepot.get(UseExternalDnsServers);
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("RouterMonitor"));
_checkExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("RouterStatusMonitor"));
_networkStatsUpdateExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("NetworkStatsUpdater"));
@ -1426,7 +1451,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
InsufficientCapacityException, ResourceUnavailableException {
List<DomainRouterVO> routers = new ArrayList<DomainRouterVO>();
Network lock = _networkDao.acquireInLockTable(guestNetwork.getId(), _networkMgr.getNetworkLockTimeout());
Network lock = _networkDao.acquireInLockTable(guestNetwork.getId(), _networkLockTimeout.value());
if (lock == null) {
throw new ConcurrentOperationException("Unable to lock network " + guestNetwork.getId());
}
@ -1621,19 +1646,19 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
String templateName = null;
switch (hType) {
case XenServer:
templateName = _configServer.getConfigValue(Config.RouterTemplateXen.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateXen.valueIn(dest.getDataCenter().getId());
break;
case KVM:
templateName = _configServer.getConfigValue(Config.RouterTemplateKVM.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateKvm.valueIn(dest.getDataCenter().getId());
break;
case VMware:
templateName = _configServer.getConfigValue(Config.RouterTemplateVmware.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateVmware.valueIn(dest.getDataCenter().getId());
break;
case Hyperv:
templateName = _configServer.getConfigValue(Config.RouterTemplateHyperv.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateHyperV.valueIn(dest.getDataCenter().getId());
break;
case LXC:
templateName = _configServer.getConfigValue(Config.RouterTemplateLXC.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
templateName = _routerTemplateLxc.valueIn(dest.getDataCenter().getId());
break;
default: break;
}
@ -2151,10 +2176,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
boolean useExtDns = !dnsProvided;
/* For backward compatibility */
String use_external_dns = _configServer.getConfigValue(Config.UseExternalDnsServers.key(), Config.ConfigurationParameterScope.zone.toString(), dc.getId());
if (use_external_dns != null && use_external_dns.equals("true")) {
useExtDns = true;
}
useExtDns = _useExternalDnsServers.valueIn(dc.getId());
if (useExtDns) {
buf.append(" useextdns=true");

View File

@ -161,6 +161,8 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
VpcGatewayDao _vpcGatewayDao;
@Inject
NetworkACLItemDao _networkACLItemDao;
@Inject
EntityManager _entityMgr;
@Override
public List<DomainRouterVO> deployVirtualRouterInVpc(Vpc vpc, DeployDestination dest, Account owner,
@ -627,7 +629,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
//add vpc cidr/dns/networkdomain to the boot load args
StringBuilder buf = profile.getBootArgsBuilder();
Vpc vpc = _vpcMgr.getVpc(vr.getVpcId());
Vpc vpc = _entityMgr.findById(Vpc.class, vr.getVpcId());
buf.append(" vpccidr=" + vpc.getCidr() + " domain=" + vpc.getNetworkDomain());
buf.append(" dns1=").append(defaultDns1);
@ -829,7 +831,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
for (StaticRoute route : routes) {
VpcGateway gateway = gatewayMap.get(route.getVpcGatewayId());
if (gateway == null) {
gateway = _vpcMgr.getVpcGateway(route.getVpcGatewayId());
gateway = _entityMgr.findById(VpcGateway.class, route.getVpcGatewayId());
gatewayMap.put(gateway.getId(), gateway);
}
staticRouteProfiles.add(new StaticRouteProfile(route, gateway));

View File

@ -57,6 +57,7 @@ import com.cloud.network.rules.FirewallRule.FirewallRuleType;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.network.vpc.VpcManager;
import com.cloud.network.vpc.VpcService;
import com.cloud.offering.NetworkOffering;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.server.ResourceTag.TaggedResourceType;
@ -140,6 +141,8 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules
NicSecondaryIpDao _nicSecondaryDao;
@Inject
LoadBalancerVMMapDao _loadBalancerVMMapDao;
@Inject
VpcService _vpcService;
protected void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller, Boolean ignoreVmState) {
@ -506,7 +509,7 @@ public class RulesManagerImpl extends ManagerBase implements RulesManager, Rules
// associate portable IP to vpc, if network is part of VPC
if (network.getVpcId() != null) {
_vpcMgr.associateIPToVpc(ipId, network.getVpcId());
_vpcService.associateIPToVpc(ipId, network.getVpcId());
}
// associate portable IP with guest network

View File

@ -55,8 +55,6 @@ import com.cloud.utils.exception.CloudRuntimeException;
public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLManager{
private static final Logger s_logger = Logger.getLogger(NetworkACLManagerImpl.class);
@Inject
EntityManager _entityMgr;
@Inject
AccountManager _accountMgr;
@Inject
@ -81,6 +79,8 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
NetworkModel _ntwkModel;
@Inject
ConfigurationManager _configMgr;
@Inject
EntityManager _entityMgr;
@Override
public NetworkACL createNetworkACL(String name, String description, long vpcId) {
@ -105,7 +105,7 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
List<VpcGatewayVO> vpcGateways = _vpcGatewayDao.listByAclIdAndType(aclId, VpcGateway.Type.Private);
for (VpcGatewayVO vpcGateway : vpcGateways) {
PrivateGateway privateGateway = _vpcMgr.getVpcPrivateGateway(vpcGateway.getId());
PrivateGateway privateGateway = _entityMgr.findById(PrivateGateway.class, vpcGateway.getId());
if (!applyACLToPrivateGw(privateGateway)) {
aclApplyStatus = false;
s_logger.debug("failed to apply network acl item on private gateway " + privateGateway.getId() + "acl id " + aclId);

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