Merge branch '4.4' into dev

This commit is contained in:
Will Stevens 2014-07-28 14:29:17 -04:00
commit f3be111365
275 changed files with 25090 additions and 9347 deletions

View File

@ -1,4 +1,4 @@
Apache CloudStack Version 4.4.0
Apache CloudStack Version 4.4.1
# About Apache CloudStack

View File

@ -17,3 +17,5 @@
configureSimulator=com.cloud.api.commands.ConfigureSimulatorCmd;1
querySimulatorMock=com.cloud.api.commands.QuerySimulatorMockCmd;1
cleanupSimulatorMock=com.cloud.api.commands.CleanupSimulatorMockCmd;1

View File

@ -19,6 +19,7 @@ package com.cloud.network;
import java.util.Date;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;
@ -35,7 +36,7 @@ import com.cloud.utils.net.Ip;
* - DomainId = domain of the account owner.
* - Allocated = time it was allocated.
*/
public interface IpAddress extends ControlledEntity, Identity, InternalIdentity {
public interface IpAddress extends ControlledEntity, Identity, InternalIdentity, Displayable {
enum State {
Allocating, // The IP Address is being propagated to other network elements and is not ready for use yet.
Allocated, // The IP address is in used.
@ -85,6 +86,7 @@ public interface IpAddress extends ControlledEntity, Identity, InternalIdentity
Long getNetworkId();
@Override
boolean isDisplay();
public Date getRemoved();

View File

@ -90,6 +90,8 @@ public interface NetworkModel {
boolean areServicesSupportedByNetworkOffering(long networkOfferingId, Service... services);
Network getNetworkWithSGWithFreeIPs(Long zoneId);
Network getNetworkWithSecurityGroupEnabled(Long zoneId);
String getIpOfNetworkElementInVirtualNetwork(long accountId, long dataCenterId);
@ -273,4 +275,4 @@ public interface NetworkModel {
boolean isNetworkReadyForGc(long networkId);
boolean getNetworkEgressDefaultPolicy(Long networkId);
}
}

View File

@ -17,10 +17,11 @@
package com.cloud.network;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;
public interface RemoteAccessVpn extends ControlledEntity, InternalIdentity, Identity {
public interface RemoteAccessVpn extends ControlledEntity, InternalIdentity, Identity, Displayable {
enum State {
Added, Running, Removed
}
@ -39,5 +40,6 @@ public interface RemoteAccessVpn extends ControlledEntity, InternalIdentity, Ide
State getState();
@Override
boolean isDisplay();
}

View File

@ -19,9 +19,10 @@ package com.cloud.network;
import java.util.Date;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.InternalIdentity;
public interface Site2SiteVpnConnection extends ControlledEntity, InternalIdentity {
public interface Site2SiteVpnConnection extends ControlledEntity, InternalIdentity, Displayable {
enum State {
Pending, Connected, Disconnected, Error,
}
@ -43,5 +44,6 @@ public interface Site2SiteVpnConnection extends ControlledEntity, InternalIdenti
public boolean isPassive();
@Override
boolean isDisplay();
}

View File

@ -19,16 +19,18 @@ package com.cloud.network;
import java.util.Date;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;
public interface Site2SiteVpnGateway extends ControlledEntity, Identity, InternalIdentity {
public interface Site2SiteVpnGateway extends ControlledEntity, Identity, InternalIdentity, Displayable {
public long getAddrId();
public long getVpcId();
public Date getRemoved();
@Override
boolean isDisplay();
}

View File

@ -20,9 +20,10 @@ package com.cloud.network.as;
import java.util.Date;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.InternalIdentity;
public interface AutoScaleVmGroup extends ControlledEntity, InternalIdentity {
public interface AutoScaleVmGroup extends ControlledEntity, InternalIdentity, Displayable {
String State_New = "new";
String State_Revoke = "revoke";
@ -53,6 +54,7 @@ public interface AutoScaleVmGroup extends ControlledEntity, InternalIdentity {
String getUuid();
@Override
boolean isDisplay();
}

View File

@ -20,6 +20,7 @@ package com.cloud.network.as;
import java.util.List;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.InternalIdentity;
import com.cloud.utils.Pair;
@ -27,7 +28,7 @@ import com.cloud.utils.Pair;
/**
* AutoScaleVmProfile
*/
public interface AutoScaleVmProfile extends ControlledEntity, InternalIdentity {
public interface AutoScaleVmProfile extends ControlledEntity, InternalIdentity, Displayable {
@Override
public long getId();
@ -48,6 +49,7 @@ public interface AutoScaleVmProfile extends ControlledEntity, InternalIdentity {
public long getAutoScaleUserId();
@Override
boolean isDisplay();
}

View File

@ -16,12 +16,13 @@
// under the License.
package com.cloud.network.rules;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;
/**
*/
public interface HealthCheckPolicy extends InternalIdentity, Identity {
public interface HealthCheckPolicy extends InternalIdentity, Identity, Displayable {
public long getLoadBalancerId();
@ -39,9 +40,7 @@ public interface HealthCheckPolicy extends InternalIdentity, Identity {
public boolean isRevoke();
/**
* @return
*/
@Override
boolean isDisplay();
}

View File

@ -18,6 +18,7 @@ package com.cloud.network.rules;
import java.util.List;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;
@ -25,7 +26,7 @@ import com.cloud.utils.Pair;
/**
*/
public interface StickinessPolicy extends InternalIdentity, Identity {
public interface StickinessPolicy extends InternalIdentity, Identity, Displayable {
public long getLoadBalancerId();
@ -39,9 +40,7 @@ public interface StickinessPolicy extends InternalIdentity, Identity {
public List<Pair<String, String>> getParams(); /* get params in Map <string,String> format */
/**
* @return
*/
@Override
boolean isDisplay();
}

View File

@ -17,9 +17,10 @@
package com.cloud.network.vpc;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.InternalIdentity;
public interface NetworkACL extends InternalIdentity {
public interface NetworkACL extends InternalIdentity, Displayable {
public static final long DEFAULT_DENY = 1;
public static final long DEFAULT_ALLOW = 2;
@ -34,5 +35,6 @@ public interface NetworkACL extends InternalIdentity {
String getName();
@Override
boolean isDisplay();
}

View File

@ -18,9 +18,10 @@ package com.cloud.network.vpc;
import java.util.List;
import org.apache.cloudstack.api.Displayable;
import org.apache.cloudstack.api.InternalIdentity;
public interface NetworkACLItem extends InternalIdentity {
public interface NetworkACLItem extends InternalIdentity, Displayable {
String getUuid();
@ -73,6 +74,7 @@ public interface NetworkACLItem extends InternalIdentity {
*/
TrafficType getTrafficType();
@Override
boolean isDisplay();
}

View File

@ -46,6 +46,16 @@ public interface ResourceMetaDataService {
ResourceDetail getDetail(long resourceId, ResourceObjectType resourceType, String key);
/**
* List by key, value pair
* @param resourceType
* @param key
* @param value
* @param forDisplay
* @return
*/
List<? extends ResourceDetail> getDetails(ResourceObjectType resourceType, String key, String value, Boolean forDisplay);
Map<String, String> getDetailsMap(long resourceId, ResourceObjectType resourceType, Boolean forDisplay);
List<? extends ResourceDetail> getDetailsList(long resourceId, ResourceObjectType resourceType, Boolean forDisplay);

View File

@ -201,10 +201,19 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd {
}
}
@Deprecated
public Boolean getDisplayIp() {
return display;
}
@Override
public boolean isDisplay() {
if(display == null)
return true;
else
return display;
}
@Override
public long getEntityOwnerId() {
Account caller = CallContext.current().getCallingAccount();

View File

@ -184,10 +184,19 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd {
return ApiCommandJobType.AutoScaleVmGroup;
}
@Deprecated
public Boolean getDisplay() {
return display;
}
@Override
public boolean isDisplay() {
if(display == null)
return true;
else
return display;
}
@Override
public void create() throws ResourceAllocationException {
AutoScaleVmGroup result = _autoScaleService.createAutoScaleVmGroup(this);

View File

@ -131,10 +131,19 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd {
return templateId;
}
@Deprecated
public Boolean getDisplay() {
return display;
}
@Override
public boolean isDisplay() {
if(display == null)
return true;
else
return display;
}
public Map getCounterParamList() {
return counterParamList;
}

View File

@ -97,10 +97,19 @@ public class CreateLBHealthCheckPolicyCmd extends BaseAsyncCreateCmd {
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
@Deprecated
public Boolean getDisplay() {
return display;
}
@Override
public boolean isDisplay() {
if(display == null)
return true;
else
return display;
}
public Long getLbRuleId() {
return lbRuleId;
}

View File

@ -82,10 +82,19 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd {
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
@Deprecated
public Boolean getDisplay() {
return display;
}
@Override
public boolean isDisplay() {
if(display == null)
return true;
else
return display;
}
public Long getLbRuleId() {
return lbRuleId;
}

View File

@ -124,8 +124,13 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements L
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Boolean getDisplay() {
return display;
@Override
public boolean isDisplay() {
if (display != null) {
return display;
} else {
return true;
}
}
public String getAlgorithm() {
@ -309,7 +314,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements L
try {
LoadBalancer result =
_lbService.createPublicLoadBalancerRule(getXid(), getName(), getDescription(), getSourcePortStart(), getSourcePortEnd(), getDefaultPortStart(),
getDefaultPortEnd(), getSourceIpAddressId(), getProtocol(), getAlgorithm(), getNetworkId(), getEntityOwnerId(), getOpenFirewall(), getLbProtocol(), getDisplay());
getDefaultPortEnd(), getSourceIpAddressId(), getProtocol(), getAlgorithm(), getNetworkId(), getEntityOwnerId(), getOpenFirewall(), getLbProtocol(), isDisplay());
this.setEntityId(result.getId());
this.setEntityUuid(result.getUuid());
} catch (NetworkRuleConflictException e) {

View File

@ -103,10 +103,20 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd {
// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
@Deprecated
public Boolean getDisplay() {
return display;
}
@Override
public boolean isDisplay() {
if (display != null) {
return display;
} else {
return true;
}
}
public String getProtocol() {
String p = protocol.trim();
// Deal with ICMP(protocol number 1) specially because it need to be paired with icmp type and code

View File

@ -77,8 +77,13 @@ public class CreateNetworkACLListCmd extends BaseAsyncCreateCmd {
return vpcId;
}
public Boolean getDisplay() {
return display;
@Override
public boolean isDisplay() {
if (display != null) {
return display;
} else {
return true;
}
}
// ///////////////////////////////////////////////////
@ -92,7 +97,7 @@ public class CreateNetworkACLListCmd extends BaseAsyncCreateCmd {
@Override
public void create() {
NetworkACL result = _networkACLService.createNetworkACL(getName(), getDescription(), getVpcId(), getDisplay());
NetworkACL result = _networkACLService.createNetworkACL(getName(), getDescription(), getVpcId(), isDisplay());
setEntityId(result.getId());
setEntityUuid(result.getUuid());
}

View File

@ -88,8 +88,14 @@ public class UpdateNetworkACLItemCmd extends BaseAsyncCustomIdCmd {
// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
public Boolean getDisplay() {
return display;
@Override
public boolean isDisplay() {
if (display != null) {
return display;
} else {
return true;
}
}
public Long getId() {
@ -172,7 +178,7 @@ public class UpdateNetworkACLItemCmd extends BaseAsyncCustomIdCmd {
CallContext.current().setEventDetails("Rule Id: " + getId());
NetworkACLItem aclItem =
_networkACLService.updateNetworkACLItem(getId(), getProtocol(), getSourceCidrList(), getTrafficType(), getAction(), getNumber(), getSourcePortStart(),
getSourcePortEnd(), getIcmpCode(), getIcmpType(), this.getCustomId(), this.getDisplay());
getSourcePortEnd(), getIcmpCode(), getIcmpType(), this.getCustomId(), this.isDisplay());
if (aclItem == null) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network ACL Item");
}

View File

@ -44,6 +44,10 @@ public class ListResourceDetailsCmd extends BaseListProjectAndAccountResourcesCm
@Parameter(name = ApiConstants.KEY, type = CommandType.STRING, description = "list by key")
private String key;
@Parameter(name = ApiConstants.VALUE, type = CommandType.STRING, description = "list by key, value. Needs to be passed only along with key" ,
since = "4.4", authorized = { RoleType.Admin })
private String value;
@Parameter(name = ApiConstants.FOR_DISPLAY, type = CommandType.BOOLEAN, description = "if set to true, only details marked with display=true, are returned."
+ " False by default", since = "4.3", authorized = { RoleType.Admin })
private Boolean forDisplay;
@ -56,6 +60,10 @@ public class ListResourceDetailsCmd extends BaseListProjectAndAccountResourcesCm
return key;
}
public String getValue() {
return value;
}
@Override
public String getCommandName() {
return s_name;

View File

@ -25,6 +25,7 @@ import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ResponseObject.ResponseView;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.DiskOfferingResponse;
import org.apache.cloudstack.api.response.DomainResponse;
import org.apache.cloudstack.api.response.ProjectResponse;
import org.apache.cloudstack.api.response.VolumeResponse;
@ -89,6 +90,9 @@ public class UploadVolumeCmd extends BaseAsyncCmd {
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "Upload volume for the project")
private Long projectId;
@Parameter(name = ApiConstants.DISK_OFFERING_ID, required = false, type = CommandType.UUID, entityType = DiskOfferingResponse.class, description = "the ID of the disk offering. This must be a custom sized offering since during uploadVolume volume size is unknown.")
private Long diskOfferingId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@ -125,6 +129,10 @@ public class UploadVolumeCmd extends BaseAsyncCmd {
return imageStoreUuid;
}
public Long getDiskOfferingId() {
return diskOfferingId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////

View File

@ -145,7 +145,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
@Override
public void create() {
try {
RemoteAccessVpn vpn = _ravService.createRemoteAccessVpn(publicIpId, ipRange, getOpenFirewall(), getDisplay());
RemoteAccessVpn vpn = _ravService.createRemoteAccessVpn(publicIpId, ipRange, getOpenFirewall(), isDisplay());
if (vpn != null) {
setEntityId(vpn.getServerAddressId());
// find uuid for server ip address
@ -198,7 +198,11 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
return ip;
}
public Boolean getDisplay() {
return display;
@Override
public boolean isDisplay() {
if(display == null)
return true;
else
return display;
}
}

View File

@ -87,10 +87,20 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd {
return passive;
}
@Deprecated
public Boolean getDisplay() {
return display;
}
@Override
public boolean isDisplay() {
if (display != null) {
return display;
} else {
return true;
}
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////

View File

@ -16,25 +16,26 @@
// under the License.
package org.apache.cloudstack.api.command.user.vpn;
import org.apache.log4j.Logger;
import com.cloud.event.EventTypes;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.network.Site2SiteVpnGateway;
import com.cloud.network.vpc.Vpc;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.BaseAsyncCreateCmd;
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 com.cloud.event.EventTypes;
import com.cloud.network.Site2SiteVpnGateway;
import com.cloud.network.vpc.Vpc;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
@APICommand(name = "createVpnGateway", description = "Creates site to site vpn local gateway", responseObject = Site2SiteVpnGatewayResponse.class, entityType = {Site2SiteVpnGateway.class},
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class CreateVpnGatewayCmd extends BaseAsyncCmd {
public class CreateVpnGatewayCmd extends BaseAsyncCreateCmd {
public static final Logger s_logger = Logger.getLogger(CreateVpnGatewayCmd.class.getName());
private static final String s_name = "createvpngatewayresponse";
@ -60,10 +61,20 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd {
return vpcId;
}
@Deprecated
public Boolean getDisplay() {
return display;
}
@Override
public boolean isDisplay() {
if (display != null) {
return display;
} else {
return true;
}
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@ -91,8 +102,8 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd {
@Override
public void execute() {
Site2SiteVpnGateway result;
result = _s2sVpnService.createVpnGateway(this);
CallContext.current().setEventDetails("VPN gateway Id: " + getEntityId());
Site2SiteVpnGateway result = _s2sVpnService.getVpnGateway(getEntityId());
if (result != null) {
Site2SiteVpnGatewayResponse response = _responseGenerator.createSite2SiteVpnGatewayResponse(result);
response.setResponseName(getCommandName());
@ -111,4 +122,15 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd {
public Long getSyncObjId() {
return getVpcId();
}
@Override
public void create() throws ResourceAllocationException {
Site2SiteVpnGateway result = _s2sVpnService.createVpnGateway(this);
if (result != null) {
setEntityId(result.getId());
setEntityUuid(result.getUuid());
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create VPN gateway");
}
}
}

View File

@ -620,6 +620,8 @@ deleteStratoshereSsp=1
#### host simulator commands
configureSimulator=1
querySimulatorMock=1
cleanupSimulatorMock=1
#### api discovery commands

View File

@ -75,6 +75,7 @@
<property name="orderConfigDefault"
value="FirstFitPlanner,UserDispersingPlanner,UserConcentratedPodPlanner,ImplicitDedicationPlanner,BareMetalPlanner" />
<property name="excludeKey" value="deployment.planners.exclude" />
<property name="excludeDefault" value="SkipHeuresticsPlanner" />
</bean>
<bean id="haPlannersRegistry"
@ -89,6 +90,8 @@
<bean id="hostAllocatorsRegistry"
class="org.apache.cloudstack.spring.lifecycle.registry.ExtensionRegistry">
<property name="orderConfigKey" value="host.allocators.order" />
<property name="orderConfigDefault" value="FirstFitRouting" />
<property name="excludeKey" value="host.allocators.exclude" />
<property name="excludeDefault"
value="RandomAllocator,TestingAllocator,FirstFitAllocator,RecreateHostAllocator" />

View File

@ -30,7 +30,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.log4j.Logger;
@ -107,7 +106,6 @@ public abstract class AgentAttache {
protected Status _status = Status.Connecting;
protected boolean _maintenance;
protected long _nextSequence;
protected AtomicInteger _outstandingTaskCount;
protected AgentManagerImpl _agentMgr;
@ -130,7 +128,6 @@ public abstract class AgentAttache {
_requests = new LinkedList<Request>();
_agentMgr = agentMgr;
_nextSequence = new Long(s_rand.nextInt(Short.MAX_VALUE)) << 48;
_outstandingTaskCount = new AtomicInteger(0);
}
public synchronized long getNextSequence() {

View File

@ -162,6 +162,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
protected ExecutorService _executor;
protected ThreadPoolExecutor _connectExecutor;
protected ScheduledExecutorService _directAgentExecutor;
protected ScheduledExecutorService _cronJobExecutor;
protected ScheduledExecutorService _monitorExecutor;
private int _directAgentThreadCap;
@ -219,7 +220,10 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
_connection = new NioServer("AgentManager", Port.value(), Workers.value() + 10, this);
s_logger.info("Listening on " + Port.value() + " with " + Workers.value() + " workers");
// executes all agent commands other than cron and ping
_directAgentExecutor = new ScheduledThreadPoolExecutor(DirectAgentPoolSize.value(), new NamedThreadFactory("DirectAgent"));
// executes cron and ping agent commands
_cronJobExecutor = new ScheduledThreadPoolExecutor(DirectAgentPoolSize.value(), new NamedThreadFactory("DirectAgentCronJob"));
s_logger.debug("Created DirectAgentAttache pool with size: " + DirectAgentPoolSize.value());
_directAgentThreadCap = Math.round(DirectAgentPoolSize.value() * DirectAgentThreadCap.value()) + 1; // add 1 to always make the value > 0
@ -1451,6 +1455,10 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
return _directAgentExecutor;
}
public ScheduledExecutorService getCronJobPool() {
return _cronJobExecutor;
}
public int getDirectAgentThreadCap() {
return _directAgentThreadCap;
}

View File

@ -17,12 +17,13 @@
package com.cloud.agent.manager;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import com.cloud.agent.api.Answer;
@ -43,11 +44,16 @@ public class DirectAgentAttache extends AgentAttache {
List<ScheduledFuture<?>> _futures = new ArrayList<ScheduledFuture<?>>();
AgentManagerImpl _mgr;
long _seq = 0;
LinkedList<Task> tasks = new LinkedList<Task>();
AtomicInteger _outstandingTaskCount;
AtomicInteger _outstandingCronTaskCount;
public DirectAgentAttache(AgentManagerImpl agentMgr, long id, String name, ServerResource resource, boolean maintenance, AgentManagerImpl mgr) {
super(agentMgr, id, name, maintenance);
_resource = resource;
_mgr = mgr;
_outstandingTaskCount = new AtomicInteger(0);
_outstandingCronTaskCount = new AtomicInteger(0);
}
@Override
@ -90,15 +96,16 @@ public class DirectAgentAttache extends AgentAttache {
if (answers != null && answers[0] instanceof StartupAnswer) {
StartupAnswer startup = (StartupAnswer)answers[0];
int interval = startup.getPingInterval();
_futures.add(_agentMgr.getDirectAgentPool().scheduleAtFixedRate(new PingTask(), interval, interval, TimeUnit.SECONDS));
_futures.add(_agentMgr.getCronJobPool().scheduleAtFixedRate(new PingTask(), interval, interval, TimeUnit.SECONDS));
}
} else {
Command[] cmds = req.getCommands();
if (cmds.length > 0 && !(cmds[0] instanceof CronCommand)) {
_agentMgr.getDirectAgentPool().execute(new Task(req));
queueTask(new Task(req));
scheduleFromQueue();
} else {
CronCommand cmd = (CronCommand)cmds[0];
_futures.add(_agentMgr.getDirectAgentPool().scheduleAtFixedRate(new Task(req), cmd.getInterval(), cmd.getInterval(), TimeUnit.SECONDS));
_futures.add(_agentMgr.getCronJobPool().scheduleAtFixedRate(new CronTask(req), cmd.getInterval(), cmd.getInterval(), TimeUnit.SECONDS));
}
}
}
@ -109,7 +116,7 @@ public class DirectAgentAttache extends AgentAttache {
StartupAnswer startup = (StartupAnswer)answers[0];
int interval = startup.getPingInterval();
s_logger.info("StartupAnswer received " + startup.getHostId() + " Interval = " + interval);
_futures.add(_agentMgr.getDirectAgentPool().scheduleAtFixedRate(new PingTask(), interval, interval, TimeUnit.SECONDS));
_futures.add(_agentMgr.getCronJobPool().scheduleAtFixedRate(new PingTask(), interval, interval, TimeUnit.SECONDS));
}
}
@ -128,13 +135,26 @@ public class DirectAgentAttache extends AgentAttache {
}
}
private synchronized void queueTask(Task task) {
tasks.add(task);
}
private synchronized void scheduleFromQueue() {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Agent attache=" + _id + ", task queue size=" + tasks.size() + ", outstanding tasks=" + _outstandingTaskCount.get());
}
while (!tasks.isEmpty() && _outstandingTaskCount.get() < _agentMgr.getDirectAgentThreadCap()) {
_outstandingTaskCount.incrementAndGet();
_agentMgr.getDirectAgentPool().execute(tasks.remove());
}
}
protected class PingTask extends ManagedContextRunnable {
@Override
protected synchronized void runInContext() {
try {
if (_outstandingTaskCount.incrementAndGet() > _agentMgr.getDirectAgentThreadCap()) {
s_logger.warn("Task execution for direct attache(" + _id + ") has reached maximum outstanding limit(" + _agentMgr.getDirectAgentThreadCap() +
"), bailing out");
if (_outstandingCronTaskCount.incrementAndGet() >= _agentMgr.getDirectAgentThreadCap()) {
s_logger.warn("PingTask execution for direct attache(" + _id + ") has reached maximum outstanding limit(" + _agentMgr.getDirectAgentThreadCap() + "), bailing out");
return;
}
@ -162,15 +182,15 @@ public class DirectAgentAttache extends AgentAttache {
} catch (Exception e) {
s_logger.warn("Unable to complete the ping task", e);
} finally {
_outstandingTaskCount.decrementAndGet();
_outstandingCronTaskCount.decrementAndGet();
}
}
}
protected class Task extends ManagedContextRunnable {
protected class CronTask extends ManagedContextRunnable {
Request _req;
public Task(Request req) {
public CronTask(Request req) {
_req = req;
}
@ -194,9 +214,8 @@ public class DirectAgentAttache extends AgentAttache {
protected void runInContext() {
long seq = _req.getSequence();
try {
if (_outstandingTaskCount.incrementAndGet() > _agentMgr.getDirectAgentThreadCap()) {
s_logger.warn("Task execution for direct attache(" + _id + ") has reached maximum outstanding limit(" + _agentMgr.getDirectAgentThreadCap() +
"), bailing out");
if (_outstandingCronTaskCount.incrementAndGet() >= _agentMgr.getDirectAgentThreadCap()) {
s_logger.warn("CronTask execution for direct attache(" + _id + ") has reached maximum outstanding limit(" + _agentMgr.getDirectAgentThreadCap() + "), bailing out");
bailout();
return;
}
@ -243,9 +262,67 @@ public class DirectAgentAttache extends AgentAttache {
} catch (Exception e) {
s_logger.warn(log(seq, "Exception caught "), e);
} finally {
_outstandingTaskCount.decrementAndGet();
_outstandingCronTaskCount.decrementAndGet();
}
}
}
protected class Task extends ManagedContextRunnable {
Request _req;
public Task(Request req) {
_req = req;
}
@Override
protected void runInContext() {
long seq = _req.getSequence();
try {
ServerResource resource = _resource;
Command[] cmds = _req.getCommands();
boolean stopOnError = _req.stopOnError();
if (s_logger.isDebugEnabled()) {
s_logger.debug(log(seq, "Executing request"));
}
ArrayList<Answer> answers = new ArrayList<Answer>(cmds.length);
for (int i = 0; i < cmds.length; i++) {
Answer answer = null;
try {
if (resource != null) {
answer = resource.executeRequest(cmds[i]);
if (answer == null) {
s_logger.warn("Resource returned null answer!");
answer = new Answer(cmds[i], false, "Resource returned null answer");
}
} else {
answer = new Answer(cmds[i], false, "Agent is disconnected");
}
} catch (Exception e) {
s_logger.warn(log(seq, "Exception Caught while executing command"), e);
answer = new Answer(cmds[i], false, e.toString());
}
answers.add(answer);
if (!answer.getResult() && stopOnError) {
if (i < cmds.length - 1 && s_logger.isDebugEnabled()) {
s_logger.debug(log(seq, "Cancelling because one of the answers is false and it is stop on error."));
}
break;
}
}
Response resp = new Response(_req, answers.toArray(new Answer[answers.size()]));
if (s_logger.isDebugEnabled()) {
s_logger.debug(log(seq, "Response Received: "));
}
processAnswers(seq, resp);
} catch (Exception e) {
s_logger.warn(log(seq, "Exception caught "), e);
} finally {
_outstandingTaskCount.decrementAndGet();
scheduleFromQueue();
}
}
}
}

View File

@ -866,9 +866,11 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati
if (volumesForVm != null) {
for (VolumeVO volumeForVm : volumesForVm) {
VolumeInfo volumeInfo = volFactory.getVolume(volumeForVm.getId());
DataStore dataStore = dataStoreMgr.getDataStore(volumeForVm.getPoolId(), DataStoreRole.Primary);
volService.disconnectVolumeFromHost(volumeInfo, host, dataStore);
// pool id can be null for the VM's volumes in Allocated state
if (volumeForVm.getPoolId() != null) {
DataStore dataStore = dataStoreMgr.getDataStore(volumeForVm.getPoolId(), DataStoreRole.Primary);
volService.disconnectVolumeFromHost(volumeInfo, host, dataStore);
}
}
}
}

View File

@ -26,63 +26,50 @@ public class DatabaseAccessObject {
private static Logger s_logger = Logger.getLogger(DatabaseAccessObject.class);
public void dropKey(Connection conn, String tableName, String key, boolean isForeignKey) {
PreparedStatement pstmt = null;
try {
if (isForeignKey) {
pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP FOREIGN KEY " + key);
} else {
pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP KEY " + key);
}
public void dropKey(Connection conn, String tableName, String key, boolean isForeignKey)
{
String alter_sql_str;
if (isForeignKey) {
alter_sql_str = "ALTER TABLE " + tableName + " DROP FOREIGN KEY " + key;
} else {
alter_sql_str = "ALTER TABLE " + tableName + " DROP KEY " + key;
}
try(PreparedStatement pstmt = conn.prepareStatement(alter_sql_str);)
{
pstmt.executeUpdate();
s_logger.debug("Key " + key + " is dropped successfully from the table " + tableName);
} catch (SQLException e) {
s_logger.warn("Ignored SQL Exception when trying to drop " + (isForeignKey ? "foreign " : "") + "key " + key + " on table " + tableName, e);
} finally {
closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer dropping " + (isForeignKey ? "foreign " : "") + "key " + key
+ " on table " + tableName);
s_logger.warn("Ignored SQL Exception when trying to drop " + (isForeignKey ? "foreign " : "") + "key " + key + " on table " + tableName, e);
}
}
public void dropPrimaryKey(Connection conn, String tableName) {
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP PRIMARY KEY ");
try(PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP PRIMARY KEY ");) {
pstmt.executeUpdate();
s_logger.debug("Primary key is dropped successfully from the table " + tableName);
} catch (SQLException e) {
s_logger.warn("Ignored SQL Exception when trying to drop primary key on table " + tableName, e);
} finally {
closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer dropping primary key on table " + tableName);
}
}
public void dropColumn(Connection conn, String tableName, String columnName) {
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP COLUMN " + columnName);
try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP COLUMN " + columnName);){
pstmt.executeUpdate();
s_logger.debug("Column " + columnName + " is dropped successfully from the table " + tableName);
} catch (SQLException e) {
s_logger.warn("Unable to drop columns using query " + pstmt + " due to exception", e);
} finally {
closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement after dropping column " + columnName + " on table " + tableName);
s_logger.warn("Unable to drop column " + columnName + " due to exception", e);
}
}
public boolean columnExists(Connection conn, String tableName, String columnName) {
boolean columnExists = false;
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("SELECT " + columnName + " FROM " + tableName);
try (PreparedStatement pstmt = conn.prepareStatement("SELECT " + columnName + " FROM " + tableName);){
pstmt.executeQuery();
columnExists = true;
} catch (SQLException e) {
s_logger.warn("Field " + columnName + " doesn't exist in " + tableName, e);
} finally {
closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer checking if column " + columnName + " existed on table " + tableName);
}
return columnExists;
}

View File

@ -659,12 +659,12 @@ public class VMInstanceDaoImpl extends GenericDaoBase<VMInstanceVO, Long> implem
finalQuery.append(COUNT_VMS_BASED_ON_VGPU_TYPES1);
if (podId != null) {
finalQuery.append(" AND host.pod_id = ?");
finalQuery.append("AND host.pod_id = ? ");
resourceIdList.add(podId);
}
if (clusterId != null) {
finalQuery.append(" AND host.cluster_id = ?");
finalQuery.append("AND host.cluster_id = ? ");
resourceIdList.add(clusterId);
}
finalQuery.append(COUNT_VMS_BASED_ON_VGPU_TYPES2);

View File

@ -32,6 +32,15 @@ public interface ResourceDetailsDao<R extends ResourceDetail> extends GenericDao
*/
public R findDetail(long resourceId, String name);
/**
* Find details by key,value pair
* @param key
* @param value
* @param display
* @return
*/
public List<R> findDetails(String key, String value, Boolean display);
/**
* Removes all details for the resource specified
* @param resourceId

View File

@ -34,6 +34,7 @@ public abstract class ResourceDetailsDaoBase<R extends ResourceDetail> extends G
AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("resourceId", AllFieldsSearch.entity().getResourceId(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("name", AllFieldsSearch.entity().getName(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("value", AllFieldsSearch.entity().getValue(), SearchCriteria.Op.EQ);
// FIXME SnapshotDetailsVO doesn't have a display field
if (_allAttributes.containsKey("display")) {
AllFieldsSearch.and("display", AllFieldsSearch.entity().isDisplay(), SearchCriteria.Op.EQ);
@ -49,6 +50,25 @@ public abstract class ResourceDetailsDaoBase<R extends ResourceDetail> extends G
return findOneBy(sc);
}
public List<R> findDetails(String name, String value, Boolean display) {
SearchCriteria<R> sc = AllFieldsSearch.create();
if(display != null){
sc.setParameters("display", display);
}
if(name != null){
sc.setParameters("name", name);
}
if(value != null){
sc.setParameters("value", value);
}
List<R> results = search(sc, null);
return results;
}
public Map<String, String> listDetailsKeyPairs(long resourceId) {
SearchCriteria<R> sc = AllFieldsSearch.create();
sc.setParameters("resourceId", resourceId);

View File

@ -81,7 +81,7 @@ public class DefaultHostListener implements HypervisorHostListener {
}
StoragePoolVO poolVO = this.primaryStoreDao.findById(poolId);
poolVO.setUsedBytes(mspAnswer.getPoolInfo().getAvailableBytes());
poolVO.setUsedBytes(mspAnswer.getPoolInfo().getCapacityBytes() - mspAnswer.getPoolInfo().getAvailableBytes());
poolVO.setCapacityBytes(mspAnswer.getPoolInfo().getCapacityBytes());
primaryStoreDao.update(pool.getId(), poolVO);

View File

@ -105,8 +105,8 @@ public class EncryptionSecretKeyChanger {
PropertiesConfiguration backupDBProps = null;
System.out.println("Parsing db.properties file");
try {
dbProps.load(new FileInputStream(dbPropsFile));
try(FileInputStream db_prop_fstream = new FileInputStream(dbPropsFile);) {
dbProps.load(db_prop_fstream);
backupDBProps = new PropertiesConfiguration(dbPropsFile);
} catch (FileNotFoundException e) {
System.out.println("db.properties file not found while reading DB secret key" + e.getMessage());
@ -142,11 +142,10 @@ public class EncryptionSecretKeyChanger {
//db.properties updated successfully
if (encryptionType.equals("file")) {
//update key file with new MS key
try {
FileWriter fwriter = new FileWriter(keyFile);
BufferedWriter bwriter = new BufferedWriter(fwriter);
try (FileWriter fwriter = new FileWriter(keyFile);
BufferedWriter bwriter = new BufferedWriter(fwriter);)
{
bwriter.write(newMSKey);
bwriter.close();
} catch (IOException e) {
System.out.println("Failed to write new secret to file. Please update the file manually");
}
@ -180,11 +179,10 @@ public class EncryptionSecretKeyChanger {
}
if (encryptionType.equals("file")) {
//revert secret key in file
try {
FileWriter fwriter = new FileWriter(keyFile);
BufferedWriter bwriter = new BufferedWriter(fwriter);
try (FileWriter fwriter = new FileWriter(keyFile);
BufferedWriter bwriter = new BufferedWriter(fwriter);)
{
bwriter.write(oldMSKey);
bwriter.close();
} catch (IOException e) {
System.out.println("Failed to revert to old secret to file. Please update the file manually");
}

View File

@ -131,52 +131,44 @@ public class ScriptRunner {
} else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
String value = rs.getString(i);
print(value + "\t");
try (Statement statement = conn.createStatement();) {
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
println("");
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
try(ResultSet rs = statement.getResultSet();) {
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
Thread.yield();
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
int idx = line.indexOf("--");
if (idx != -1)

View File

@ -112,9 +112,6 @@ public class TransactionLegacy {
TransactionLegacy txn = tls.get();
if (check) {
assert txn != null : "No Transaction on stack. Did you mark the method with @DB?";
assert checkAnnotation(4, txn) : "Did you even read the guide to use Transaction...IOW...other people's code? Try method can't be private. What about @DB? hmmm... could that be it? " +
txn;
}
return txn;
}

View File

@ -214,12 +214,14 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase<AsyncJobJoinMapVO, Lo
List<Long> standaloneList = new ArrayList<Long>();
TransactionLegacy txn = TransactionLegacy.currentTxn();
String sql = "SELECT job_id FROM async_job_join_map WHERE join_job_id = ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
try {
PreparedStatement pstmt = txn.prepareStatement(sql);
try (PreparedStatement pstmt = txn.prepareStatement(sql);){
pstmt.setLong(1, joinedJobId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
standaloneList.add(rs.getLong(1));
try(ResultSet rs = pstmt.executeQuery();) {
while (rs.next()) {
standaloneList.add(rs.getLong(1));
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to execute " + sql, e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to execute " + sql, e);
@ -231,23 +233,26 @@ public class AsyncJobJoinMapDaoImpl extends GenericDaoBase<AsyncJobJoinMapVO, Lo
public List<Long> findJobsToWakeBetween(Date cutDate) {
List<Long> standaloneList = new ArrayList<Long>();
TransactionLegacy txn = TransactionLegacy.currentTxn();
try {
String sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
PreparedStatement pstmt = txn.prepareStatement(sql);
String sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
try (PreparedStatement pstmt = txn.prepareStatement(sql);){
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
standaloneList.add(rs.getLong(1));
try(ResultSet rs = pstmt.executeQuery();) {
while (rs.next()) {
standaloneList.add(rs.getLong(1));
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to handle SQL exception", e);
}
// update for next wake-up
sql = "UPDATE async_job_join_map SET next_wakeup=DATE_ADD(next_wakeup, INTERVAL wakeup_interval SECOND) WHERE next_wakeup < ? AND expiration > ?";
pstmt = txn.prepareStatement(sql);
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
pstmt.executeUpdate();
try(PreparedStatement update_pstmt = txn.prepareStatement(sql);) {
update_pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
update_pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
update_pstmt.executeUpdate();
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to handle SQL exception", e);
}
return standaloneList;
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to handle SQL exception", e);

View File

@ -302,7 +302,7 @@ namespace HypervResource
path = Utils.NormalizePath(path);
if (Directory.Exists(path))
{
string[] choices = choices = Directory.GetFiles(path, volInfo.uuid + ".vhd*");
string[] choices = Directory.GetFiles(path, volInfo.uuid + ".vhd*");
if (choices.Length != 1)
{
String errMsg = "Tried to guess file extension, but cannot find file corresponding to " +
@ -609,6 +609,7 @@ namespace HypervResource
public struct VolumeInfo
{
#pragma warning disable 0414
public long id;
public string type;
public string storagePoolType;
@ -618,6 +619,7 @@ namespace HypervResource
public string path;
long size;
string chainInfo;
#pragma warning restore 0414
public VolumeInfo(long id, string type, string poolType, String poolUuid, String name, String mountPoint, String path, long size, String chainInfo)
{
@ -635,10 +637,12 @@ namespace HypervResource
public class VmState
{
#pragma warning disable 0414
[JsonProperty("state")]
public String state;
[JsonProperty("host")]
String host;
#pragma warning restore 0414
public VmState() { }
public VmState(String vmState, String host)
{
@ -649,6 +653,7 @@ namespace HypervResource
public struct StoragePoolInfo
{
#pragma warning disable 0414
[JsonProperty("uuid")]
public String uuid;
[JsonProperty("host")]
@ -667,6 +672,7 @@ namespace HypervResource
long availableBytes;
[JsonProperty("details")]
Dictionary<String, String> details;
#pragma warning restore 0414
public StoragePoolInfo(String uuid, String host, String hostPath,
String localPath, string poolType, long capacityBytes,

View File

@ -1,4 +1,4 @@
// Licensed to the Apache Software Foundation (ASF) under one
// 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
@ -88,7 +88,7 @@ namespace HypervResource
{
IntPtr token = IntPtr.Zero;
bool isSuccess = LogonUser(cifsShareDetails.User, cifsShareDetails.Domain, cifsShareDetails.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
LogonUser(cifsShareDetails.User, cifsShareDetails.Domain, cifsShareDetails.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
using (WindowsImpersonationContext remoteIdentity = new WindowsIdentity(token).Impersonate())
{
String dest = "";

View File

@ -135,6 +135,9 @@
<Compile Include="ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_ShutdownComponent.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs">
<SubType>Component</SubType>
</Compile>
@ -181,8 +184,8 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="BeforeBuild" Condition="'$(BuildWithMono)' == 'true' ">
<RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" Condition="Exists('$(ProjectDir)$(BaseIntermediateOutputPath)')"/>
<RemoveDir Directories="$(ProjectDir)$(OutputPath)" Condition="Exists('$(ProjectDir)$(OutputPath)')"/>
<RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" Condition="Exists('$(ProjectDir)$(BaseIntermediateOutputPath)')" />
<RemoveDir Directories="$(ProjectDir)$(OutputPath)" Condition="Exists('$(ProjectDir)$(OutputPath)')" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -3977,7 +3977,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
if ((volumeObjectTO.getIopsWriteRate() != null) && (volumeObjectTO.getIopsWriteRate() > 0))
disk.setIopsWriteRate(volumeObjectTO.getIopsWriteRate());
if (volumeObjectTO.getCacheMode() != null)
disk.setCacheMode(DiskDef.diskCacheMode.valueOf(volumeObjectTO.getCacheMode().toString()));
disk.setCacheMode(DiskDef.diskCacheMode.valueOf(volumeObjectTO.getCacheMode().toString().toUpperCase()));
}
vm.getDevices().addDevice(disk);
}
@ -4128,7 +4128,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
diskdef.setIopsWriteRate(iopsWriteRate);
if (cacheMode != null) {
diskdef.setCacheMode(DiskDef.diskCacheMode.valueOf(cacheMode));
diskdef.setCacheMode(DiskDef.diskCacheMode.valueOf(cacheMode.toUpperCase()));
}
}

View File

@ -30,5 +30,10 @@
<bean id="SimulatorGuru" class="com.cloud.simulator.SimulatorGuru">
<property name="name" value="Simulator Guru"/>
</bean>
<bean id="SimulatorInvestigator" class="com.cloud.ha.SimulatorInvestigator">
<property name="name" value="Simulator Investigator"/>
</bean>
<bean id="SimulatorFencer" class="com.cloud.ha.SimulatorFencer">
<property name="name" value="Simulator Fencer"/>
</bean>
</beans>

View File

@ -289,11 +289,11 @@ public class MockStorageManagerImpl extends ManagerBase implements MockStorageMa
vm = _mockVMDao.findByVmName(vmName);
txn.commit();
if (vm == null) {
return new Answer(cmd, false, "can't vm :" + vmName);
return new Answer(cmd, false, "can't find vm :" + vmName);
}
} catch (Exception ex) {
txn.rollback();
throw new CloudRuntimeException("Error when attaching iso to vm " + vm.getName(), ex);
throw new CloudRuntimeException("Error when attaching iso to vm " + vmName, ex);
} finally {
txn.close();
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
@ -335,7 +335,7 @@ public class MockStorageManagerImpl extends ManagerBase implements MockStorageMa
if (storagePool == null) {
storagePool = new MockStoragePoolVO();
storagePool.setUuid(sf.getUuid());
storagePool.setMountPoint("/mnt/" + sf.getUuid() + File.separator);
storagePool.setMountPoint("/mnt/" + sf.getUuid());
Long size = DEFAULT_HOST_STORAGE_SIZE;
String path = sf.getPath();
@ -362,7 +362,7 @@ public class MockStorageManagerImpl extends ManagerBase implements MockStorageMa
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
txn.close();
}
return new ModifyStoragePoolAnswer(cmd, storagePool.getCapacity(), 0, new HashMap<String, TemplateProp>());
return new ModifyStoragePoolAnswer(cmd, storagePool.getCapacity(), storagePool.getCapacity(), new HashMap<String, TemplateProp>());
}
@Override
@ -376,7 +376,7 @@ public class MockStorageManagerImpl extends ManagerBase implements MockStorageMa
if (storagePool == null) {
storagePool = new MockStoragePoolVO();
storagePool.setUuid(sf.getUuid());
storagePool.setMountPoint("/mnt/" + sf.getUuid() + File.separator);
storagePool.setMountPoint("/mnt/" + sf.getUuid());
Long size = DEFAULT_HOST_STORAGE_SIZE;
String path = sf.getPath();
@ -514,8 +514,8 @@ public class MockStorageManagerImpl extends ManagerBase implements MockStorageMa
if (cmd.getVmName() != null) {
MockVm vm = _mockVMDao.findByVmName(cmd.getVmName());
vm.setState(State.Expunging);
if (vm != null) {
vm.setState(State.Expunging);
MockVMVO vmVo = _mockVMDao.createForUpdate(vm.getId());
_mockVMDao.update(vm.getId(), vmVo);
}
@ -945,7 +945,7 @@ public class MockStorageManagerImpl extends ManagerBase implements MockStorageMa
String uuid = UUID.randomUUID().toString();
storagePool = new MockStoragePoolVO();
storagePool.setUuid(uuid);
storagePool.setMountPoint("/mnt/" + uuid + File.separator);
storagePool.setMountPoint("/mnt/" + uuid);
storagePool.setCapacity(DEFAULT_HOST_STORAGE_SIZE);
storagePool.setHostGuid(hostGuid);
storagePool.setStorageType(StoragePoolType.Filesystem);
@ -964,7 +964,7 @@ public class MockStorageManagerImpl extends ManagerBase implements MockStorageMa
}
}
return new StoragePoolInfo(storagePool.getUuid(), host.getPrivateIpAddress(), storagePool.getMountPoint(), storagePool.getMountPoint(),
storagePool.getPoolType(), storagePool.getCapacity(), 0);
storagePool.getPoolType(), storagePool.getCapacity(), storagePool.getCapacity());
}
@Override
@ -1004,7 +1004,7 @@ public class MockStorageManagerImpl extends ManagerBase implements MockStorageMa
String uuid = UUID.randomUUID().toString();
storagePool = new MockStoragePoolVO();
storagePool.setUuid(uuid);
storagePool.setMountPoint("/mnt/" + uuid + File.separator);
storagePool.setMountPoint("/mnt/" + uuid);
storagePool.setCapacity(storageSize);
storagePool.setHostGuid(hostGuid);
storagePool.setStorageType(StoragePoolType.Filesystem);

View File

@ -27,6 +27,7 @@ import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.CleanupNetworkRulesCmd;
import com.cloud.agent.api.CreateVMSnapshotCommand;
import com.cloud.agent.api.DeleteVMSnapshotCommand;
import com.cloud.agent.api.FenceCommand;
import com.cloud.agent.api.GetDomRVersionAnswer;
import com.cloud.agent.api.GetDomRVersionCmd;
import com.cloud.agent.api.GetVmStatsCommand;
@ -110,4 +111,6 @@ public interface MockVmManager extends Manager {
Answer deleteVmSnapshot(DeleteVMSnapshotCommand cmd);
Answer revertVmSnapshot(RevertToVMSnapshotCommand cmd);
Answer fence(FenceCommand cmd);
}

View File

@ -27,6 +27,7 @@ import javax.inject.Inject;
import javax.naming.ConfigurationException;
import com.cloud.network.VirtualNetworkApplianceService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
@ -41,6 +42,8 @@ import com.cloud.agent.api.CreateVMSnapshotAnswer;
import com.cloud.agent.api.CreateVMSnapshotCommand;
import com.cloud.agent.api.DeleteVMSnapshotAnswer;
import com.cloud.agent.api.DeleteVMSnapshotCommand;
import com.cloud.agent.api.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.agent.api.GetDomRVersionAnswer;
import com.cloud.agent.api.GetDomRVersionCmd;
import com.cloud.agent.api.GetVmStatsAnswer;
@ -661,4 +664,8 @@ public class MockVmManagerImpl extends ManagerBase implements MockVmManager {
return maps;
}
@Override
public Answer fence(FenceCommand cmd) {
return new FenceAnswer(cmd);
}
}

View File

@ -22,7 +22,9 @@ import java.util.Map;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.StoragePoolInfo;
import com.cloud.simulator.MockConfigurationVO;
import com.cloud.simulator.MockVMVO;
import com.cloud.simulator.dao.MockConfigurationDao;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Manager;
import com.cloud.vm.VirtualMachine.State;
@ -56,11 +58,17 @@ public interface SimulatorManager extends Manager {
StoragePoolInfo getLocalStorage(String hostGuid);
boolean configureSimulator(Long zoneId, Long podId, Long clusterId, Long hostId, String command, String values);
Long configureSimulator(Long zoneId, Long podId, Long clusterId, Long hostId, String command, String values, Integer count, String jsonResponse);
public HashMap<String, Pair<Long, Long>> syncNetworkGroups(String hostGuid);
Map<String, State> getVmStates(String hostGuid);
Map<String, MockVMVO> getVms(String hostGuid);
MockConfigurationVO querySimulatorMock(Long id);
boolean clearSimulatorMock(Long id);
MockConfigurationDao getMockConfigurationDao();
}

View File

@ -16,7 +16,9 @@
// under the License.
package com.cloud.agent.manager;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -108,8 +110,12 @@ import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.storage.ListTemplateCommand;
import com.cloud.agent.api.storage.ListVolumeCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.api.commands.CleanupSimulatorMockCmd;
import com.cloud.api.commands.ConfigureSimulatorCmd;
import com.cloud.api.commands.QuerySimulatorMockCmd;
import com.cloud.agent.api.SecStorageFirewallCfgCommand;
import com.cloud.resource.SimulatorStorageProcessor;
import com.cloud.serializer.GsonHelper;
import com.cloud.simulator.MockConfigurationVO;
import com.cloud.simulator.MockHost;
import com.cloud.simulator.MockVMVO;
@ -124,11 +130,14 @@ import com.cloud.utils.db.DB;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.VirtualMachine.State;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
@Component
@Local(value = {SimulatorManager.class})
public class SimulatorManagerImpl extends ManagerBase implements SimulatorManager, PluggableService {
private static final Logger s_logger = Logger.getLogger(SimulatorManagerImpl.class);
private static final Gson s_gson = GsonHelper.getGson();
@Inject
MockVmManager _mockVmMgr;
@Inject
@ -184,12 +193,16 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
public List<Class<?>> getCommands() {
List<Class<?>> cmdList = new ArrayList<Class<?>>();
cmdList.add(ConfigureSimulatorCmd.class);
cmdList.add(QuerySimulatorMockCmd.class);
cmdList.add(CleanupSimulatorMockCmd.class);
return cmdList;
}
@DB
@Override
public Answer simulate(Command cmd, String hostGuid) {
Answer answer = null;
Exception exception = null;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
MockHost host = _mockHost.findByGuid(hostGuid);
@ -198,12 +211,12 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
if (index != -1) {
cmdName = cmdName.substring(index + 1);
}
MockConfigurationVO config = _mockConfigDao.findByNameBottomUP(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), cmdName);
SimulatorInfo info = new SimulatorInfo();
info.setHostUuid(hostGuid);
if (config != null) {
MockConfigurationVO config = _mockConfigDao.findByNameBottomUP(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), cmdName);
if (config != null && (config.getCount() == null || config.getCount().intValue() > 0)) {
Map<String, String> configParameters = config.getParameters();
for (Map.Entry<String, String> entry : configParameters.entrySet()) {
if (entry.getKey().equalsIgnoreCase("enabled")) {
@ -214,171 +227,218 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
} catch (NumberFormatException e) {
s_logger.debug("invalid timeout parameter: " + e.toString());
}
} else if (entry.getKey().equalsIgnoreCase("wait")) {
}
if (entry.getKey().equalsIgnoreCase("wait")) {
try {
int wait = Integer.valueOf(entry.getValue());
Thread.sleep(wait);
} catch (NumberFormatException e) {
s_logger.debug("invalid timeout parameter: " + e.toString());
s_logger.debug("invalid wait parameter: " + e.toString());
} catch (InterruptedException e) {
s_logger.debug("thread is interrupted: " + e.toString());
}
}
if (entry.getKey().equalsIgnoreCase("result")) {
String value = entry.getValue();
if (value.equalsIgnoreCase("fail")) {
answer = new Answer(cmd, false, "Simulated failure");
} else if (value.equalsIgnoreCase("fault")) {
exception = new Exception("Simulated fault");
}
}
}
if (exception != null) {
throw exception;
}
if (answer == null) {
String message = config.getJsonResponse();
if (message != null) {
// json response looks like {"<Type>":....}
String objectType = message.split(":")[0].substring(2).replace("\"", "");
String objectData = message.substring(message.indexOf(':') + 1, message.length() - 1);
if (objectType != null) {
Class<?> clz = null;
try {
clz = Class.forName(objectType);
} catch (ClassNotFoundException e) {
}
if (clz != null) {
StringReader reader = new StringReader(objectData);
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
answer = (Answer)s_gson.fromJson(jsonReader, clz);
}
}
}
}
}
if (cmd instanceof GetHostStatsCommand) {
return _mockAgentMgr.getHostStatistic((GetHostStatsCommand)cmd);
} else if (cmd instanceof CheckHealthCommand) {
return _mockAgentMgr.checkHealth((CheckHealthCommand)cmd);
} else if (cmd instanceof PingTestCommand) {
return _mockAgentMgr.pingTest((PingTestCommand)cmd);
} else if (cmd instanceof PrepareForMigrationCommand) {
return _mockVmMgr.prepareForMigrate((PrepareForMigrationCommand)cmd);
} else if (cmd instanceof MigrateCommand) {
return _mockVmMgr.Migrate((MigrateCommand)cmd, info);
} else if (cmd instanceof StartCommand) {
return _mockVmMgr.startVM((StartCommand)cmd, info);
} else if (cmd instanceof CheckSshCommand) {
return _mockVmMgr.checkSshCommand((CheckSshCommand)cmd);
} else if (cmd instanceof CheckVirtualMachineCommand) {
return _mockVmMgr.checkVmState((CheckVirtualMachineCommand)cmd);
} else if (cmd instanceof SetStaticNatRulesCommand) {
return _mockNetworkMgr.SetStaticNatRules((SetStaticNatRulesCommand)cmd);
} else if (cmd instanceof SetFirewallRulesCommand) {
return _mockNetworkMgr.SetFirewallRules((SetFirewallRulesCommand)cmd);
} else if (cmd instanceof SetPortForwardingRulesCommand) {
return _mockNetworkMgr.SetPortForwardingRules((SetPortForwardingRulesCommand)cmd);
} else if (cmd instanceof NetworkUsageCommand) {
return _mockNetworkMgr.getNetworkUsage((NetworkUsageCommand)cmd);
} else if (cmd instanceof IpAssocCommand) {
return _mockNetworkMgr.IpAssoc((IpAssocCommand)cmd);
} else if (cmd instanceof LoadBalancerConfigCommand) {
return _mockNetworkMgr.LoadBalancerConfig((LoadBalancerConfigCommand)cmd);
} else if (cmd instanceof DhcpEntryCommand) {
return _mockNetworkMgr.AddDhcpEntry((DhcpEntryCommand)cmd);
} else if (cmd instanceof VmDataCommand) {
return _mockVmMgr.setVmData((VmDataCommand)cmd);
} else if (cmd instanceof CleanupNetworkRulesCmd) {
return _mockVmMgr.CleanupNetworkRules((CleanupNetworkRulesCmd)cmd, info);
} else if (cmd instanceof CheckNetworkCommand) {
return _mockAgentMgr.checkNetworkCommand((CheckNetworkCommand)cmd);
} else if (cmd instanceof StopCommand) {
return _mockVmMgr.stopVM((StopCommand)cmd);
} else if (cmd instanceof RebootCommand) {
return _mockVmMgr.rebootVM((RebootCommand)cmd);
} else if (cmd instanceof GetVncPortCommand) {
return _mockVmMgr.getVncPort((GetVncPortCommand)cmd);
} else if (cmd instanceof CheckConsoleProxyLoadCommand) {
return _mockVmMgr.CheckConsoleProxyLoad((CheckConsoleProxyLoadCommand)cmd);
} else if (cmd instanceof WatchConsoleProxyLoadCommand) {
return _mockVmMgr.WatchConsoleProxyLoad((WatchConsoleProxyLoadCommand)cmd);
} else if (cmd instanceof SecurityGroupRulesCmd) {
return _mockVmMgr.AddSecurityGroupRules((SecurityGroupRulesCmd)cmd, info);
} else if (cmd instanceof SavePasswordCommand) {
return _mockVmMgr.SavePassword((SavePasswordCommand)cmd);
} else if (cmd instanceof PrimaryStorageDownloadCommand) {
return _mockStorageMgr.primaryStorageDownload((PrimaryStorageDownloadCommand)cmd);
} else if (cmd instanceof CreateCommand) {
return _mockStorageMgr.createVolume((CreateCommand)cmd);
} else if (cmd instanceof AttachVolumeCommand) {
return _mockStorageMgr.AttachVolume((AttachVolumeCommand)cmd);
} else if (cmd instanceof AttachIsoCommand) {
return _mockStorageMgr.AttachIso((AttachIsoCommand)cmd);
} else if (cmd instanceof DeleteStoragePoolCommand) {
return _mockStorageMgr.DeleteStoragePool((DeleteStoragePoolCommand)cmd);
} else if (cmd instanceof ModifyStoragePoolCommand) {
return _mockStorageMgr.ModifyStoragePool((ModifyStoragePoolCommand)cmd);
} else if (cmd instanceof CreateStoragePoolCommand) {
return _mockStorageMgr.CreateStoragePool((CreateStoragePoolCommand)cmd);
} else if (cmd instanceof SecStorageSetupCommand) {
return _mockStorageMgr.SecStorageSetup((SecStorageSetupCommand)cmd);
} else if (cmd instanceof ListTemplateCommand) {
return _mockStorageMgr.ListTemplates((ListTemplateCommand)cmd);
} else if (cmd instanceof ListVolumeCommand) {
return _mockStorageMgr.ListVolumes((ListVolumeCommand)cmd);
} else if (cmd instanceof DestroyCommand) {
return _mockStorageMgr.Destroy((DestroyCommand)cmd);
} else if (cmd instanceof DownloadProgressCommand) {
return _mockStorageMgr.DownloadProcess((DownloadProgressCommand)cmd);
} else if (cmd instanceof DownloadCommand) {
return _mockStorageMgr.Download((DownloadCommand)cmd);
} else if (cmd instanceof GetStorageStatsCommand) {
return _mockStorageMgr.GetStorageStats((GetStorageStatsCommand)cmd);
} else if (cmd instanceof ManageSnapshotCommand) {
return _mockStorageMgr.ManageSnapshot((ManageSnapshotCommand)cmd);
} else if (cmd instanceof BackupSnapshotCommand) {
return _mockStorageMgr.BackupSnapshot((BackupSnapshotCommand)cmd, info);
} else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
return _mockStorageMgr.CreateVolumeFromSnapshot((CreateVolumeFromSnapshotCommand)cmd);
} else if (cmd instanceof DeleteCommand) {
return _mockStorageMgr.Delete((DeleteCommand)cmd);
} else if (cmd instanceof SecStorageVMSetupCommand) {
return _mockStorageMgr.SecStorageVMSetup((SecStorageVMSetupCommand)cmd);
} else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
return _mockStorageMgr.CreatePrivateTemplateFromSnapshot((CreatePrivateTemplateFromSnapshotCommand)cmd);
} else if (cmd instanceof ComputeChecksumCommand) {
return _mockStorageMgr.ComputeChecksum((ComputeChecksumCommand)cmd);
} else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
return _mockStorageMgr.CreatePrivateTemplateFromVolume((CreatePrivateTemplateFromVolumeCommand)cmd);
} else if (cmd instanceof MaintainCommand) {
return _mockAgentMgr.maintain((MaintainCommand)cmd);
} else if (cmd instanceof GetVmStatsCommand) {
return _mockVmMgr.getVmStats((GetVmStatsCommand)cmd);
} else if (cmd instanceof CheckRouterCommand) {
return _mockVmMgr.checkRouter((CheckRouterCommand)cmd);
} else if (cmd instanceof BumpUpPriorityCommand) {
return _mockVmMgr.bumpPriority((BumpUpPriorityCommand)cmd);
} else if (cmd instanceof GetDomRVersionCmd) {
return _mockVmMgr.getDomRVersion((GetDomRVersionCmd)cmd);
} else if (cmd instanceof ClusterSyncCommand) {
return new Answer(cmd);
} else if (cmd instanceof CopyVolumeCommand) {
return _mockStorageMgr.CopyVolume((CopyVolumeCommand)cmd);
} else if (cmd instanceof PlugNicCommand) {
return _mockNetworkMgr.plugNic((PlugNicCommand)cmd);
} else if (cmd instanceof UnPlugNicCommand) {
return _mockNetworkMgr.unplugNic((UnPlugNicCommand)cmd);
} else if (cmd instanceof IpAssocVpcCommand) {
return _mockNetworkMgr.ipAssoc((IpAssocVpcCommand)cmd);
} else if (cmd instanceof SetSourceNatCommand) {
return _mockNetworkMgr.setSourceNat((SetSourceNatCommand)cmd);
} else if (cmd instanceof SetNetworkACLCommand) {
return _mockNetworkMgr.setNetworkAcl((SetNetworkACLCommand)cmd);
} else if (cmd instanceof SetupGuestNetworkCommand) {
return _mockNetworkMgr.setUpGuestNetwork((SetupGuestNetworkCommand)cmd);
} else if (cmd instanceof SetPortForwardingRulesVpcCommand) {
return _mockNetworkMgr.setVpcPortForwards((SetPortForwardingRulesVpcCommand)cmd);
} else if (cmd instanceof SetStaticNatRulesCommand) {
return _mockNetworkMgr.setVPCStaticNatRules((SetStaticNatRulesCommand)cmd);
} else if (cmd instanceof SetStaticRouteCommand) {
return _mockNetworkMgr.setStaticRoute((SetStaticRouteCommand)cmd);
} else if (cmd instanceof Site2SiteVpnCfgCommand) {
return _mockNetworkMgr.siteToSiteVpn((Site2SiteVpnCfgCommand)cmd);
} else if (cmd instanceof CheckS2SVpnConnectionsCommand) {
return _mockNetworkMgr.checkSiteToSiteVpnConnection((CheckS2SVpnConnectionsCommand)cmd);
} else if (cmd instanceof CreateVMSnapshotCommand) {
return _mockVmMgr.createVmSnapshot((CreateVMSnapshotCommand)cmd);
} else if (cmd instanceof DeleteVMSnapshotCommand) {
return _mockVmMgr.deleteVmSnapshot((DeleteVMSnapshotCommand)cmd);
} else if (cmd instanceof RevertToVMSnapshotCommand) {
return _mockVmMgr.revertVmSnapshot((RevertToVMSnapshotCommand)cmd);
} else if (cmd instanceof NetworkRulesVmSecondaryIpCommand) {
return _mockVmMgr.plugSecondaryIp((NetworkRulesVmSecondaryIpCommand)cmd);
} else if (cmd instanceof ScaleVmCommand) {
return _mockVmMgr.scaleVm((ScaleVmCommand)cmd);
} else if (cmd instanceof PvlanSetupCommand) {
return _mockNetworkMgr.setupPVLAN((PvlanSetupCommand)cmd);
} else if (cmd instanceof StorageSubSystemCommand) {
return this.storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
} else if (cmd instanceof GetRouterAlertsCommand) {
return new Answer(cmd);
} else if (cmd instanceof VpnUsersCfgCommand || cmd instanceof RemoteAccessVpnCfgCommand || cmd instanceof SetMonitorServiceCommand || cmd instanceof AggregationControlCommand) {
return new Answer(cmd);
} else {
s_logger.error("Simulator does not implement command of type " + cmd.toString());
return Answer.createUnsupportedCommandAnswer(cmd);
if (answer == null) {
if (cmd instanceof GetHostStatsCommand) {
answer = _mockAgentMgr.getHostStatistic((GetHostStatsCommand)cmd);
} else if (cmd instanceof CheckHealthCommand) {
answer = _mockAgentMgr.checkHealth((CheckHealthCommand)cmd);
} else if (cmd instanceof PingTestCommand) {
answer = _mockAgentMgr.pingTest((PingTestCommand)cmd);
} else if (cmd instanceof PrepareForMigrationCommand) {
answer = _mockVmMgr.prepareForMigrate((PrepareForMigrationCommand)cmd);
} else if (cmd instanceof MigrateCommand) {
answer = _mockVmMgr.Migrate((MigrateCommand)cmd, info);
} else if (cmd instanceof StartCommand) {
answer = _mockVmMgr.startVM((StartCommand)cmd, info);
} else if (cmd instanceof CheckSshCommand) {
answer = _mockVmMgr.checkSshCommand((CheckSshCommand)cmd);
} else if (cmd instanceof CheckVirtualMachineCommand) {
answer = _mockVmMgr.checkVmState((CheckVirtualMachineCommand)cmd);
} else if (cmd instanceof SetStaticNatRulesCommand) {
answer = _mockNetworkMgr.SetStaticNatRules((SetStaticNatRulesCommand)cmd);
} else if (cmd instanceof SetFirewallRulesCommand) {
answer = _mockNetworkMgr.SetFirewallRules((SetFirewallRulesCommand)cmd);
} else if (cmd instanceof SetPortForwardingRulesCommand) {
answer = _mockNetworkMgr.SetPortForwardingRules((SetPortForwardingRulesCommand)cmd);
} else if (cmd instanceof NetworkUsageCommand) {
answer = _mockNetworkMgr.getNetworkUsage((NetworkUsageCommand)cmd);
} else if (cmd instanceof IpAssocCommand) {
answer = _mockNetworkMgr.IpAssoc((IpAssocCommand)cmd);
} else if (cmd instanceof LoadBalancerConfigCommand) {
answer = _mockNetworkMgr.LoadBalancerConfig((LoadBalancerConfigCommand)cmd);
} else if (cmd instanceof DhcpEntryCommand) {
answer = _mockNetworkMgr.AddDhcpEntry((DhcpEntryCommand)cmd);
} else if (cmd instanceof VmDataCommand) {
answer = _mockVmMgr.setVmData((VmDataCommand)cmd);
} else if (cmd instanceof CleanupNetworkRulesCmd) {
answer = _mockVmMgr.CleanupNetworkRules((CleanupNetworkRulesCmd)cmd, info);
} else if (cmd instanceof CheckNetworkCommand) {
answer = _mockAgentMgr.checkNetworkCommand((CheckNetworkCommand)cmd);
} else if (cmd instanceof StopCommand) {
answer = _mockVmMgr.stopVM((StopCommand)cmd);
} else if (cmd instanceof RebootCommand) {
answer = _mockVmMgr.rebootVM((RebootCommand)cmd);
} else if (cmd instanceof GetVncPortCommand) {
answer = _mockVmMgr.getVncPort((GetVncPortCommand)cmd);
} else if (cmd instanceof CheckConsoleProxyLoadCommand) {
answer = _mockVmMgr.CheckConsoleProxyLoad((CheckConsoleProxyLoadCommand)cmd);
} else if (cmd instanceof WatchConsoleProxyLoadCommand) {
answer = _mockVmMgr.WatchConsoleProxyLoad((WatchConsoleProxyLoadCommand)cmd);
} else if (cmd instanceof SecurityGroupRulesCmd) {
answer = _mockVmMgr.AddSecurityGroupRules((SecurityGroupRulesCmd)cmd, info);
} else if (cmd instanceof SavePasswordCommand) {
answer = _mockVmMgr.SavePassword((SavePasswordCommand)cmd);
} else if (cmd instanceof PrimaryStorageDownloadCommand) {
answer = _mockStorageMgr.primaryStorageDownload((PrimaryStorageDownloadCommand)cmd);
} else if (cmd instanceof CreateCommand) {
answer = _mockStorageMgr.createVolume((CreateCommand)cmd);
} else if (cmd instanceof AttachVolumeCommand) {
answer = _mockStorageMgr.AttachVolume((AttachVolumeCommand)cmd);
} else if (cmd instanceof AttachIsoCommand) {
answer = _mockStorageMgr.AttachIso((AttachIsoCommand)cmd);
} else if (cmd instanceof DeleteStoragePoolCommand) {
answer = _mockStorageMgr.DeleteStoragePool((DeleteStoragePoolCommand)cmd);
} else if (cmd instanceof ModifyStoragePoolCommand) {
answer = _mockStorageMgr.ModifyStoragePool((ModifyStoragePoolCommand)cmd);
} else if (cmd instanceof CreateStoragePoolCommand) {
answer = _mockStorageMgr.CreateStoragePool((CreateStoragePoolCommand)cmd);
} else if (cmd instanceof SecStorageSetupCommand) {
answer = _mockStorageMgr.SecStorageSetup((SecStorageSetupCommand)cmd);
} else if (cmd instanceof ListTemplateCommand) {
answer = _mockStorageMgr.ListTemplates((ListTemplateCommand)cmd);
} else if (cmd instanceof ListVolumeCommand) {
answer = _mockStorageMgr.ListVolumes((ListVolumeCommand)cmd);
} else if (cmd instanceof DestroyCommand) {
answer = _mockStorageMgr.Destroy((DestroyCommand)cmd);
} else if (cmd instanceof DownloadProgressCommand) {
answer = _mockStorageMgr.DownloadProcess((DownloadProgressCommand)cmd);
} else if (cmd instanceof DownloadCommand) {
answer = _mockStorageMgr.Download((DownloadCommand)cmd);
} else if (cmd instanceof GetStorageStatsCommand) {
answer = _mockStorageMgr.GetStorageStats((GetStorageStatsCommand)cmd);
} else if (cmd instanceof ManageSnapshotCommand) {
answer = _mockStorageMgr.ManageSnapshot((ManageSnapshotCommand)cmd);
} else if (cmd instanceof BackupSnapshotCommand) {
answer = _mockStorageMgr.BackupSnapshot((BackupSnapshotCommand)cmd, info);
} else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
answer = _mockStorageMgr.CreateVolumeFromSnapshot((CreateVolumeFromSnapshotCommand)cmd);
} else if (cmd instanceof DeleteCommand) {
answer = _mockStorageMgr.Delete((DeleteCommand)cmd);
} else if (cmd instanceof SecStorageVMSetupCommand) {
answer = _mockStorageMgr.SecStorageVMSetup((SecStorageVMSetupCommand)cmd);
} else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
answer = _mockStorageMgr.CreatePrivateTemplateFromSnapshot((CreatePrivateTemplateFromSnapshotCommand)cmd);
} else if (cmd instanceof ComputeChecksumCommand) {
answer = _mockStorageMgr.ComputeChecksum((ComputeChecksumCommand)cmd);
} else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
answer = _mockStorageMgr.CreatePrivateTemplateFromVolume((CreatePrivateTemplateFromVolumeCommand)cmd);
} else if (cmd instanceof MaintainCommand) {
answer = _mockAgentMgr.maintain((MaintainCommand)cmd);
} else if (cmd instanceof GetVmStatsCommand) {
answer = _mockVmMgr.getVmStats((GetVmStatsCommand)cmd);
} else if (cmd instanceof CheckRouterCommand) {
answer = _mockVmMgr.checkRouter((CheckRouterCommand)cmd);
} else if (cmd instanceof BumpUpPriorityCommand) {
answer = _mockVmMgr.bumpPriority((BumpUpPriorityCommand)cmd);
} else if (cmd instanceof GetDomRVersionCmd) {
answer = _mockVmMgr.getDomRVersion((GetDomRVersionCmd)cmd);
} else if (cmd instanceof ClusterSyncCommand) {
answer = new Answer(cmd);
} else if (cmd instanceof CopyVolumeCommand) {
answer = _mockStorageMgr.CopyVolume((CopyVolumeCommand)cmd);
} else if (cmd instanceof PlugNicCommand) {
answer = _mockNetworkMgr.plugNic((PlugNicCommand)cmd);
} else if (cmd instanceof UnPlugNicCommand) {
answer = _mockNetworkMgr.unplugNic((UnPlugNicCommand)cmd);
} else if (cmd instanceof IpAssocVpcCommand) {
answer = _mockNetworkMgr.ipAssoc((IpAssocVpcCommand)cmd);
} else if (cmd instanceof SetSourceNatCommand) {
answer = _mockNetworkMgr.setSourceNat((SetSourceNatCommand)cmd);
} else if (cmd instanceof SetNetworkACLCommand) {
answer = _mockNetworkMgr.setNetworkAcl((SetNetworkACLCommand)cmd);
} else if (cmd instanceof SetupGuestNetworkCommand) {
answer = _mockNetworkMgr.setUpGuestNetwork((SetupGuestNetworkCommand)cmd);
} else if (cmd instanceof SetPortForwardingRulesVpcCommand) {
answer = _mockNetworkMgr.setVpcPortForwards((SetPortForwardingRulesVpcCommand)cmd);
} else if (cmd instanceof SetStaticNatRulesCommand) {
answer = _mockNetworkMgr.setVPCStaticNatRules((SetStaticNatRulesCommand)cmd);
} else if (cmd instanceof SetStaticRouteCommand) {
answer = _mockNetworkMgr.setStaticRoute((SetStaticRouteCommand)cmd);
} else if (cmd instanceof Site2SiteVpnCfgCommand) {
answer = _mockNetworkMgr.siteToSiteVpn((Site2SiteVpnCfgCommand)cmd);
} else if (cmd instanceof CheckS2SVpnConnectionsCommand) {
answer = _mockNetworkMgr.checkSiteToSiteVpnConnection((CheckS2SVpnConnectionsCommand)cmd);
} else if (cmd instanceof CreateVMSnapshotCommand) {
answer = _mockVmMgr.createVmSnapshot((CreateVMSnapshotCommand)cmd);
} else if (cmd instanceof DeleteVMSnapshotCommand) {
answer = _mockVmMgr.deleteVmSnapshot((DeleteVMSnapshotCommand)cmd);
} else if (cmd instanceof RevertToVMSnapshotCommand) {
answer = _mockVmMgr.revertVmSnapshot((RevertToVMSnapshotCommand)cmd);
} else if (cmd instanceof NetworkRulesVmSecondaryIpCommand) {
answer = _mockVmMgr.plugSecondaryIp((NetworkRulesVmSecondaryIpCommand)cmd);
} else if (cmd instanceof ScaleVmCommand) {
answer = _mockVmMgr.scaleVm((ScaleVmCommand)cmd);
} else if (cmd instanceof PvlanSetupCommand) {
answer = _mockNetworkMgr.setupPVLAN((PvlanSetupCommand)cmd);
} else if (cmd instanceof StorageSubSystemCommand) {
answer = this.storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
} else if (cmd instanceof GetRouterAlertsCommand || cmd instanceof VpnUsersCfgCommand || cmd instanceof RemoteAccessVpnCfgCommand || cmd instanceof SetMonitorServiceCommand || cmd instanceof AggregationControlCommand ||
cmd instanceof SecStorageFirewallCfgCommand) {
answer = new Answer(cmd);
} else {
s_logger.error("Simulator does not implement command of type " + cmd.toString());
answer = Answer.createUnsupportedCommandAnswer(cmd);
}
}
if (config != null && (config.getCount() != null && config.getCount().intValue() > 0)) {
if (answer != null) {
config.setCount(config.getCount().intValue() - 1);
_mockConfigDao.update(config.getId(), config);
}
}
return answer;
} catch (Exception e) {
s_logger.error("Failed execute cmd: ", e);
txn.rollback();
@ -413,7 +473,8 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
}
@Override
public boolean configureSimulator(Long zoneId, Long podId, Long clusterId, Long hostId, String command, String values) {
public Long configureSimulator(Long zoneId, Long podId, Long clusterId, Long hostId, String command, String values, Integer count, String jsonResponse) {
Long id = null;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
@ -426,21 +487,71 @@ public class SimulatorManagerImpl extends ManagerBase implements SimulatorManage
config.setHostId(hostId);
config.setName(command);
config.setValues(values);
_mockConfigDao.persist(config);
config.setCount(count);
config.setJsonResponse(jsonResponse);
config = _mockConfigDao.persist(config);
txn.commit();
} else {
config.setValues(values);
config.setCount(count);
config.setJsonResponse(jsonResponse);
_mockConfigDao.update(config.getId(), config);
txn.commit();
}
id = config.getId();
} catch (Exception ex) {
txn.rollback();
throw new CloudRuntimeException("Unable to configure simulator because of " + ex.getMessage(), ex);
throw new CloudRuntimeException("Unable to configure simulator mock because of " + ex.getMessage(), ex);
} finally {
txn.close();
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
txn.close();
}
return true;
return id;
}
@Override
public MockConfigurationVO querySimulatorMock(Long id) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
return _mockConfigDao.findById(id);
} catch (Exception ex) {
txn.rollback();
throw new CloudRuntimeException("Unable to query simulator mock because of " + ex.getMessage(), ex);
} finally {
txn.close();
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
txn.close();
}
}
@Override
public boolean clearSimulatorMock(Long id) {
boolean status = false;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
txn.start();
MockConfigurationVO config = _mockConfigDao.findById(id);
if (config != null) {
config.setRemoved(new Date());
_mockConfigDao.update(config.getId(), config);
status = true;
txn.commit();
}
} catch (Exception ex) {
txn.rollback();
throw new CloudRuntimeException("Unable to cleanup simulator mock because of " + ex.getMessage(), ex);
} finally {
txn.close();
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
txn.close();
}
return status;
}
@Override
public MockConfigurationDao getMockConfigurationDao() {
return _mockConfigDao;
}
}

View File

@ -0,0 +1,69 @@
// 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.api.commands;
import com.cloud.agent.manager.SimulatorManager;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.user.Account;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.log4j.Logger;
import javax.inject.Inject;
@APICommand(name = "cleanupSimulatorMock", description="cleanup simulator mock", responseObject=SuccessResponse.class)
public class CleanupSimulatorMockCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CleanupSimulatorMockCmd.class.getName());
private static final String s_name = "cleanupsimulatormockresponse";
@Inject SimulatorManager _simMgr;
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="id of the configured mock")
private Long id;
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
boolean result = _simMgr.clearSimulatorMock(id);
if (!result) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to cleanup mock");
}
SuccessResponse response = new SuccessResponse(getCommandName());
this.setResponseObject(response);
}
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
}

View File

@ -19,23 +19,27 @@ package com.cloud.api.commands;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.api.response.ClusterResponse;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.PodResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import com.cloud.agent.manager.SimulatorManager;
import com.cloud.api.response.MockResponse;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.simulator.MockConfigurationVO;
import com.cloud.user.Account;
@APICommand(name = "configureSimulator", description = "configure simulator", responseObject = SuccessResponse.class,
@APICommand(name = "configureSimulator", description = "configure simulator", responseObject = MockResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class ConfigureSimulatorCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(ConfigureSimulatorCmd.class.getName());
@ -44,16 +48,16 @@ public class ConfigureSimulatorCmd extends BaseCmd {
@Inject
SimulatorManager _simMgr;
@Parameter(name = ApiConstants.ZONE_ID, type = CommandType.LONG, description = "configure range: in a zone")
@Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, description="configure range: in a zone")
private Long zoneId;
@Parameter(name = ApiConstants.POD_ID, type = CommandType.LONG, description = "configure range: in a pod")
@Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, description="configure range: in a pod")
private Long podId;
@Parameter(name = ApiConstants.CLUSTER_ID, type = CommandType.LONG, description = "configure range: in a cluster")
@Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, description="configure range: in a cluster")
private Long clusterId;
@Parameter(name = ApiConstants.HOST_ID, type = CommandType.LONG, description = "configure range: in a host")
@Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, description="configure range: in a host")
private Long hostId;
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "which command needs to be configured")
@ -62,15 +66,34 @@ public class ConfigureSimulatorCmd extends BaseCmd {
@Parameter(name = ApiConstants.VALUE, type = CommandType.STRING, required = true, description = "configuration options for this command, which is seperated by ;")
private String values;
@Parameter(name=ApiConstants.COUNT, type=CommandType.INTEGER, description="number of times the mock is active")
private Integer count;
@Parameter(name="jsonresponse", type=CommandType.STRING, description="agent command response to be returned")
private String jsonResponse;
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
ResourceAllocationException {
boolean result = _simMgr.configureSimulator(zoneId, podId, clusterId, hostId, command, values);
if (!result) {
Long id = _simMgr.configureSimulator(zoneId, podId, clusterId, hostId, command, values, count, jsonResponse);
if (id == null) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure simulator");
}
SuccessResponse response = new SuccessResponse(getCommandName());
MockConfigurationVO config = _simMgr.querySimulatorMock(id);
if (config == null) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to query simulator mock");
}
MockResponse response = new MockResponse();
response.setId(config.getId());
response.setZoneId(config.getDataCenterId());
response.setPodId(config.getPodId());
response.setClusterId(config.getClusterId());
response.setHostId(config.getHostId());
response.setName(config.getName());
response.setCount(config.getCount());
response.setResponseName("simulatormock");
this.setResponseObject(response);
}

View File

@ -0,0 +1,78 @@
// 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.api.commands;
import com.cloud.agent.manager.SimulatorManager;
import com.cloud.api.response.MockResponse;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.simulator.MockConfigurationVO;
import com.cloud.user.Account;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.log4j.Logger;
import javax.inject.Inject;
@APICommand(name = "querySimulatorMock", description="query simulator mock", responseObject=MockResponse.class)
public class QuerySimulatorMockCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(QuerySimulatorMockCmd.class.getName());
private static final String s_name = "querysimulatormockresponse";
@Inject SimulatorManager _simMgr;
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="id of the configured mock")
private Long id;
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
MockConfigurationVO config = _simMgr.querySimulatorMock(id);
if (config == null) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to query mock");
}
MockResponse response = new MockResponse();
response.setId(config.getId());
response.setZoneId(config.getDataCenterId());
response.setPodId(config.getPodId());
response.setClusterId(config.getClusterId());
response.setHostId(config.getHostId());
response.setName(config.getName());
response.setCount(config.getCount());
response.setResponseName("simulatormock");
this.setResponseObject(response);
}
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
}

View File

@ -0,0 +1,107 @@
// 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.api.response;
import com.cloud.serializer.Param;
import com.cloud.simulator.MockConfigurationVO;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
@EntityReference(value = MockConfigurationVO.class)
public class MockResponse extends BaseResponse {
@SerializedName(ApiConstants.ID) @Param(description="the mock ID")
private Long id;
@SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID scope of the mock")
private Long zoneId;
@SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID scope of the mock")
private Long podId;
@SerializedName(ApiConstants.CLUSTER_ID) @Param(description="the Cluster ID scope of the mock")
private Long clusterId;
@SerializedName(ApiConstants.HOST_ID) @Param(description="the Host ID scope of the mock")
private Long hostId;
@SerializedName(ApiConstants.NAME) @Param(description="the agent command to be mocked")
private String name;
@SerializedName(ApiConstants.COUNT) @Param(description="number of times mock is executed, if not specified then mock remains active till cleaned up")
private Integer count;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getZoneId() {
return zoneId;
}
public void setZoneId(Long zoneId) {
this.zoneId = zoneId;
}
public Long getPodId() {
return podId;
}
public void setPodId(Long podId) {
this.podId = podId;
}
public Long getClusterId() {
return clusterId;
}
public void setClusterId(Long clusterId) {
this.clusterId = clusterId;
}
public Long getHostId() {
return hostId;
}
public void setHostId(Long hostId) {
this.hostId = hostId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}

View File

@ -0,0 +1,116 @@
// 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.ha;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.FenceAnswer;
import com.cloud.agent.api.FenceCommand;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.resource.ResourceManager;
import com.cloud.utils.component.AdapterBase;
import com.cloud.vm.VirtualMachine;
@Local(value=FenceBuilder.class)
public class SimulatorFencer extends AdapterBase implements FenceBuilder {
private static final Logger s_logger = Logger.getLogger(SimulatorFencer.class);
@Inject HostDao _hostDao;
@Inject AgentManager _agentMgr;
@Inject ResourceManager _resourceMgr;
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean start() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean stop() {
// TODO Auto-generated method stub
return true;
}
public SimulatorFencer() {
super();
}
@Override
public Boolean fenceOff(VirtualMachine vm, Host host) {
if (host.getHypervisorType() != HypervisorType.Simulator) {
s_logger.debug("Don't know how to fence non simulator hosts " + host.getHypervisorType());
return null;
}
List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId());
FenceCommand fence = new FenceCommand(vm, host);
for (HostVO h : hosts) {
if (h.getHypervisorType() == HypervisorType.Simulator) {
if( h.getStatus() != Status.Up ) {
continue;
}
if( h.getId() == host.getId() ) {
continue;
}
FenceAnswer answer = null;
try {
answer = (FenceAnswer)_agentMgr.send(h.getId(), fence);
} catch (AgentUnavailableException e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable");
}
continue;
} catch (OperationTimedoutException e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable");
}
continue;
}
if (answer != null && answer.getResult()) {
return true;
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString());
}
return false;
}
}

View File

@ -0,0 +1,102 @@
// 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.ha;
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.Answer;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.resource.ResourceManager;
import com.cloud.simulator.dao.MockConfigurationDao;
import com.cloud.utils.component.AdapterBase;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
@Local(value=Investigator.class)
public class SimulatorInvestigator extends AdapterBase implements Investigator {
private final static Logger s_logger = Logger.getLogger(SimulatorInvestigator.class);
@Inject
AgentManager _agentMgr;
@Inject
ResourceManager _resourceMgr;
@Inject
MockConfigurationDao _mockConfigDao;
protected SimulatorInvestigator() {
}
@Override
public Status isAgentAlive(Host agent) {
if (agent.getHypervisorType() != HypervisorType.Simulator) {
return null;
}
CheckOnHostCommand cmd = new CheckOnHostCommand(agent);
List<HostVO> neighbors = _resourceMgr.listHostsInClusterByStatus(agent.getClusterId(), Status.Up);
for (HostVO neighbor : neighbors) {
if (neighbor.getId() == agent.getId() || neighbor.getHypervisorType() != Hypervisor.HypervisorType.Simulator) {
continue;
}
try {
Answer answer = _agentMgr.easySend(neighbor.getId(), cmd);
if (answer != null) {
return answer.getResult() ? Status.Up : Status.Down;
}
} catch (Exception e) {
s_logger.debug("Failed to send command to host: " + neighbor.getId());
}
}
return null;
}
@Override
public Boolean isVmAlive(VirtualMachine vm, Host host) {
CheckVirtualMachineCommand cmd = new CheckVirtualMachineCommand(vm.getInstanceName());
try {
Answer answer = _agentMgr.send(vm.getHostId(), cmd);
if (!answer.getResult()) {
s_logger.debug("Unable to get vm state on " + vm.toString());
return null;
}
CheckVirtualMachineAnswer cvmAnswer = (CheckVirtualMachineAnswer)answer;
s_logger.debug("Agent responded with state " + cvmAnswer.getState().toString());
return cvmAnswer.getState() == State.Running;
} catch (AgentUnavailableException e) {
s_logger.debug("Unable to reach the agent for " + vm.toString() + ": " + e.getMessage());
return null;
} catch (OperationTimedoutException e) {
s_logger.debug("Operation timed out for " + vm.toString() + ": " + e.getMessage());
return null;
}
}
}

View File

@ -16,6 +16,7 @@
// under the License.
package com.cloud.resource;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -50,15 +51,21 @@ import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.Networks.RouterPrivateIpStrategy;
import com.cloud.serializer.GsonHelper;
import com.cloud.simulator.MockConfigurationVO;
import com.cloud.simulator.MockVMVO;
import com.cloud.storage.Storage.StorageResourceType;
import com.cloud.storage.template.TemplateProp;
import com.cloud.utils.Pair;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.VirtualMachine.State;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
public class AgentRoutingResource extends AgentStorageResource {
private static final Logger s_logger = Logger.getLogger(AgentRoutingResource.class);
private static final Gson s_gson = GsonHelper.getGson();
protected Map<String, State> _vms = new HashMap<String, State>();
private Map<String, Pair<Long, Long>> _runningVms = new HashMap<String, Pair<Long, Long>>();
@ -104,6 +111,51 @@ public class AgentRoutingResource extends AgentStorageResource {
@Override
public PingCommand getCurrentStatus(long id) {
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
try {
MockConfigurationVO config = _simMgr.getMockConfigurationDao().findByNameBottomUP(agentHost.getDataCenterId(), agentHost.getPodId(), agentHost.getClusterId(), agentHost.getId(), "PingCommand");
if (config != null) {
Map<String, String> configParameters = config.getParameters();
for (Map.Entry<String, String> entry : configParameters.entrySet()) {
if (entry.getKey().equalsIgnoreCase("result")) {
String value = entry.getValue();
if (value.equalsIgnoreCase("fail")) {
return null;
}
}
}
}
config = _simMgr.getMockConfigurationDao().findByNameBottomUP(agentHost.getDataCenterId(), agentHost.getPodId(), agentHost.getClusterId(), agentHost.getId(), "PingRoutingWithNwGroupsCommand");
if (config != null) {
String message = config.getJsonResponse();
if (message != null) {
// json response looks like {"<Type>":....}
String objectType = message.split(":")[0].substring(2).replace("\"", "");
String objectData = message.substring(message.indexOf(':') + 1, message.length() - 1);
if (objectType != null) {
Class<?> clz = null;
try {
clz = Class.forName(objectType);
} catch (ClassNotFoundException e) {
}
if (clz != null) {
StringReader reader = new StringReader(objectData);
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
return (PingCommand)s_gson.fromJson(jsonReader, clz);
}
}
}
}
} catch (Exception e) {
txn.rollback();
} finally {
txn.close();
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
txn.close();
}
if (isStopped()) {
return null;
}
@ -279,8 +331,16 @@ public class AgentRoutingResource extends AgentStorageResource {
protected HashMap<String, HostVmStateReportEntry> getHostVmStateReport() {
HashMap<String, HostVmStateReportEntry> report = new HashMap<String, HostVmStateReportEntry>();
for (String vmName : _runningVms.keySet()) {
report.put(vmName, new HostVmStateReportEntry(PowerState.PowerOn, agentHost.getName()));
Map<String, State> states = _simMgr.getVmStates(this.hostGuid);
for (String vmName : states.keySet()) {
State state = states.get(vmName);
if (state == State.Running) {
report.put(vmName, new HostVmStateReportEntry(PowerState.PowerOn, agentHost.getName()));
} else if (state == State.Stopped) {
report.put(vmName, new HostVmStateReportEntry(PowerState.PowerOff, agentHost.getName()));
} else {
report.put(vmName, new HostVmStateReportEntry(PowerState.PowerUnknown, agentHost.getName()));
}
}
return report;

View File

@ -41,7 +41,6 @@ import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.manager.MockAgentManager;
import com.cloud.agent.manager.MockStorageManager;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.DiscoveryException;
import com.cloud.host.Host;
@ -65,15 +64,11 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L
@Inject
VMTemplateZoneDao _vmTemplateZoneDao;
@Inject
ClusterDao _clusterDao;
@Inject
AgentManager _agentMgr = null;
@Inject
MockAgentManager _mockAgentMgr = null;
@Inject
MockStorageManager _mockStorageMgr = null;
@Inject
ResourceManager _resourceMgr;
/**
* Finds ServerResources of an in-process simulator

View File

@ -31,7 +31,6 @@ import org.apache.cloudstack.storage.resource.SecondaryStorageDiscoverer;
import org.apache.cloudstack.storage.resource.SecondaryStorageResource;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
@ -52,8 +51,6 @@ public class SimulatorSecondaryDiscoverer extends SecondaryStorageDiscoverer imp
@Inject
MockStorageManager _mockStorageMgr = null;
@Inject
AgentManager _agentMgr;
@Inject
SnapshotDao _snapshotDao;
@Inject
ImageStoreDao imageStoreDao;

View File

@ -16,6 +16,7 @@
// under the License.
package com.cloud.simulator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@ -25,6 +26,8 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.apache.cloudstack.api.InternalIdentity;
@ -54,6 +57,16 @@ public class MockConfigurationVO implements InternalIdentity {
@Column(name = "values")
private String values;
@Column(name="count")
private Integer count;
@Column(name="json_response")
private String jsonResponse;
@Column(name="removed")
@Temporal(value=TemporalType.TIMESTAMP)
private Date removed;
@Override
public long getId() {
return this.id;
@ -120,4 +133,24 @@ public class MockConfigurationVO implements InternalIdentity {
public void setValues(String values) {
this.values = values;
}
public Integer getCount() {
return this.count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getJsonResponse() {
return this.jsonResponse;
}
public void setJsonResponse(String jsonResponse) {
this.jsonResponse = jsonResponse;
}
public void setRemoved(Date removed) {
this.removed = removed;
}
}

View File

@ -127,7 +127,9 @@ public class MockConfigurationDaoImpl extends GenericDaoBase<MockConfigurationVO
formatter.format(" or (data_center_id = %d and pod_id = %d and cluster_id = %d and host_id is null)", dcId, podId, clusterId);
formatter.format(" or (data_center_id = %d and pod_id = %d and cluster_id is null and host_id is null)", dcId, podId);
formatter.format(" or (data_center_id = %d and pod_id is null and cluster_id is null and host_id is null)", dcId);
formatter.format(" or (data_center_id is null and pod_id is null and cluster_id is null and host_id is null)) LIMIT 1");
formatter.format(" or (data_center_id is null and pod_id is null and cluster_id is null and host_id is null))");
formatter.format(" and removed is NULL ORDER BY id ASC LIMIT 1 for update");
formatter.close();
PreparedStatement pstmt = null;
try {

View File

@ -91,7 +91,6 @@ import com.vmware.vim25.VirtualMachineRelocateSpecDiskLocator;
import com.vmware.vim25.VirtualMachineRuntimeInfo;
import com.vmware.vim25.VmwareDistributedVirtualSwitchVlanIdSpec;
import org.apache.cloudstack.storage.command.DeleteCommand;
import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
import org.apache.cloudstack.storage.to.TemplateObjectTO;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
@ -3817,151 +3816,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
}
public Answer execute(DeleteCommand cmd) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource DeleteCommand: " + _gson.toJson(cmd));
}
/*
* DestroyCommand content exafmple
*
* {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary",
* "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType":
* "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } }
*
* {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary",
* "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem",
* "poolId":0,"deviceId":0 } }
*/
try {
VmwareContext context = getServiceContext();
VmwareHypervisorHost hyperHost = getHyperHost(context);
VolumeObjectTO vol = (VolumeObjectTO)cmd.getData();
DataStoreTO store = vol.getDataStore();
ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, store.getUuid());
if (morDs == null) {
String msg = "Unable to find datastore based on volume mount point " + store.getUrl();
s_logger.error(msg);
throw new Exception(msg);
}
DatastoreMO dsMo = new DatastoreMO(context, morDs);
ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter();
ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();
ClusterMO clusterMo = new ClusterMO(context, morCluster);
if (vol.getVolumeType() == Volume.Type.ROOT) {
String vmName = vol.getVmName();
if (vmName != null) {
VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName);
if (vmMo != null) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy root volume and VM itself. vmName " + vmName);
}
HostMO hostMo = vmMo.getRunningHost();
List<NetworkDetails> networks = vmMo.getNetworksWithDetails();
// tear down all devices first before we destroy the VM to avoid accidently delete disk backing files
if (getVmPowerState(vmMo) != PowerState.PowerOff)
vmMo.safePowerOff(_shutdownWaitMs);
vmMo.tearDownDevices(new Class<?>[] { /* VirtualDisk.class, */VirtualEthernetCard.class});
vmMo.destroy();
for (NetworkDetails netDetails : networks) {
if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) {
if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) {
cleanupNetwork(hostMo, netDetails);
}
}
}
}
if (s_logger.isInfoEnabled())
s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk");
dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true);
// root volume may be created via linked-clone, delete the delta disk as well
if (_fullCloneFlag) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk");
}
dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true);
} else {
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-delta.vmdk");
}
dsMo.deleteFile(vol.getPath() + "-delta.vmdk", morDc, true);
}
return new Answer(cmd, true, "Success");
}
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy root volume directly from datastore");
}
} else {
// evitTemplate will be converted into DestroyCommand, test if we are running in this case
VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vol.getPath());
if (vmMo != null) {
if (s_logger.isInfoEnabled())
s_logger.info("Destroy template volume " + vol.getPath());
vmMo.destroy();
return new Answer(cmd, true, "Success");
}
}
String chainInfo = vol.getChainInfo();
if (chainInfo != null && !chainInfo.isEmpty()) {
s_logger.info("Destroy volume by chain info: " + chainInfo);
String[] diskChain = _gson.fromJson(chainInfo, String[].class);
if (diskChain != null && diskChain.length > 0) {
for (String backingName : diskChain) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Delete volume backing file: " + backingName);
}
dsMo.deleteFile(backingName, morDc, true);
}
} else {
if (s_logger.isInfoEnabled()) {
s_logger.info("Empty disk chain info, fall back to try to delete by original backing file name");
}
dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true);
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk");
}
dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true);
}
} else {
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk");
}
dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true);
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk");
}
dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true);
}
return new Answer(cmd, true, "Success");
} catch (Throwable e) {
if (e instanceof RemoteException) {
s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
invalidateServiceContext();
}
String msg = "DestroyCommand failed due to " + VmwareHelper.getExceptionMessage(e);
s_logger.error(msg, e);
return new Answer(cmd, false, msg);
}
}
public void cleanupNetwork(HostMO hostMo, NetworkDetails netDetails) {
// we will no longer cleanup VLAN networks in order to support native VMware HA
/*

View File

@ -3908,7 +3908,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
s_logger.debug("Found unplugged VIF " + deviceId + " in VM " + vmName + " destroy it");
vif.destroy(conn);
}
usedDeviceNums.add(Integer.valueOf(vif.getDevice(conn)));
} catch (NumberFormatException e) {
String msg = "Obtained an invalid value for an allocated VIF device number for VM: " + vmName;
s_logger.debug(msg, e);

View File

@ -119,7 +119,7 @@ public class XenServer56Resource extends CitrixResourceBase {
host.forgetDataSourceArchives(conn, "pif_" + device + "." + vlannum + "_tx");
host.forgetDataSourceArchives(conn, "pif_" + device + "." + vlannum + "_rx");
} catch (XenAPIException e) {
s_logger.info("Catch " + e.getClass().getName() + ": failed to destory VLAN " + device + " on host " + _host.uuid + " due to " + e.toString());
s_logger.trace("Catch " + e.getClass().getName() + ": failed to destory VLAN " + device + " on host " + _host.uuid + " due to " + e.toString());
}
}
return;

View File

@ -135,6 +135,11 @@ public class XenServer620SP1Resource extends XenServer620Resource {
@Override
protected void createVGPU(Connection conn, StartCommand cmd, VM vm, GPUDeviceTO gpuDevice) throws XenAPIException, XmlRpcException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating VGPU of VGPU type [ " + gpuDevice.getVgpuType() + " ] in gpu group" + gpuDevice.getGpuGroup()
+ " for VM " + cmd.getVirtualMachine().getName());
}
Set<GPUGroup> groups = GPUGroup.getByNameLabel(conn, gpuDevice.getGpuGroup());
assert groups.size() == 1 : "Should only have 1 group but found " + groups.size();
GPUGroup gpuGroup = groups.iterator().next();

View File

@ -102,7 +102,7 @@ public class XenServerResourceNewBase extends XenServer620SP1Resource {
}
protected void waitForTask(Connection c, Task task, long pollInterval, long timeout) throws XenAPIException, XmlRpcException, TimeoutException {
protected void waitForTask2(Connection c, Task task, long pollInterval, long timeout) throws XenAPIException, XmlRpcException, TimeoutException {
long beginTime = System.currentTimeMillis();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Task " + task.getNameLabel(c) + " (" + task.getType(c) + ") sent to " + c.getSessionReference() + " is pending completion with a " + timeout +

View File

@ -900,7 +900,11 @@ public class ApiDBUtils {
}
public static DiskOfferingVO findDiskOfferingById(Long diskOfferingId) {
return s_diskOfferingDao.findByIdIncludingRemoved(diskOfferingId);
DiskOfferingVO off = s_diskOfferingDao.findByIdIncludingRemoved(diskOfferingId);
if (off.getType() == DiskOfferingVO.Type.Disk) {
return off;
}
return null;
}
public static DomainVO findDomainById(Long domainId) {

View File

@ -3382,23 +3382,40 @@ public class QueryManagerImpl extends ManagerBase implements QueryService {
Boolean forDisplay = cmd.getDisplay();
ResourceTag.ResourceObjectType resourceType = cmd.getResourceType();
String resourceIdStr = cmd.getResourceId();
String value = cmd.getValue();
Long resourceId = null;
//Validation - 1.1 - resourceId and value cant be null.
if(resourceIdStr == null && value == null){
throw new InvalidParameterValueException("Insufficient parameters passed for listing by resourceId OR key,value pair. Please check your params and try again.");
}
//Validation - 1.2 - Value has to be passed along with key.
if(value != null && key == null){
throw new InvalidParameterValueException("Listing by (key, value) but key is null. Please check the params and try again");
}
//Validation - 1.3
if (resourceIdStr != null) {
resourceId = _taggedResourceMgr.getResourceId(resourceIdStr, resourceType);
if (resourceId == null) {
throw new InvalidParameterValueException("Cannot find resource with resourceId " + resourceIdStr + " and of resource type " + resourceType);
}
}
if (resourceId == null) {
throw new InvalidParameterValueException("Cannot find resource with resourceId " + resourceIdStr + " and of resource type " + resourceType);
}
List<? extends ResourceDetail> detailList = new ArrayList<ResourceDetail>();
ResourceDetail requestedDetail = null;
if (key == null) {
detailList = _resourceMetaDataMgr.getDetailsList(resourceId, resourceType, forDisplay);
} else {
} else if (value == null){
requestedDetail = _resourceMetaDataMgr.getDetail(resourceId, resourceType, key);
if (requestedDetail != null && forDisplay != null && requestedDetail.isDisplay() != forDisplay) {
requestedDetail = null;
}
}else {
detailList = _resourceMetaDataMgr.getDetails(resourceType, key, value, forDisplay);
}
List<ResourceDetailResponse> responseList = new ArrayList<ResourceDetailResponse>();

View File

@ -22,13 +22,12 @@ import java.util.List;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.ResponseObject.ResponseView;
import org.apache.cloudstack.api.response.VolumeResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.ApiResponseHelper;
@ -152,19 +151,28 @@ public class VolumeJoinDaoImpl extends GenericDaoBase<VolumeJoinVO, Long> implem
// DiskOfferingVO diskOffering =
// ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId());
if (volume.getDiskOfferingId() > 0) {
boolean isServiceOffering = false;
if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
volResponse.setServiceOfferingId(volume.getDiskOfferingUuid());
isServiceOffering = true;
} else {
volResponse.setDiskOfferingId(volume.getDiskOfferingUuid());
// can't rely on the fact that the volume is the datadisk as it might have been created as a root, and
// then detached later
long offeringId = volume.getDiskOfferingId();
if (ApiDBUtils.findDiskOfferingById(offeringId) == null) {
isServiceOffering = true;
}
}
if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
if (isServiceOffering) {
volResponse.setServiceOfferingId(volume.getDiskOfferingUuid());
volResponse.setServiceOfferingName(volume.getDiskOfferingName());
volResponse.setServiceOfferingDisplayText(volume.getDiskOfferingDisplayText());
} else {
volResponse.setDiskOfferingId(volume.getDiskOfferingUuid());
volResponse.setDiskOfferingName(volume.getDiskOfferingName());
volResponse.setDiskOfferingDisplayText(volume.getDiskOfferingDisplayText());
}
volResponse.setStorageType(volume.isUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString());
volResponse.setBytesReadRate(volume.getBytesReadRate());
volResponse.setBytesWriteRate(volume.getBytesReadRate());

View File

@ -701,7 +701,7 @@ public enum Config {
"system.vm.use.local.storage",
"false",
"Indicates whether to use local storage pools or shared storage pools for system VMs.",
null),
null, ConfigKey.Scope.Zone.toString()),
SystemVMAutoReserveCapacity(
"Advanced",
ManagementServer.class,

View File

@ -954,9 +954,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
}
// Check if the IP range is valid
if (startIp != null || endIp != null) {
checkIpRange(startIp, endIp, cidrAddress, cidrSize);
}
checkIpRange(startIp, endIp, cidrAddress, cidrSize);
// Check if the IP range overlaps with the public ip
checkOverlapPublicIpRange(zoneId, startIp, endIp);
@ -1016,7 +1014,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
// Delete private ip addresses for the pod if there are any
List<DataCenterIpAddressVO> privateIps = _privateIpAddressDao.listByPodIdDcId(Long.valueOf(podId), pod.getDataCenterId());
List<DataCenterIpAddressVO> privateIps = _privateIpAddressDao.listByPodIdDcId(podId, pod.getDataCenterId());
if (!privateIps.isEmpty()) {
if (!(_privateIpAddressDao.deleteIpAddressByPod(podId))) {
throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId);
@ -1517,13 +1515,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
@ActionEvent(eventType = EventTypes.EVENT_ZONE_DELETE, eventDescription = "deleting zone", async = false)
public boolean deleteZone(DeleteZoneCmd cmd) {
Long userId = CallContext.current().getCallingUserId();
final Long zoneId = cmd.getId();
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
// Make sure the zone exists
if (!validZone(zoneId)) {
throw new InvalidParameterValueException("A zone with ID: " + zoneId + " does not exist.");
@ -2044,7 +2037,6 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
}
} else {
allowNetworkRate = true;
;
}
if (cmd.getNetworkRate() != null && !allowNetworkRate) {

View File

@ -197,6 +197,8 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy
@Inject
protected StoragePoolHostDao _poolHostDao;
@Inject
protected DataCenterDao _zoneDao;
@Inject
protected VolumeDao _volsDao;
@Inject
@ -1270,7 +1272,18 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy
boolean useLocalStorage = false;
if (vmProfile.getType() != VirtualMachine.Type.User) {
String ssvmUseLocalStorage = _configDao.getValue(Config.SystemVMUseLocalStorage.key());
if (ssvmUseLocalStorage.equalsIgnoreCase("true")) {
DataCenterVO zone = _zoneDao.findById(plan.getDataCenterId());
// It should not happen to have a "null" zone here. There can be NO instance if there is NO zone,
// so this part of the code would never be reached if no zone has been created.
//
// Added the check and the comment just to make it clear.
boolean zoneUsesLocalStorage = zone != null ? zone.isLocalStorageEnabled() : false;
// Local storage is used for the NON User VMs if, and only if, the Zone is marked to use local storage AND
// the global settings (ssvmUseLocalStorage) is set to true. Otherwise, the global settings won't be applied.
if (ssvmUseLocalStorage.equalsIgnoreCase("true") && zoneUsesLocalStorage) {
useLocalStorage = true;
}
} else {

View File

@ -224,6 +224,10 @@ public class ResourceMetaDataManagerImpl extends ManagerBase implements Resource
return dao.findDetail(resourceId, key);
}
private List<? extends ResourceDetail> getDetails(String key, String value, Boolean forDisplay) {
return dao.findDetails(key, value, forDisplay);
}
private void addDetail(long resourceId, String key, String value, boolean forDisplay) {
dao.addDetail(resourceId, key, value, forDisplay);
}
@ -257,6 +261,12 @@ public class ResourceMetaDataManagerImpl extends ManagerBase implements Resource
return newDetailDaoHelper.getDetail(resourceId, key);
}
@Override
public List<? extends ResourceDetail> getDetails(ResourceObjectType resourceType, String key, String value, Boolean forDisplay){
DetailDaoHelper newDetailDaoHelper = new DetailDaoHelper(resourceType);
return newDetailDaoHelper.getDetails(key, value, forDisplay);
}
@Override
public Map<String, String> getDetailsMap(long resourceId, ResourceObjectType resourceType, Boolean forDisplay) {
DetailDaoHelper newDetailDaoHelper = new DetailDaoHelper(resourceType);

View File

@ -736,6 +736,31 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel {
return networks.get(0);
}
@Override
public NetworkVO getNetworkWithSGWithFreeIPs(Long zoneId) {
List<NetworkVO> networks = _networksDao.listByZoneSecurityGroup(zoneId);
if (networks == null || networks.isEmpty()) {
return null;
}
NetworkVO ret_network = null;
for (NetworkVO nw : networks) {
List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(nw.getId());
for (VlanVO vlan : vlans) {
if (_ipAddressDao.countFreeIpsInVlan(vlan.getId()) > 0) {
ret_network = nw;
break;
}
}
if (ret_network != null) {
break;
}
}
if (ret_network == null) {
s_logger.debug("Can not find network with security group enabled with free IPs");
}
return ret_network;
}
@Override
public NetworkVO getNetworkWithSecurityGroupEnabled(Long zoneId) {
List<NetworkVO> networks = _networksDao.listByZoneSecurityGroup(zoneId);

View File

@ -1265,7 +1265,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
NicProfile privateNicProfile = new NicProfile();
if (privateNic != null) {
VirtualMachine vm = _vmDao.findById(privateNic.getId());
VirtualMachine vm = _vmDao.findById(privateNic.getInstanceId());
privateNicProfile =
new NicProfile(privateNic, privateNetwork, privateNic.getBroadcastUri(), privateNic.getIsolationUri(), _networkModel.getNetworkRate(
privateNetwork.getId(), vm.getId()), _networkModel.isSecurityGroupSupportedInNetwork(privateNetwork), _networkModel.getNetworkTag(

View File

@ -23,15 +23,14 @@ import java.util.List;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManager;
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.agent.AgentManager;
import com.cloud.agent.api.Answer;
@ -362,10 +361,16 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
// if the instance is of type user vm, call the user vm manager
if (vmInstance.getType().equals(VirtualMachine.Type.User)) {
UserVmVO userVm = userVmDao.findById(vmInstance.getId());
vmMgr.advanceStart(userVm.getUuid(), null, null); // update work queue
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
// check if the vm has a root volume. If not, remove the item from the queue, the vm should be
// started only when it has at least one root volume attached to it
// don't allow to start vm that doesn't have a root volume
if (volumeDao.findByInstanceAndType(work.getId(), Volume.Type.ROOT).isEmpty()) {
_storagePoolWorkDao.remove(work.getId());
} else {
vmMgr.advanceStart(userVm.getUuid(), null, null);
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
}
return true;
} catch (Exception e) {

View File

@ -254,12 +254,13 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
String volumeName = cmd.getVolumeName();
String url = cmd.getUrl();
String format = cmd.getFormat();
Long diskOfferingId = cmd.getDiskOfferingId();
String imageStoreUuid = cmd.getImageStoreUuid();
DataStore store = _tmpltMgr.getImageStore(imageStoreUuid, zoneId);
validateVolume(caller, ownerId, zoneId, volumeName, url, format);
validateVolume(caller, ownerId, zoneId, volumeName, url, format, diskOfferingId);
VolumeVO volume = persistVolume(owner, zoneId, volumeName, url, cmd.getFormat());
VolumeVO volume = persistVolume(owner, zoneId, volumeName, url, cmd.getFormat(), diskOfferingId);
VolumeInfo vol = volFactory.getVolume(volume.getId());
@ -270,13 +271,15 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
return volume;
}
private boolean validateVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url, String format) throws ResourceAllocationException {
private boolean validateVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url,
String format, Long diskOfferingId) throws ResourceAllocationException {
// permission check
_accountMgr.checkAccess(caller, null, true, _accountMgr.getActiveAccountById(ownerId));
Account volumeOwner = _accountMgr.getActiveAccountById(ownerId);
_accountMgr.checkAccess(caller, null, true, volumeOwner);
// Check that the resource limit for volumes won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.volume);
_resourceLimitMgr.checkResourceLimit(volumeOwner, ResourceType.volume);
// Verify that zone exists
DataCenterVO zone = _dcDao.findById(zoneId);
@ -323,9 +326,28 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
}
UriUtils.validateUrl(url);
// Check that the resource limit for secondary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
// Check that the the disk offering specified is valid
if (diskOfferingId != null) {
DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
if ((diskOffering == null) || diskOffering.getRemoved() != null
|| !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) {
throw new InvalidParameterValueException("Please specify a valid disk offering.");
}
if (!diskOffering.isCustomized()) {
throw new InvalidParameterValueException("Please specify a custom sized disk offering.");
}
if (diskOffering.getDomainId() == null) {
// do nothing as offering is public
} else {
_configMgr.checkDiskOfferingAccess(volumeOwner, diskOffering);
}
}
return false;
}
@ -334,7 +356,8 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
}
@DB
protected VolumeVO persistVolume(final Account owner, final Long zoneId, final String volumeName, final String url, final String format) {
protected VolumeVO persistVolume(final Account owner, final Long zoneId, final String volumeName, final String url,
final String format, final Long diskOfferingId) {
return Transaction.execute(new TransactionCallback<VolumeVO>() {
@Override
public VolumeVO doInTransaction(TransactionStatus status) {
@ -346,8 +369,13 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
// TODO Decide if this is valid or whether throwing a CloudRuntimeException is more appropriate
volume.setAccountId((owner == null) ? Account.ACCOUNT_ID_SYSTEM : owner.getAccountId());
volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner.getDomainId());
long diskOfferingId = _diskOfferingDao.findByUniqueName("Cloud.com-Custom").getId();
volume.setDiskOfferingId(diskOfferingId);
if (diskOfferingId == null) {
long defaultDiskOfferingId = _diskOfferingDao.findByUniqueName("Cloud.com-Custom").getId();
volume.setDiskOfferingId(defaultDiskOfferingId);
} else {
volume.setDiskOfferingId(diskOfferingId);
}
// volume.setSize(size);
volume.setInstanceId(null);
volume.setUpdated(new Date());

View File

@ -16,8 +16,6 @@
// under the License.
package com.cloud.template;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
@ -130,20 +128,6 @@ public class HypervisorTemplateAdapter extends TemplateAdapterBase {
public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
TemplateProfile profile = super.prepare(cmd);
String url = profile.getUrl();
String path = null;
try {
URL str = new URL(url);
path = str.getPath();
} catch (MalformedURLException ex) {
throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is invalid");
}
try {
checkFormat(cmd.getFormat(), url);
} catch (InvalidParameterValueException ex) {
checkFormat(cmd.getFormat(), path);
}
UriUtils.validateUrl(url);
profile.setUrl(url);
// Check that the resource limit for secondary storage won't be exceeded

View File

@ -2358,7 +2358,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
// If no network is specified, find system security group enabled network
if (networkIdList == null || networkIdList.isEmpty()) {
Network networkWithSecurityGroup = _networkModel.getNetworkWithSecurityGroupEnabled(zone.getId());
Network networkWithSecurityGroup = _networkModel.getNetworkWithSGWithFreeIPs(zone.getId());
if (networkWithSecurityGroup == null) {
throw new InvalidParameterValueException("No network with security enabled is found in zone id=" + zone.getId());
}
@ -4670,10 +4670,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
} else {
newVol = volumeMgr.allocateDuplicateVolume(root, null);
}
// Save usage event and update resource count for user vm volumes
// 1. Save usage event and update resource count for user vm volumes
if (vm instanceof UserVm) {
_resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.volume);
}
//2. Create Usage event for the newly created volume
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, newVol.getAccountId(), newVol.getDataCenterId(), newVol.getId(), newVol.getName(), newVol.getDiskOfferingId(), templateId, newVol.getSize());
_usageEventDao.persist(usageEvent);
handleManagedStorage(vm, root);

View File

@ -227,6 +227,15 @@ public class MockNetworkModelImpl extends ManagerBase implements NetworkModel {
return false;
}
/* (non-Javadoc)
* @see com.cloud.network.NetworkModel#getNetworkWithSGWithFreeIPs(java.lang.Long)
*/
@Override
public NetworkVO getNetworkWithSGWithFreeIPs(Long zoneId) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.cloud.network.NetworkModel#getNetworkWithSecurityGroupEnabled(java.lang.Long)
*/

View File

@ -35,6 +35,7 @@ import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;
import com.cloud.event.dao.UsageEventDao;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
@ -145,6 +146,8 @@ public class UserVmManagerTest {
ResourceLimitService _resourceLimitMgr;
@Mock
PrimaryDataStoreDao _storagePoolDao;
@Mock
UsageEventDao _usageEventDao;
@Before
public void setup() {
@ -154,6 +157,7 @@ public class UserVmManagerTest {
_userVmMgr._vmInstanceDao = _vmInstanceDao;
_userVmMgr._templateDao = _templateDao;
_userVmMgr._volsDao = _volsDao;
_userVmMgr._usageEventDao = _usageEventDao;
_userVmMgr._itMgr = _itMgr;
_userVmMgr.volumeMgr = _storageMgr;
_userVmMgr._accountDao = _accountDao;

View File

@ -238,6 +238,15 @@ public class MockNetworkModelImpl extends ManagerBase implements NetworkModel {
return (_ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(networkOfferingId, services));
}
/* (non-Javadoc)
* @see com.cloud.network.NetworkModel#getNetworkWithSGWithFreeIPs(java.lang.Long)
*/
@Override
public NetworkVO getNetworkWithSGWithFreeIPs(Long zoneId) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.cloud.network.NetworkModel#getNetworkWithSecurityGroupEnabled(java.lang.Long)
*/

View File

@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloudstack-service-console-proxy</artifactId>
<version>4.4.0-SNAPSHOT</version>
<version>4.4.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
</project>

View File

@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloudstack-service-iam</artifactId>
<version>4.4.0-SNAPSHOT</version>
<version>4.4.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloudstack-services</artifactId>
<version>4.4.0-SNAPSHOT</version>
<version>4.4.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<build>

View File

@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloudstack-service-iam</artifactId>
<version>4.4.0-SNAPSHOT</version>
<version>4.4.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>

View File

@ -106,7 +106,10 @@ CREATE TABLE `simulator`.`mockconfiguration` (
`cluster_id` bigint unsigned,
`host_id` bigint unsigned,
`name` varchar(255),
`values` varchar(4095),
`values` varchar(4096),
`count` int,
`json_response` varchar(4096),
`removed` datetime,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@ -17,12 +17,27 @@
# under the License.
STRIKE_FILE="[RROUTER_BIN_PATH]/keepalived.strikes"
if [ -e [RROUTER_BIN_PATH]/keepalived.ts2 ]
then
lasttime=$(cat [RROUTER_BIN_PATH]/keepalived.ts2)
thistime=$(cat [RROUTER_BIN_PATH]/keepalived.ts)
diff=$(($thistime - $lasttime))
s=0
if [ $diff -lt 30 ]
then
if [ -e $STRIKE_FILE ]
then
s=`cat $STRIKE_FILE 2>/dev/null`
fi
s=$(($s+1))
echo $s > $STRIKE_FILE
else
rm $STRIKE_FILE
fi
#3 strikes rule
if [ $s -gt 2 ]
then
echo Keepalived process is dead! >> [RROUTER_LOG]
[RROUTER_BIN_PATH]/services.sh stop >> [RROUTER_LOG] 2>&1

View File

@ -23,9 +23,9 @@ from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.sshClient import SshClient
from marvin.integration.lib.utils import *
from marvin.integration.lib.base import *
from marvin.integration.lib.common import *
from marvin.lib.utils import *
from marvin.lib.base import *
from marvin.lib.common import *
#Import System modules
import time
@ -100,19 +100,17 @@ class TestEgressAfterHostMaintenance(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.services = Services().services
cls.api_client = super(
TestEgressAfterHostMaintenance,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestEgressAfterHostMaintenance, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
cls.pod = get_pod(
cls.api_client,
zoneid=cls.zone.id
zone_id=cls.zone.id
)
template = get_template(

View File

@ -23,9 +23,9 @@ import marvin
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.integration.lib.utils import *
from marvin.integration.lib.base import *
from marvin.integration.lib.common import *
from marvin.lib.utils import *
from marvin.lib.base import *
from marvin.lib.common import *
from marvin.sshClient import SshClient
import datetime
@ -107,24 +107,16 @@ class TestHighAvailability(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.api_client = super(
TestHighAvailability,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestHighAvailability, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(
cls.api_client,
cls.services
)
cls.zone = get_zone(
cls.api_client,
cls.services
)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.pod = get_pod(
cls.api_client,
zoneid=cls.zone.id,
services=cls.services
zone_id=cls.zone.id
)
cls.template = get_template(
cls.api_client,

View File

@ -21,9 +21,10 @@
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.integration.lib.utils import *
from marvin.integration.lib.base import *
from marvin.integration.lib.common import *
from marvin.lib.utils import *
from marvin.lib.base import *
from marvin.lib.common import *
import time
class Services:
@ -76,20 +77,13 @@ class TestHostHighAvailability(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.api_client = super(
TestHostHighAvailability,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestHostHighAvailability, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(
cls.api_client,
cls.services
)
cls.zone = get_zone(
cls.api_client,
cls.services
)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
@ -626,11 +620,7 @@ class TestHostHighAvailability(cloudstackTestCase):
#verify the VM live migration happened to another running host
self.debug("Waiting for VM to come up")
wait_for_vm(
self.apiclient,
virtualmachineid=vm_with_ha_enabled.id,
interval=timeout
)
time.sleep(timeout)
vms = VirtualMachine.list(
self.apiclient,
@ -758,11 +748,7 @@ class TestHostHighAvailability(cloudstackTestCase):
#verify the VM live migration happened to another running host
self.debug("Waiting for VM to come up")
wait_for_vm(
self.apiclient,
virtualmachineid=vm_with_ha_disabled.id,
interval=timeout
)
time.sleep(timeout)
vms = VirtualMachine.list(
self.apiclient,

View File

@ -18,10 +18,10 @@
"""
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.cloudstackException import cloudstackAPIException
from marvin.integration.lib.utils import *
from marvin.integration.lib.base import *
from marvin.integration.lib.common import *
from marvin.cloudstackException import CloudstackAPIException
from marvin.lib.utils import *
from marvin.lib.base import *
from marvin.lib.common import *
# from netaddr import *
import netaddr
from nose.plugins.attrib import attr
@ -87,13 +87,15 @@ class TestMultipleIpRanges(cloudstackTestCase):
"""
@classmethod
def setUpClass(cls):
cls.api_client = super(TestMultipleIpRanges, cls).getClsTestClient().getApiClient()
cls.dbclient = super(TestMultipleIpRanges, cls).getClsTestClient().getDbConnection()
cls.testClient = super(TestEgressAfterHostMaintenance, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.dbclient = cls.testClient.getDbConnection()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.pod = get_pod(cls.api_client, cls.zone.id, cls.services)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.pod = get_pod(cls.api_client, cls.zone.id)
cls.services['mode'] = cls.zone.networktype
cls.services["domainid"] = cls.domain.id
cls.services["zoneid"] = cls.zone.id

View File

@ -16,9 +16,9 @@
# under the License.
from nose.plugins.attrib import attr
from marvin.integration.lib.base import *
from marvin.integration.lib.utils import *
from marvin.integration.lib.common import *
from marvin.lib.base import *
from marvin.lib.utils import *
from marvin.lib.common import *
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
@ -137,14 +137,13 @@ class TestCreateRvRNetworkOffering(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.api_client = super(
TestCreateRvRNetworkOffering,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestCreateRvRNetworkOffering, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls._cleanup = []
return
@ -231,14 +230,13 @@ class TestCreateRvRNetwork(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.api_client = super(
TestCreateRvRNetwork,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestCreateRvRNetwork, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
@ -433,14 +431,13 @@ class TestCreateRvRNetworkNonDefaultGuestCidr(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.api_client = super(
TestCreateRvRNetworkNonDefaultGuestCidr,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestCreateRvRNetworkNonDefaultGuestCidr, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
@ -642,14 +639,13 @@ class TestRVRInternals(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.api_client = super(
TestRVRInternals,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestRVRInternals, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
@ -685,6 +681,7 @@ class TestRVRInternals(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.hypervisor = self.testClient.getHypervisorInfo()
self.dbclient = self.testClient.getDbConnection()
self.account = Account.create(
self.apiclient,
@ -846,7 +843,7 @@ class TestRVRInternals(cloudstackTestCase):
self.debug(master_router.linklocalip)
# Check eth2 port for master router
if self.apiclient.hypervisor.lower() == 'vmware':
if self.hypervisor.lower() == 'vmware':
result = get_process_status(
self.apiclient.connection.mgtSvr,
22,
@ -854,7 +851,7 @@ class TestRVRInternals(cloudstackTestCase):
self.apiclient.connection.passwd,
master_router.linklocalip,
'ip addr show eth2',
hypervisor=self.apiclient.hypervisor
hypervisor=self.hypervisor
)
else:
result = get_process_status(
@ -882,7 +879,7 @@ class TestRVRInternals(cloudstackTestCase):
)
# Check eth2 port for backup router
if self.apiclient.hypervisor.lower() == 'vmware':
if self.hypervisor.lower() == 'vmware':
result = get_process_status(
self.apiclient.connection.mgtSvr,
22,
@ -890,7 +887,7 @@ class TestRVRInternals(cloudstackTestCase):
self.apiclient.connction.passwd,
backup_router.linklocalip,
'ip addr show eth2',
hypervisor=self.apiclient.hypervisor
hypervisor=self.hypervisor
)
else:
result = get_process_status(
@ -945,14 +942,13 @@ class TestRvRRedundancy(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.api_client = super(
TestRvRRedundancy,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestRvRRedundancy, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,

View File

@ -16,9 +16,9 @@
# under the License.
from nose.plugins.attrib import attr
from marvin.integration.lib.base import *
from marvin.integration.lib.utils import *
from marvin.integration.lib.common import *
from marvin.lib.base import *
from marvin.lib.utils import *
from marvin.lib.common import *
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
@ -136,14 +136,13 @@ class TestRvRDeploymentPlanning(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.api_client = super(
TestRvRDeploymentPlanning,
cls
).getClsTestClient().getApiClient()
cls.testClient = super(TestRvRDeploymentPlanning, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,

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