suspend/resume

This commit is contained in:
Adrian Cole 2010-10-31 11:38:01 -07:00
parent ad61d6e071
commit fc596fb5ce
39 changed files with 518 additions and 508 deletions

View File

@ -56,6 +56,8 @@ import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.compute.util.ComputeUtils; import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
@ -82,16 +84,19 @@ public class EC2ComputeService extends BaseComputeService {
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy, @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
ResumeNodeStrategy startNodeStrategy, SuspendNodeStrategy stopNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider, Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning, @Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils, Timeouts timeouts, @Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated,
@Named("NODE_SUSPENDED") Predicate<NodeMetadata> nodeSuspended, ComputeUtils utils, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client,
Map<RegionAndName, KeyPair> credentialsMap, @Named("SECURITY") Map<RegionAndName, String> securityGroupMap, Map<RegionAndName, KeyPair> credentialsMap, @Named("SECURITY") Map<RegionAndName, String> securityGroupMap,
@Named("PLACEMENT") Map<RegionAndName, String> placementGroupMap, @Named("PLACEMENT") Map<RegionAndName, String> placementGroupMap,
@Named("DELETED") Predicate<PlacementGroup> placementGroupDeleted) { @Named("DELETED") Predicate<PlacementGroup> placementGroupDeleted) {
super(context, credentialStore, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, super(context, credentialStore, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy,
runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, startNodeStrategy,
templateOptionsProvider, nodeRunning, nodeTerminated, utils, timeouts, executor); stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning, nodeTerminated,
nodeSuspended, utils, timeouts, executor);
this.ec2Client = ec2Client; this.ec2Client = ec2Client;
this.credentialsMap = credentialsMap; this.credentialsMap = credentialsMap;
this.securityGroupMap = securityGroupMap; this.securityGroupMap = securityGroupMap;

View File

@ -24,6 +24,8 @@ import org.jclouds.aws.ec2.compute.strategy.EC2GetNodeMetadataStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2ListNodesStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2ListNodesStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2RebootNodeStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2RebootNodeStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2RunNodesAndAddToSetStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2RunNodesAndAddToSetStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2ResumeNodeStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2SuspendNodeStrategy;
import org.jclouds.compute.config.BindComputeStrategiesByClass; import org.jclouds.compute.config.BindComputeStrategiesByClass;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy; import org.jclouds.compute.strategy.DestroyNodeStrategy;
@ -31,6 +33,8 @@ import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -76,4 +80,14 @@ public class EC2BindComputeStrategiesByClass extends BindComputeStrategiesByClas
return EC2RebootNodeStrategy.class; return EC2RebootNodeStrategy.class;
} }
@Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return EC2ResumeNodeStrategy.class;
}
@Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return EC2SuspendNodeStrategy.class;
}
} }

View File

@ -234,6 +234,30 @@ See http://code.google.com/p/jclouds for details."
([id #^ComputeService compute] ([id #^ComputeService compute]
(.getNodeMetadata compute id))) (.getNodeMetadata compute id)))
(defn suspend-nodes-with-tag
"Reboot all the nodes with the given tag."
([tag] (suspend-nodes-with-tag tag *compute*))
([#^String tag #^ComputeService compute]
(.suspendNodesMatching compute (NodePredicates/withTag tag))))
(defn suspend-node
"Suspend a node, given its id."
([id] (suspend-node id *compute*))
([id #^ComputeService compute]
(.suspendNode compute id)))
(defn resume-nodes-with-tag
"Suspend all the nodes with the given tag."
([tag] (resume-nodes-with-tag tag *compute*))
([#^String tag #^ComputeService compute]
(.resumeNodesMatching compute (NodePredicates/withTag tag))))
(defn resume-node
"Resume a node, given its id."
([id] (resume-node id *compute*))
([id #^ComputeService compute]
(.resumeNode compute id)))
(defn reboot-nodes-with-tag (defn reboot-nodes-with-tag
"Reboot all the nodes with the given tag." "Reboot all the nodes with the given tag."
([tag] (reboot-nodes-with-tag tag *compute*)) ([tag] (reboot-nodes-with-tag tag *compute*))

View File

@ -52,6 +52,10 @@
(^void destroyNode [this ^String id] (^void destroyNode [this ^String id]
()) ())
(^void rebootNode [this ^String id] (^void rebootNode [this ^String id]
())
(^void suspendNode [this ^String id]
())
(^void resumeNode [this ^String id]
())))) ()))))
(defn compute-context [^RestContextSpec spec] (defn compute-context [^RestContextSpec spec]

View File

@ -63,52 +63,48 @@ public interface ComputeService {
TemplateOptions templateOptions(); TemplateOptions templateOptions();
/** /**
* The list hardware profiles command shows you the options including virtual cpu count, * The list hardware profiles command shows you the options including virtual cpu count, memory,
* memory, and disks. cpu count is not a portable quantity across clouds, as * and disks. cpu count is not a portable quantity across clouds, as they are measured
* they are measured differently. However, it is a good indicator of relative * differently. However, it is a good indicator of relative speed within a cloud. memory is
* speed within a cloud. memory is measured in megabytes and disks in * measured in megabytes and disks in gigabytes.
* gigabytes.
* *
* @return a map of hardware profiles by ID, conceding that in some clouds the "id" is * @return a map of hardware profiles by ID, conceding that in some clouds the "id" is not used.
* not used.
*/ */
Set<? extends Hardware> listHardwareProfiles(); Set<? extends Hardware> listHardwareProfiles();
/** /**
* Images define the operating system and metadata related to a node. In some * Images define the operating system and metadata related to a node. In some clouds, Images are
* clouds, Images are bound to a specific region, and their identifiers are * bound to a specific region, and their identifiers are different across these regions. For this
* different across these regions. For this reason, you should consider * reason, you should consider matching image requirements like operating system family with
* matching image requirements like operating system family with * TemplateBuilder as opposed to choosing an image explicitly. The getImages() command returns a
* TemplateBuilder as opposed to choosing an image explicitly. The * map of images by id.
* getImages() command returns a map of images by id.
*/ */
Set<? extends Image> listImages(); Set<? extends Image> listImages();
/** /**
* all nodes available to the current user by id. If possible, the returned * all nodes available to the current user by id. If possible, the returned set will include
* set will include {@link NodeMetadata} objects. * {@link NodeMetadata} objects.
*/ */
Set<? extends ComputeMetadata> listNodes(); Set<? extends ComputeMetadata> listNodes();
/** /**
* The list locations command returns all the valid locations for nodes. A * The list locations command returns all the valid locations for nodes. A location has a scope,
* location has a scope, which is typically region or zone. A region is a * which is typically region or zone. A region is a general area, like eu-west, where a zone is
* general area, like eu-west, where a zone is similar to a datacenter. If a * similar to a datacenter. If a location has a parent, that implies it is within that location.
* location has a parent, that implies it is within that location. For * For example a location can be a rack, whose parent is likely to be a zone.
* example a location can be a rack, whose parent is likely to be a zone.
*/ */
Set<? extends Location> listAssignableLocations(); Set<? extends Location> listAssignableLocations();
/** /**
* *
* The compute api treats nodes as a group based on a tag you specify. Using * The compute api treats nodes as a group based on a tag you specify. Using this tag, you can
* this tag, you can choose to operate one or many nodes as a logical unit * choose to operate one or many nodes as a logical unit without regard to the implementation
* without regard to the implementation details of the cloud. * details of the cloud.
* <p/> * <p/>
* *
* The set that is returned will include credentials you can use to ssh into * The set that is returned will include credentials you can use to ssh into the nodes. The "key"
* the nodes. The "key" part of the credentials is either a password or a * part of the credentials is either a password or a private key. You have to inspect the value
* private key. You have to inspect the value to determine this. * to determine this.
* *
* <pre> * <pre>
* if (node.getCredentials().key.startsWith("-----BEGIN RSA PRIVATE KEY-----")) * if (node.getCredentials().key.startsWith("-----BEGIN RSA PRIVATE KEY-----"))
@ -116,11 +112,11 @@ public interface ComputeService {
* </pre> * </pre>
* *
* <p/> * <p/>
* Note. if all you want to do is execute a script at bootup, you should * Note. if all you want to do is execute a script at bootup, you should consider use of the
* consider use of the runscript option. * runscript option.
* <p/> * <p/>
* If resources such as security groups are needed, they will be reused or * If resources such as security groups are needed, they will be reused or created for you.
* created for you. Inbound port 22 will always be opened up. * Inbound port 22 will always be opened up.
* *
* @param tag * @param tag
* - common identifier to group nodes by, cannot contain hyphens * - common identifier to group nodes by, cannot contain hyphens
@ -131,38 +127,65 @@ public interface ComputeService {
* @return all of the nodes the api was able to launch in a running state. * @return all of the nodes the api was able to launch in a running state.
* *
* @throws RunNodesException * @throws RunNodesException
* when there's a problem applying options to nodes. Note that * when there's a problem applying options to nodes. Note that successful and failed
* successful and failed nodes are a part of this exception, so be * nodes are a part of this exception, so be sure to inspect this carefully.
* sure to inspect this carefully.
*/ */
Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, Template template) throws RunNodesException; Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, Template template) throws RunNodesException;
/** /**
* Like {@link ComputeService#runNodesWithTag(String,int,Template)}, except * Like {@link ComputeService#runNodesWithTag(String,int,Template)}, except that the template is
* that the template is default, equivalent to {@code * default, equivalent to {@code templateBuilder().any().options(templateOptions)}.
* templateBuilder().any().options(templateOptions)}.
*/ */
Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, TemplateOptions templateOptions) Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, TemplateOptions templateOptions)
throws RunNodesException; throws RunNodesException;
/** /**
* Like {@link ComputeService#runNodesWithTag(String,int,TemplateOptions)}, * Like {@link ComputeService#runNodesWithTag(String,int,TemplateOptions)}, except that the
* except that the options are default, as specified in * options are default, as specified in {@link ComputeService#templateOptions}.
* {@link ComputeService#templateOptions}.
*/ */
Set<? extends NodeMetadata> runNodesWithTag(String tag, int count) throws RunNodesException; Set<? extends NodeMetadata> runNodesWithTag(String tag, int count) throws RunNodesException;
/** /**
* destroy the node, given its id. If it is the only node in a tag set, the * resume the node from {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended} state,
* dependent resources will also be destroyed. * given its id.
*/
void resumeNode(String id);
/**
* nodes matching the filter are treated as a logical set. Using the resume command, you can save
* time by resumeing the nodes in parallel.
*
* @throws UnsupportedOperationException
* if the underlying provider doesn't support suspend/resume
*/
void resumeNodesMatching(Predicate<NodeMetadata> filter);
/**
* suspend the node, given its id. This will result in
* {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended} state.
*
* @throws UnsupportedOperationException
* if the underlying provider doesn't support suspend/resume
*/
void suspendNode(String id);
/**
* nodes matching the filter are treated as a logical set. Using the suspend command, you can
* save time by suspending the nodes in parallel.
*
*/
void suspendNodesMatching(Predicate<NodeMetadata> filter);
/**
* destroy the node, given its id. If it is the only node in a tag set, the dependent resources
* will also be destroyed.
*/ */
void destroyNode(String id); void destroyNode(String id);
/** /**
* nodes matching the filter are treated as a logical set. Using the delete * nodes matching the filter are treated as a logical set. Using the delete command, you can save
* command, you can save time by removing the nodes in parallel. When the * time by removing the nodes in parallel. When the last node in a set is destroyed, any indirect
* last node in a set is destroyed, any indirect resources it uses, such as * resources it uses, such as keypairs, are also destroyed.
* keypairs, are also destroyed.
* *
* @return list of nodes destroyed * @return list of nodes destroyed
*/ */
@ -174,8 +197,8 @@ public interface ComputeService {
void rebootNode(String id); void rebootNode(String id);
/** /**
* nodes matching the filter are treated as a logical set. Using this * nodes matching the filter are treated as a logical set. Using this command, you can save time
* command, you can save time by rebooting the nodes in parallel. * by rebooting the nodes in parallel.
*/ */
void rebootNodesMatching(Predicate<NodeMetadata> filter); void rebootNodesMatching(Predicate<NodeMetadata> filter);
@ -185,8 +208,8 @@ public interface ComputeService {
NodeMetadata getNodeMetadata(String id); NodeMetadata getNodeMetadata(String id);
/** /**
* get all nodes including details such as image and ip addresses even if it * get all nodes including details such as image and ip addresses even if it incurs extra
* incurs extra requests to the service. * requests to the service.
* *
* @param filter * @param filter
* how to select the nodes you are interested in details on. * how to select the nodes you are interested in details on.
@ -201,19 +224,17 @@ public interface ComputeService {
* @see org.jclouds.compute.predicates.NodePredicates#runningWithTag(String) * @see org.jclouds.compute.predicates.NodePredicates#runningWithTag(String)
*/ */
Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript) Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript)
throws RunScriptOnNodesException; throws RunScriptOnNodesException;
/** /**
* Run the script on all nodes with the specific tag. * Run the script on all nodes with the specific tag.
* *
* @param filter * @param filter
* Predicate-based filter to define on which nodes the script is to * Predicate-based filter to define on which nodes the script is to be executed
* be executed
* @param runScript * @param runScript
* payload containing the script to run * payload containing the script to run
* @param options * @param options
* nullable options to how to run the script, whether to override * nullable options to how to run the script, whether to override credentials
* credentials
* @return map with node identifiers and corresponding responses * @return map with node identifiers and corresponding responses
* @throws RunScriptOnNodesException * @throws RunScriptOnNodesException
* if anything goes wrong during script execution * if anything goes wrong during script execution
@ -222,6 +243,6 @@ public interface ComputeService {
* @see org.jclouds.io.Payloads * @see org.jclouds.io.Payloads
*/ */
Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter,
Payload runScript, RunScriptOptions options) throws RunScriptOnNodesException; Payload runScript, RunScriptOptions options) throws RunScriptOnNodesException;
} }

View File

@ -50,10 +50,10 @@ public interface ComputeServiceAdapter<N, H, I, L> {
* @param name * @param name
* unique supplied name for the node, which has the tag encoded into it. * unique supplied name for the node, which has the tag encoded into it.
* @param template * @param template
* includes {@code imageId}, {@code locationId}, and {@code hardwareId} used to start * includes {@code imageId}, {@code locationId}, and {@code hardwareId} used to resume
* the instance. * the instance.
* @param credentialStore * @param credentialStore
* once the node is started, its login user and password must be stored keyed on * once the node is resumeed, its login user and password must be stored keyed on
* {@code node#id}. * {@code node#id}.
* @return library-native representation of a node. * @return library-native representation of a node.
* *
@ -94,6 +94,10 @@ public interface ComputeServiceAdapter<N, H, I, L> {
void rebootNode(String id); void rebootNode(String id);
void resumeNode(String id);
void suspendNode(String id);
Iterable<N> listNodes(); Iterable<N> listNodes();
} }

View File

@ -25,6 +25,8 @@ import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.compute.strategy.impl.EncodeTagIntoNameRunNodesAndAddToSetStrategy; import org.jclouds.compute.strategy.impl.EncodeTagIntoNameRunNodesAndAddToSetStrategy;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
@ -42,6 +44,8 @@ public abstract class BindComputeStrategiesByClass extends AbstractModule {
bindListNodesStrategy(defineListNodesStrategy()); bindListNodesStrategy(defineListNodesStrategy());
bindGetNodeMetadataStrategy(defineGetNodeMetadataStrategy()); bindGetNodeMetadataStrategy(defineGetNodeMetadataStrategy());
bindRebootNodeStrategy(defineRebootNodeStrategy()); bindRebootNodeStrategy(defineRebootNodeStrategy());
bindStartNodeStrategy(defineStartNodeStrategy());
bindStopNodeStrategy(defineStopNodeStrategy());
bindDestroyNodeStrategy(defineDestroyNodeStrategy()); bindDestroyNodeStrategy(defineDestroyNodeStrategy());
} }
@ -64,6 +68,14 @@ public abstract class BindComputeStrategiesByClass extends AbstractModule {
bind(RebootNodeStrategy.class).to(clazz).in(Scopes.SINGLETON); bind(RebootNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
} }
protected void bindStartNodeStrategy(Class<? extends ResumeNodeStrategy> clazz) {
bind(ResumeNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindStopNodeStrategy(Class<? extends SuspendNodeStrategy> clazz) {
bind(SuspendNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindGetNodeMetadataStrategy(Class<? extends GetNodeMetadataStrategy> clazz) { protected void bindGetNodeMetadataStrategy(Class<? extends GetNodeMetadataStrategy> clazz) {
bind(GetNodeMetadataStrategy.class).to(clazz).in(Scopes.SINGLETON); bind(GetNodeMetadataStrategy.class).to(clazz).in(Scopes.SINGLETON);
} }
@ -85,6 +97,10 @@ public abstract class BindComputeStrategiesByClass extends AbstractModule {
protected abstract Class<? extends RebootNodeStrategy> defineRebootNodeStrategy(); protected abstract Class<? extends RebootNodeStrategy> defineRebootNodeStrategy();
protected abstract Class<? extends ResumeNodeStrategy> defineStartNodeStrategy();
protected abstract Class<? extends SuspendNodeStrategy> defineStopNodeStrategy();
protected abstract Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy(); protected abstract Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy();
protected abstract Class<? extends ListNodesStrategy> defineListNodesStrategy(); protected abstract Class<? extends ListNodesStrategy> defineListNodesStrategy();

View File

@ -26,6 +26,7 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodeRunning; import org.jclouds.compute.predicates.NodeRunning;
import org.jclouds.compute.predicates.NodeSuspended;
import org.jclouds.compute.predicates.NodeTerminated; import org.jclouds.compute.predicates.NodeTerminated;
import org.jclouds.compute.predicates.ScriptStatusReturnsZero; import org.jclouds.compute.predicates.ScriptStatusReturnsZero;
import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient; import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient;
@ -59,6 +60,15 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
timeouts.nodeTerminated); timeouts.nodeTerminated);
} }
@Provides
@Singleton
@Named("NODE_SUSPENDED")
protected Predicate<NodeMetadata> serverSuspended(NodeSuspended stateSuspended, Timeouts timeouts) {
return timeouts.nodeSuspended == 0 ? stateSuspended : new RetryablePredicate<NodeMetadata>(stateSuspended,
timeouts.nodeSuspended);
}
@Provides @Provides
@Singleton @Singleton
@Named("SCRIPT_COMPLETE") @Named("SCRIPT_COMPLETE")

View File

@ -38,6 +38,8 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.compute.strategy.impl.AdaptingComputeServiceStrategies; import org.jclouds.compute.strategy.impl.AdaptingComputeServiceStrategies;
import org.jclouds.compute.suppliers.DefaultLocationSupplier; import org.jclouds.compute.suppliers.DefaultLocationSupplier;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
@ -82,7 +84,7 @@ public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseCompu
@Provides @Provides
@Singleton @Singleton
protected Supplier<Set<? extends Hardware>> provideHardware(final ComputeServiceAdapter<N, H, I, L> adapter, protected Supplier<Set<? extends Hardware>> provideHardware(final ComputeServiceAdapter<N, H, I, L> adapter,
Function<H, Hardware> transformer) { Function<H, Hardware> transformer) {
return new TransformingSetSupplier<H, Hardware>(new Supplier<Iterable<H>>() { return new TransformingSetSupplier<H, Hardware>(new Supplier<Iterable<H>>() {
@Override @Override
@ -96,7 +98,7 @@ public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseCompu
@Provides @Provides
@Singleton @Singleton
protected Supplier<Set<? extends Image>> provideImages(final ComputeServiceAdapter<N, H, I, L> adapter, protected Supplier<Set<? extends Image>> provideImages(final ComputeServiceAdapter<N, H, I, L> adapter,
Function<I, Image> transformer) { Function<I, Image> transformer) {
return new TransformingSetSupplier<I, Image>(new Supplier<Iterable<I>>() { return new TransformingSetSupplier<I, Image>(new Supplier<Iterable<I>>() {
@Override @Override
@ -115,7 +117,7 @@ public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseCompu
@Provides @Provides
@Singleton @Singleton
protected Supplier<Set<? extends Location>> provideLocations(final ComputeServiceAdapter<N, H, I, L> adapter, protected Supplier<Set<? extends Location>> provideLocations(final ComputeServiceAdapter<N, H, I, L> adapter,
Function<L, Location> transformer) { Function<L, Location> transformer) {
return new TransformingSetSupplier<L, Location>(new Supplier<Iterable<L>>() { return new TransformingSetSupplier<L, Location>(new Supplier<Iterable<L>>() {
@Override @Override
@ -156,6 +158,18 @@ public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseCompu
return in; return in;
} }
@Provides
@Singleton
protected ResumeNodeStrategy defineStartNodeStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {
return in;
}
@Provides
@Singleton
protected SuspendNodeStrategy defineStopNodeStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {
return in;
}
// enum singleton pattern // enum singleton pattern
public static enum IdentityFunction implements Function<Object, Object> { public static enum IdentityFunction implements Function<Object, Object> {
INSTANCE; INSTANCE;

View File

@ -74,7 +74,9 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.compute.util.ComputeUtils; import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
@ -111,10 +113,13 @@ public class BaseComputeService implements ComputeService {
protected final RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy; protected final RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy;
protected final RebootNodeStrategy rebootNodeStrategy; protected final RebootNodeStrategy rebootNodeStrategy;
protected final DestroyNodeStrategy destroyNodeStrategy; protected final DestroyNodeStrategy destroyNodeStrategy;
protected final ResumeNodeStrategy resumeNodeStrategy;
protected final SuspendNodeStrategy suspendNodeStrategy;
protected final Provider<TemplateBuilder> templateBuilderProvider; protected final Provider<TemplateBuilder> templateBuilderProvider;
protected final Provider<TemplateOptions> templateOptionsProvider; protected final Provider<TemplateOptions> templateOptionsProvider;
protected final Predicate<NodeMetadata> nodeRunning; protected final Predicate<NodeMetadata> nodeRunning;
protected final Predicate<NodeMetadata> nodeTerminated; protected final Predicate<NodeMetadata> nodeTerminated;
protected final Predicate<NodeMetadata> nodeSuspended;
protected final ComputeUtils utils; protected final ComputeUtils utils;
protected final Timeouts timeouts; protected final Timeouts timeouts;
protected final ExecutorService executor; protected final ExecutorService executor;
@ -126,9 +131,11 @@ public class BaseComputeService implements ComputeService {
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy, @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
ResumeNodeStrategy resumeNodeStrategy, SuspendNodeStrategy suspendNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider, Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning, @Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils, Timeouts timeouts, @Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated,
@Named("NODE_SUSPENDED") Predicate<NodeMetadata> nodeSuspended, ComputeUtils utils, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.context = checkNotNull(context, "context"); this.context = checkNotNull(context, "context");
this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.credentialStore = checkNotNull(credentialStore, "credentialStore");
@ -139,11 +146,14 @@ public class BaseComputeService implements ComputeService {
this.getNodeMetadataStrategy = checkNotNull(getNodeMetadataStrategy, "getNodeMetadataStrategy"); this.getNodeMetadataStrategy = checkNotNull(getNodeMetadataStrategy, "getNodeMetadataStrategy");
this.runNodesAndAddToSetStrategy = checkNotNull(runNodesAndAddToSetStrategy, "runNodesAndAddToSetStrategy"); this.runNodesAndAddToSetStrategy = checkNotNull(runNodesAndAddToSetStrategy, "runNodesAndAddToSetStrategy");
this.rebootNodeStrategy = checkNotNull(rebootNodeStrategy, "rebootNodeStrategy"); this.rebootNodeStrategy = checkNotNull(rebootNodeStrategy, "rebootNodeStrategy");
this.resumeNodeStrategy = checkNotNull(resumeNodeStrategy, "resumeNodeStrategy");
this.suspendNodeStrategy = checkNotNull(suspendNodeStrategy, "suspendNodeStrategy");
this.destroyNodeStrategy = checkNotNull(destroyNodeStrategy, "destroyNodeStrategy"); this.destroyNodeStrategy = checkNotNull(destroyNodeStrategy, "destroyNodeStrategy");
this.templateBuilderProvider = checkNotNull(templateBuilderProvider, "templateBuilderProvider"); this.templateBuilderProvider = checkNotNull(templateBuilderProvider, "templateBuilderProvider");
this.templateOptionsProvider = checkNotNull(templateOptionsProvider, "templateOptionsProvider"); this.templateOptionsProvider = checkNotNull(templateOptionsProvider, "templateOptionsProvider");
this.nodeRunning = checkNotNull(nodeRunning, "nodeRunning"); this.nodeRunning = checkNotNull(nodeRunning, "nodeRunning");
this.nodeTerminated = checkNotNull(nodeTerminated, "nodeTerminated"); this.nodeTerminated = checkNotNull(nodeTerminated, "nodeTerminated");
this.nodeSuspended = checkNotNull(nodeSuspended, "nodeSuspended");
this.utils = checkNotNull(utils, "utils"); this.utils = checkNotNull(utils, "utils");
this.timeouts = checkNotNull(timeouts, "timeouts"); this.timeouts = checkNotNull(timeouts, "timeouts");
this.executor = checkNotNull(executor, "executor"); this.executor = checkNotNull(executor, "executor");
@ -174,7 +184,7 @@ public class BaseComputeService implements ComputeService {
Set<NodeMetadata> nodes = newHashSet(); Set<NodeMetadata> nodes = newHashSet();
Map<NodeMetadata, Exception> badNodes = newLinkedHashMap(); Map<NodeMetadata, Exception> badNodes = newLinkedHashMap();
Map<?, Future<Void>> responses = runNodesAndAddToSetStrategy.execute(tag, count, template, nodes, badNodes); Map<?, Future<Void>> responses = runNodesAndAddToSetStrategy.execute(tag, count, template, nodes, badNodes);
Map<?, Exception> executionExceptions = awaitCompletion(responses, executor, null, logger, "starting nodes"); Map<?, Exception> executionExceptions = awaitCompletion(responses, executor, null, logger, "resumeing nodes");
for (NodeMetadata node : concat(nodes, badNodes.keySet())) for (NodeMetadata node : concat(nodes, badNodes.keySet()))
if (node.getCredentials() != null) if (node.getCredentials() != null)
credentialStore.put("node#" + node.getId(), node.getCredentials()); credentialStore.put("node#" + node.getId(), node.getCredentials());
@ -357,6 +367,66 @@ public class BaseComputeService implements ComputeService {
logger.debug("<< rebooted"); logger.debug("<< rebooted");
} }
/**
* {@inheritDoc}
*/
@Override
public void resumeNode(String id) {
checkNotNull(id, "id");
logger.debug(">> resumeing node(%s)", id);
NodeMetadata node = resumeNodeStrategy.resumeNode(id);
boolean successful = nodeRunning.apply(node);
logger.debug("<< resumeed node(%s) success(%s)", id, successful);
}
/**
* {@inheritDoc}
*/
@Override
public void resumeNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> resumeing nodes matching(%s)", filter);
transformParallel(nodesMatchingFilterAndNotTerminated(filter), new Function<NodeMetadata, Future<Void>>() {
// TODO use native async
@Override
public Future<Void> apply(NodeMetadata from) {
resumeNode(from.getId());
return immediateFuture(null);
}
}, executor, null, logger, "resumeing nodes");
logger.debug("<< resumeed");
}
/**
* {@inheritDoc}
*/
@Override
public void suspendNode(String id) {
checkNotNull(id, "id");
logger.debug(">> suspendping node(%s)", id);
NodeMetadata node = suspendNodeStrategy.suspendNode(id);
boolean successful = nodeSuspended.apply(node);
logger.debug("<< suspendped node(%s) success(%s)", id, successful);
}
/**
* {@inheritDoc}
*/
@Override
public void suspendNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> suspending nodes matching(%s)", filter);
transformParallel(nodesMatchingFilterAndNotTerminated(filter), new Function<NodeMetadata, Future<Void>>() {
// TODO use native async
@Override
public Future<Void> apply(NodeMetadata from) {
suspendNode(from.getId());
return immediateFuture(null);
}
}, executor, null, logger, "suspending nodes");
logger.debug("<< suspended");
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */

View File

@ -19,52 +19,24 @@
package org.jclouds.compute.predicates; package org.jclouds.compute.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Resource;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeService;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
import com.google.inject.Inject; import com.google.inject.Inject;
/** /**
* *
* Tests to see if a node is active. * Tests to see if a node is running.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class NodeRunning implements Predicate<NodeMetadata> { public class NodeRunning extends NodePresentAndInIntendedState {
private final ComputeService client;
@Resource
protected Logger logger = Logger.NULL;
@Inject @Inject
public NodeRunning(ComputeService client) { public NodeRunning(ComputeService client) {
this.client = client; super(NodeState.RUNNING, client);
}
public boolean apply(NodeMetadata node) {
logger.trace("looking for state on node %s", checkNotNull(node, "node"));
node = refresh(node);
if (node == null)
return false;
logger.trace("%s: looking for node state %s: currently: %s",
node.getId(), NodeState.RUNNING, node.getState());
if (node.getState() == NodeState.ERROR)
throw new IllegalStateException("node " + node.getId()
+ " in location " + node.getLocation() + " is in error state");
return node.getState() == NodeState.RUNNING;
}
private NodeMetadata refresh(NodeMetadata node) {
return client.getNodeMetadata(node.getId());
} }
} }

View File

@ -34,6 +34,7 @@ public interface ComputeServiceConstants {
public static final String LOCAL_PARTITION_GB_PATTERN = "disk_drive/%s/gb"; public static final String LOCAL_PARTITION_GB_PATTERN = "disk_drive/%s/gb";
public static final String PROPERTY_TIMEOUT_NODE_TERMINATED = "jclouds.compute.timeout.node-terminated"; public static final String PROPERTY_TIMEOUT_NODE_TERMINATED = "jclouds.compute.timeout.node-terminated";
public static final String PROPERTY_TIMEOUT_NODE_RUNNING = "jclouds.compute.timeout.node-running"; public static final String PROPERTY_TIMEOUT_NODE_RUNNING = "jclouds.compute.timeout.node-running";
public static final String PROPERTY_TIMEOUT_NODE_SUSPENDED = "jclouds.compute.timeout.node-suspended";
public static final String PROPERTY_TIMEOUT_SCRIPT_COMPLETE = "jclouds.compute.timeout.script-complete"; public static final String PROPERTY_TIMEOUT_SCRIPT_COMPLETE = "jclouds.compute.timeout.script-complete";
public static final String PROPERTY_TIMEOUT_PORT_OPEN = "jclouds.compute.timeout.port-open"; public static final String PROPERTY_TIMEOUT_PORT_OPEN = "jclouds.compute.timeout.port-open";
/** /**
@ -52,6 +53,10 @@ public interface ComputeServiceConstants {
@Named(PROPERTY_TIMEOUT_NODE_RUNNING) @Named(PROPERTY_TIMEOUT_NODE_RUNNING)
public long nodeRunning = 1200 * 1000; public long nodeRunning = 1200 * 1000;
@Inject(optional = true)
@Named(PROPERTY_TIMEOUT_NODE_SUSPENDED)
public long nodeSuspended = 30 * 1000;
@Inject(optional = true) @Inject(optional = true)
@Named(PROPERTY_TIMEOUT_SCRIPT_COMPLETE) @Named(PROPERTY_TIMEOUT_SCRIPT_COMPLETE)
public long scriptComplete = 600 * 1000; public long scriptComplete = 600 * 1000;

View File

@ -41,6 +41,8 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
@ -54,7 +56,7 @@ import com.google.common.collect.Iterables;
*/ */
@Singleton @Singleton
public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWithTagStrategy, DestroyNodeStrategy, public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWithTagStrategy, DestroyNodeStrategy,
GetNodeMetadataStrategy, ListNodesStrategy, RebootNodeStrategy { GetNodeMetadataStrategy, ListNodesStrategy, RebootNodeStrategy, ResumeNodeStrategy, SuspendNodeStrategy {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@ -65,7 +67,7 @@ public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWith
@Inject @Inject
public AdaptingComputeServiceStrategies(Map<String, Credentials> credentialStore, public AdaptingComputeServiceStrategies(Map<String, Credentials> credentialStore,
ComputeServiceAdapter<N, H, I, L> client, Function<N, NodeMetadata> nodeMetadataAdapter) { ComputeServiceAdapter<N, H, I, L> client, Function<N, NodeMetadata> nodeMetadataAdapter) {
this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.client = checkNotNull(client, "client"); this.client = checkNotNull(client, "client");
this.nodeMetadataAdapter = checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter"); this.nodeMetadataAdapter = checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter");
@ -101,6 +103,34 @@ public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWith
return node; return node;
} }
@Override
public NodeMetadata resumeNode(String id) {
NodeMetadata node = getNode(id);
if (node == null || node.getState() == NodeState.TERMINATED || node.getState() == NodeState.RUNNING)
return node;
logger.debug(">> resuming node(%s)", id);
client.resumeNode(id);
logger.debug("<< resumed node(%s)", id);
return node;
}
@Override
public NodeMetadata suspendNode(String id) {
NodeMetadata node = getNode(id);
if (node == null || node.getState() == NodeState.TERMINATED || node.getState() == NodeState.SUSPENDED)
return node;
logger.debug(">> suspending node(%s)", id);
client.suspendNode(id);
logger.debug("<< suspended node(%s)", id);
return node;
}
@Override @Override
public NodeMetadata destroyNode(String id) { public NodeMetadata destroyNode(String id) {
@ -124,8 +154,8 @@ public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWith
checkState(name != null && name.indexOf(tag) != -1, "name should have %s encoded into it", tag); checkState(name != null && name.indexOf(tag) != -1, "name should have %s encoded into it", tag);
logger.debug(">> instantiating node location(%s) name(%s) image(%s) hardware(%s)", logger.debug(">> instantiating node location(%s) name(%s) image(%s) hardware(%s)",
template.getLocation().getId(), name, template.getImage().getProviderId(), template.getHardware() template.getLocation().getId(), name, template.getImage().getProviderId(), template.getHardware()
.getProviderId()); .getProviderId());
N from = client.runNodeWithTagAndNameAndStoreCredentials(tag, name, template, credentialStore); N from = client.runNodeWithTagAndNameAndStoreCredentials(tag, name, template, credentialStore);
NodeMetadata node = nodeMetadataAdapter.apply(from); NodeMetadata node = nodeMetadataAdapter.apply(from);

View File

@ -175,4 +175,30 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
StubComputeServiceDependenciesModule.setState(node, NodeState.PENDING, 0); StubComputeServiceDependenciesModule.setState(node, NodeState.PENDING, 0);
StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 50); StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 50);
} }
@Override
public void resumeNode(String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
throw new ResourceNotFoundException("node not found: " + id);
if (node.getState() == NodeState.RUNNING)
return;
if (node.getState() != NodeState.SUSPENDED)
throw new IllegalStateException("to resume a node, it must be in suspended state, not: " + node.getState());
StubComputeServiceDependenciesModule.setState(node, NodeState.PENDING, 0);
StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 50);
}
@Override
public void suspendNode(String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
throw new ResourceNotFoundException("node not found: " + id);
if (node.getState() == NodeState.SUSPENDED)
return;
if (node.getState() != NodeState.RUNNING)
throw new IllegalStateException("to suspend a node, it must be in running state, not: " + node.getState());
StubComputeServiceDependenciesModule.setState(node, NodeState.PENDING, 0);
StubComputeServiceDependenciesModule.setState(node, NodeState.SUSPENDED, 50);
}
} }

View File

@ -138,10 +138,10 @@ public class ComputeUtils {
"node didn't achieve the state running on node %s within %d seconds, final state: %s", node.getId(), "node didn't achieve the state running on node %s within %d seconds, final state: %s", node.getId(),
timeouts.nodeRunning / 1000, node.getState())); timeouts.nodeRunning / 1000, node.getState()));
List<Statement> bootstrap = newArrayList(); List<Statement> bootstrap = newArrayList();
if (options.getRunScript() != null)
bootstrap.add(options.getRunScript());
if (options.getPublicKey() != null) if (options.getPublicKey() != null)
bootstrap.add(new AuthorizeRSAPublicKey(options.getPublicKey())); bootstrap.add(new AuthorizeRSAPublicKey(options.getPublicKey()));
if (options.getRunScript() != null)
bootstrap.add(options.getRunScript());
if (options.getPrivateKey() != null) if (options.getPrivateKey() != null)
bootstrap.add(new InstallRSAPrivateKey(options.getPrivateKey())); bootstrap.add(new InstallRSAPrivateKey(options.getPrivateKey()));
if (bootstrap.size() >= 1) if (bootstrap.size() >= 1)

View File

@ -83,7 +83,9 @@ import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Module; import com.google.inject.Module;
@ -388,6 +390,28 @@ public abstract class BaseComputeServiceLiveTest {
testGet(); testGet();
} }
@Test(enabled = true, dependsOnMethods = "testReboot")
public void testSuspendResume() throws Exception {
client.suspendNodesMatching(withTag(tag));
Set<? extends NodeMetadata> stoppedNodes = refreshNodes();
assert Iterables.all(stoppedNodes, new Predicate<NodeMetadata>() {
@Override
public boolean apply(NodeMetadata input) {
return input.getState() == NodeState.SUSPENDED;
}
}) : nodes;
client.resumeNodesMatching(withTag(tag));
testGet();
}
private Set<? extends NodeMetadata> refreshNodes() {
return filter(client.listNodesDetailsMatching(all()), and(withTag(tag), not(TERMINATED)));
}
@Test(enabled = true) @Test(enabled = true)
public void testCreateAndRunAService() throws Exception { public void testCreateAndRunAService() throws Exception {
@ -572,7 +596,8 @@ public abstract class BaseComputeServiceLiveTest {
ExecResponse hello = ssh.exec("echo hello"); ExecResponse hello = ssh.exec("echo hello");
assertEquals(hello.getOutput().trim(), "hello"); assertEquals(hello.getOutput().trim(), "hello");
ExecResponse exec = ssh.exec("java -version"); ExecResponse exec = ssh.exec("java -version");
assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec; assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n"
+ ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log");
} finally { } finally {
if (ssh != null) if (ssh != null)
ssh.disconnect(); ssh.disconnect();

View File

@ -34,7 +34,6 @@ import java.util.concurrent.TimeoutException;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.predicates.OperatingSystemPredicates;
import org.jclouds.rest.HttpClient; import org.jclouds.rest.HttpClient;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
@ -49,14 +48,7 @@ import com.google.common.io.Files;
*/ */
public class ComputeTestUtils { public class ComputeTestUtils {
public static Statement buildScript(OperatingSystem os) { public static Statement buildScript(OperatingSystem os) {
if (OperatingSystemPredicates.supportsApt().apply(os)) return RunScriptData.installJavaAndCurl(os);
return RunScriptData.APT_RUN_SCRIPT;
else if (OperatingSystemPredicates.supportsYum().apply(os))
return RunScriptData.YUM_RUN_SCRIPT;
else if (OperatingSystemPredicates.supportsZypper().apply(os))
return RunScriptData.ZYPPER_RUN_SCRIPT;
else
throw new IllegalArgumentException("don't know how to handle" + os.toString());
} }
public static Map<String, String> setupKeyPair() throws FileNotFoundException, IOException { public static Map<String, String> setupKeyPair() throws FileNotFoundException, IOException {
@ -69,8 +61,8 @@ public class ComputeTestUtils {
checkSecretKeyFile(secretKeyFile); checkSecretKeyFile(secretKeyFile);
String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8); String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8);
assert secret.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + secret; assert secret.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + secret;
return ImmutableMap.<String, String> of("private", secret, "public", return ImmutableMap.<String, String> of("private", secret, "public", Files.toString(new File(secretKeyFile
Files.toString(new File(secretKeyFile + ".pub"), Charsets.UTF_8)); + ".pub"), Charsets.UTF_8));
} }
public static void checkSecretKeyFile(String secretKeyFile) throws FileNotFoundException { public static void checkSecretKeyFile(String secretKeyFile) throws FileNotFoundException {

View File

@ -70,7 +70,8 @@ public class RunScriptData {
// just in case iptables are being used, try to open 8080 // just in case iptables are being used, try to open 8080
exec("iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT"),// exec("iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT"),//
// TODO gogrid rules only allow ports 22, 3389, 80 and 443. // TODO gogrid rules only allow ports 22, 3389, 80 and 443.
// the above rule will be ignored, so we have to apply this directly // the above rule will be ignored, so we have to apply this
// directly
exec("iptables -I RH-Firewall-1-INPUT 1 -p tcp --dport 8080 -j ACCEPT"),// exec("iptables -I RH-Firewall-1-INPUT 1 -p tcp --dport 8080 -j ACCEPT"),//
exec("iptables-save"),// exec("iptables-save"),//
extractTargzIntoDirectory( extractTargzIntoDirectory(
@ -84,8 +85,15 @@ public class RunScriptData {
return toReturn; return toReturn;
} }
public static String aptInstall = "apt-get install -f -y -qq --force-yes";
public static String installAfterUpdatingIfNotPresent(String cmd) {
String aptInstallCmd = aptInstall + " " + cmd;
return String.format("which %s || (%s || (apt-get update && %s))", cmd, aptInstallCmd, aptInstallCmd);
}
public static final Statement APT_RUN_SCRIPT = newStatementList(// public static final Statement APT_RUN_SCRIPT = newStatementList(//
exec("which curl || apt-get install -f -y -qq --force-yes curl"),// exec(installAfterUpdatingIfNotPresent("curl")),//
exec("(which java && java -fullversion 2>&1|egrep -q 1.6 ) ||"),// exec("(which java && java -fullversion 2>&1|egrep -q 1.6 ) ||"),//
execHttpResponse(URI.create("http://whirr.s3.amazonaws.com/0.2.0-incubating-SNAPSHOT/sun/java/install")),// execHttpResponse(URI.create("http://whirr.s3.amazonaws.com/0.2.0-incubating-SNAPSHOT/sun/java/install")),//
exec(new StringBuilder()// exec(new StringBuilder()//

View File

@ -121,48 +121,48 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
SshClient client5 = createMock(SshClient.class); SshClient client5 = createMock(SshClient.class);
expect(factory.create(new IPSocket("144.175.1.1", 22), new Credentials("root", "password1"))).andReturn( expect(factory.create(new IPSocket("144.175.1.1", 22), new Credentials("root", "password1"))).andReturn(
client1); client1);
runScriptAndService(client1, 1); runScriptAndService(client1, 1);
expect(factory.create(new IPSocket("144.175.1.2", 22), new Credentials("root", "password2"))).andReturn( expect(factory.create(new IPSocket("144.175.1.2", 22), new Credentials("root", "password2"))).andReturn(
client2).times(2); client2).times(2);
expect(factory.create(new IPSocket("144.175.1.2", 22), new Credentials("root", "romeo"))).andThrow( expect(factory.create(new IPSocket("144.175.1.2", 22), new Credentials("root", "romeo"))).andThrow(
new SshException("Auth fail")); new SshException("Auth fail"));
client2.connect(); client2.connect();
try { try {
runScript(client2, "runScriptWithCreds", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class runScript(client2, "runScriptWithCreds", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
.getResourceAsStream("/runscript.sh")), 2); .getResourceAsStream("/runscript.sh")), 2);
} catch (IOException e) { } catch (IOException e) {
Throwables.propagate(e); Throwables.propagate(e);
} }
client2.disconnect(); client2.disconnect();
expect(factory.create(new IPSocket("144.175.1.3", 22), new Credentials("root", "password3"))).andReturn( expect(factory.create(new IPSocket("144.175.1.3", 22), new Credentials("root", "password3"))).andReturn(
client3).times(2); client3).times(2);
expect(factory.create(new IPSocket("144.175.1.4", 22), new Credentials("root", "password4"))).andReturn( expect(factory.create(new IPSocket("144.175.1.4", 22), new Credentials("root", "password4"))).andReturn(
client4).times(2); client4).times(2);
expect(factory.create(new IPSocket("144.175.1.5", 22), new Credentials("root", "password5"))).andReturn( expect(factory.create(new IPSocket("144.175.1.5", 22), new Credentials("root", "password5"))).andReturn(
client5).times(2); client5).times(2);
runScriptAndInstallSsh(client3, "bootstrap", 3); runScriptAndInstallSsh(client3, "bootstrap", 3);
runScriptAndInstallSsh(client4, "bootstrap", 4); runScriptAndInstallSsh(client4, "bootstrap", 4);
runScriptAndInstallSsh(client5, "bootstrap", 5); runScriptAndInstallSsh(client5, "bootstrap", 5);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.1", 22)), factory.create(eq(new IPSocket("144.175.1.1", 22)), eq(new Credentials("root", keyPair
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client1); .get("private"))))).andReturn(client1);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.2", 22)), factory.create(eq(new IPSocket("144.175.1.2", 22)), eq(new Credentials("root", keyPair
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client2); .get("private"))))).andReturn(client2);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.3", 22)), factory.create(eq(new IPSocket("144.175.1.3", 22)), eq(new Credentials("root", keyPair
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client3); .get("private"))))).andReturn(client3);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.4", 22)), factory.create(eq(new IPSocket("144.175.1.4", 22)), eq(new Credentials("root", keyPair
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client4); .get("private"))))).andReturn(client4);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.5", 22)), factory.create(eq(new IPSocket("144.175.1.5", 22)), eq(new Credentials("root", keyPair
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client5); .get("private"))))).andReturn(client5);
helloAndJava(client2); helloAndJava(client2);
helloAndJava(client3); helloAndJava(client3);
@ -184,7 +184,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
try { try {
runScript(client, "jboss", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class runScript(client, "jboss", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
.getResourceAsStream("/initscript_with_jboss.sh")), nodeId); .getResourceAsStream("/initscript_with_jboss.sh")), nodeId);
} catch (IOException e) { } catch (IOException e) {
Throwables.propagate(e); Throwables.propagate(e);
} }
@ -198,7 +198,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
try { try {
runScript(client, scriptName, Utils.toStringAndClose(StubComputeServiceIntegrationTest.class runScript(client, scriptName, Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
.getResourceAsStream("/initscript_with_java.sh")), nodeId); .getResourceAsStream("/initscript_with_java.sh")), nodeId);
} catch (IOException e) { } catch (IOException e) {
Throwables.propagate(e); Throwables.propagate(e);
} }
@ -251,7 +251,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
public void testAssignability() throws Exception { public void testAssignability() throws Exception {
@SuppressWarnings("unused") @SuppressWarnings("unused")
RestContext<ConcurrentMap<String, NodeMetadata>, ConcurrentMap<String, NodeMetadata>> stubContext = new ComputeServiceContextFactory() RestContext<ConcurrentMap<String, NodeMetadata>, ConcurrentMap<String, NodeMetadata>> stubContext = new ComputeServiceContextFactory()
.createContext(provider, identity, credential).getProviderSpecificContext(); .createContext(provider, identity, credential).getProviderSpecificContext();
} }
private static class PayloadEquals implements IArgumentMatcher, Serializable { private static class PayloadEquals implements IArgumentMatcher, Serializable {
@ -298,7 +298,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
return false; return false;
PayloadEquals other = (PayloadEquals) o; PayloadEquals other = (PayloadEquals) o;
return this.expected == null && other.expected == null || this.expected != null return this.expected == null && other.expected == null || this.expected != null
&& this.expected.equals(other.expected); && this.expected.equals(other.expected);
} }
@Override @Override
@ -361,6 +361,11 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
super.testReboot(); super.testReboot();
} }
@Test(enabled = true, dependsOnMethods = "testReboot")
public void testSuspendResume() throws Exception {
super.testSuspendResume();
}
@Test(enabled = true, dependsOnMethods = { "testImagesCache" }) @Test(enabled = true, dependsOnMethods = { "testImagesCache" })
public void testTemplateMatch() throws Exception { public void testTemplateMatch() throws Exception {
super.testTemplateMatch(); super.testTemplateMatch();

View File

@ -76,17 +76,17 @@ END_OF_SCRIPT
# add desired commands from the user # add desired commands from the user
cat >> $INSTANCE_HOME/bootstrap.sh <<'END_OF_SCRIPT' cat >> $INSTANCE_HOME/bootstrap.sh <<'END_OF_SCRIPT'
cd $INSTANCE_HOME cd $INSTANCE_HOME
which curl || apt-get install -f -y -qq --force-yes curl
(which java && java -fullversion 2>&1|egrep -q 1.6 ) ||
curl -X GET -s --retry 20 http://whirr.s3.amazonaws.com/0.2.0-incubating-SNAPSHOT/sun/java/install |(bash)
echo nameserver 208.67.222.222 >> /etc/resolv.conf
rm -rf /var/cache/apt /usr/lib/vmware-tools
echo "export PATH=\"\$JAVA_HOME/bin/:\$PATH\"" >> /root/.bashrc
mkdir -p ~/.ssh mkdir -p ~/.ssh
cat >> ~/.ssh/authorized_keys <<'END_OF_FILE' cat >> ~/.ssh/authorized_keys <<'END_OF_FILE'
ssh-rsa ssh-rsa
END_OF_FILE END_OF_FILE
chmod 600 ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys
which curl || (apt-get install -f -y -qq --force-yes curl || (apt-get update && apt-get install -f -y -qq --force-yes curl))
(which java && java -fullversion 2>&1|egrep -q 1.6 ) ||
curl -X GET -s --retry 20 http://whirr.s3.amazonaws.com/0.2.0-incubating-SNAPSHOT/sun/java/install |(bash)
echo nameserver 208.67.222.222 >> /etc/resolv.conf
rm -rf /var/cache/apt /usr/lib/vmware-tools
echo "export PATH=\"\$JAVA_HOME/bin/:\$PATH\"" >> /root/.bashrc
mkdir -p ~/.ssh mkdir -p ~/.ssh
rm ~/.ssh/id_rsa rm ~/.ssh/id_rsa
cat >> ~/.ssh/id_rsa <<'END_OF_FILE' cat >> ~/.ssh/id_rsa <<'END_OF_FILE'

View File

@ -63,7 +63,7 @@ init)
ssh-rsa ssh-rsa
END_OF_FILE END_OF_FILE
chmod 600 ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys
which curl || apt-get install -f -y -qq --force-yes curl which curl || (apt-get install -f -y -qq --force-yes curl || (apt-get update && apt-get install -f -y -qq --force-yes curl))
(which java && java -fullversion 2>&1|egrep -q 1.6 ) || (which java && java -fullversion 2>&1|egrep -q 1.6 ) ||
curl -X GET -s --retry 20 http://whirr.s3.amazonaws.com/0.2.0-incubating-SNAPSHOT/sun/java/install |(bash) curl -X GET -s --retry 20 http://whirr.s3.amazonaws.com/0.2.0-incubating-SNAPSHOT/sun/java/install |(bash)
echo nameserver 208.67.222.222 >> /etc/resolv.conf echo nameserver 208.67.222.222 >> /etc/resolv.conf

View File

@ -76,7 +76,7 @@ END_OF_SCRIPT
# add desired commands from the user # add desired commands from the user
cat >> $INSTANCE_HOME/runScriptWithCreds.sh <<'END_OF_SCRIPT' cat >> $INSTANCE_HOME/runScriptWithCreds.sh <<'END_OF_SCRIPT'
cd $INSTANCE_HOME cd $INSTANCE_HOME
which curl || apt-get install -f -y -qq --force-yes curl which curl || (apt-get install -f -y -qq --force-yes curl || (apt-get update && apt-get install -f -y -qq --force-yes curl))
(which java && java -fullversion 2>&1|egrep -q 1.6 ) || (which java && java -fullversion 2>&1|egrep -q 1.6 ) ||
curl -X GET -s --retry 20 http://whirr.s3.amazonaws.com/0.2.0-incubating-SNAPSHOT/sun/java/install |(bash) curl -X GET -s --retry 20 http://whirr.s3.amazonaws.com/0.2.0-incubating-SNAPSHOT/sun/java/install |(bash)
echo nameserver 208.67.222.222 >> /etc/resolv.conf echo nameserver 208.67.222.222 >> /etc/resolv.conf

View File

@ -25,11 +25,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridAddNodeWithTagStrategy; import org.jclouds.gogrid.compute.strategy.GoGridAddNodeWithTagStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridDestroyNodeStrategy; import org.jclouds.gogrid.compute.strategy.GoGridDestroyNodeStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridGetNodeMetadataStrategy; import org.jclouds.gogrid.compute.strategy.GoGridGetNodeMetadataStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridLifeCycleStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridListNodesStrategy; import org.jclouds.gogrid.compute.strategy.GoGridListNodesStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridRebootNodeStrategy;
/** /**
* *
@ -59,6 +61,16 @@ public class GoGridBindComputeStrategiesByClass extends BindComputeStrategiesByC
@Override @Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() { protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return GoGridRebootNodeStrategy.class; return GoGridLifeCycleStrategy.class;
}
@Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return GoGridLifeCycleStrategy.class;
}
@Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return GoGridLifeCycleStrategy.class;
} }
} }

View File

@ -1,67 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.gogrid.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.domain.PowerCommand;
import org.jclouds.gogrid.domain.Server;
import org.jclouds.gogrid.predicates.ServerLatestJobCompleted;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class GoGridRebootNodeStrategy implements RebootNodeStrategy {
private final GoGridClient client;
private final RetryablePredicate<Server> serverLatestJobCompleted;
private final RetryablePredicate<Server> serverLatestJobCompletedShort;
private final GetNodeMetadataStrategy getNode;
@Inject
protected GoGridRebootNodeStrategy(GoGridClient client, GetNodeMetadataStrategy getNode, Timeouts timeouts) {
this.client = client;
this.serverLatestJobCompleted = new RetryablePredicate<Server>(new ServerLatestJobCompleted(client
.getJobServices()), timeouts.nodeRunning * 9l / 10l);
this.serverLatestJobCompletedShort = new RetryablePredicate<Server>(new ServerLatestJobCompleted(client
.getJobServices()), timeouts.nodeRunning * 1l / 10l);
this.getNode = getNode;
}
@Override
public NodeMetadata rebootNode(String id) {
Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(new Long(id)));
client.getServerServices().power(server.getName(), PowerCommand.RESTART);
serverLatestJobCompleted.apply(server);
client.getServerServices().power(server.getName(), PowerCommand.START);
serverLatestJobCompletedShort.apply(server);
return getNode.getNode(id);
}
}

View File

@ -82,7 +82,7 @@ import com.google.inject.Module;
* *
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Test(enabled = false, groups = "live", testName = "gogrid.GoGridLiveTest") @Test(enabled = true, groups = "live", testName = "gogrid.GoGridLiveTest")
public class GoGridLiveTestDisabled { public class GoGridLiveTestDisabled {
private GoGridClient client; private GoGridClient client;

View File

@ -25,11 +25,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersAddNodeWithTagStrategy; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersAddNodeWithTagStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersDestroyNodeStrategy; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersDestroyNodeStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersGetNodeMetadataStrategy; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersGetNodeMetadataStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersListNodesStrategy; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersListNodesStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersRebootNodeStrategy; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersLifeCycleStrategy;
/** /**
* *
@ -60,6 +62,16 @@ public class CloudServersBindComputeStrategiesByClass extends BindComputeStrateg
@Override @Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() { protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return CloudServersRebootNodeStrategy.class; return CloudServersLifeCycleStrategy.class;
}
@Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return CloudServersLifeCycleStrategy.class;
}
@Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return CloudServersLifeCycleStrategy.class;
} }
} }

View File

@ -1,53 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rackspace.cloudservers.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.domain.RebootType;
/**
* @author Adrian Cole
*/
@Singleton
public class CloudServersRebootNodeStrategy implements RebootNodeStrategy {
private final CloudServersClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected CloudServersRebootNodeStrategy(CloudServersClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata rebootNode(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.rebootServer(serverId, RebootType.HARD);
return getNode.getNode(id);
}
}

View File

@ -77,4 +77,9 @@ public class CloudServersComputeServiceLiveTest extends BaseComputeServiceLiveTe
} }
} }
@Test(expectedExceptions = UnsupportedOperationException.class)
public void testSuspendResume() throws Exception {
super.testSuspendResume();
}
} }

View File

@ -6,11 +6,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingAddNodeWithTagStrategy; import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingAddNodeWithTagStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingDestroyNodeStrategy; import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingDestroyNodeStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingGetNodeMetadataStrategy; import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingGetNodeMetadataStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingLifeCycleStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingListNodesStrategy; import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingListNodesStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingRebootNodeStrategy;
public class RimuHostingBindComputeStrategiesByClass extends BindComputeStrategiesByClass { public class RimuHostingBindComputeStrategiesByClass extends BindComputeStrategiesByClass {
@Override @Override
@ -35,6 +37,16 @@ public class RimuHostingBindComputeStrategiesByClass extends BindComputeStrategi
@Override @Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() { protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return RimuHostingRebootNodeStrategy.class; return RimuHostingLifeCycleStrategy.class;
}
@Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return RimuHostingLifeCycleStrategy.class;
}
@Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return RimuHostingLifeCycleStrategy.class;
} }
} }

View File

@ -1,53 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rimuhosting.miro.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingRebootNodeStrategy implements RebootNodeStrategy {
private final RimuHostingClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected RimuHostingRebootNodeStrategy(RimuHostingClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata rebootNode(String id) {
Long serverId = Long.parseLong(id);
// if false server wasn't around in the first place
client.restartServer(serverId).getState();
return getNode.getNode(id);
}
}

View File

@ -285,4 +285,22 @@ public class LibvirtComputeServiceAdapter implements ComputeServiceAdapter<Domai
return builder.asString(outputProperties); return builder.asString(outputProperties);
} }
@Override
public void resumeNode(String id) {
try {
client.domainLookupByUUIDString(id).resume();
} catch (LibvirtException e) {
propogate(e);
}
}
@Override
public void suspendNode(String id) {
try {
client.domainLookupByUUIDString(id).suspend();
} catch (LibvirtException e) {
propogate(e);
}
}
} }

View File

@ -96,4 +96,10 @@ public class ServerManager {
public void rebootServer(int serverId) { public void rebootServer(int serverId) {
} }
public void stopServer(int serverId) {
}
public void startServer(int serverId) {
}
} }

View File

@ -80,4 +80,15 @@ public class ServerManagerComputeServiceAdapter implements ComputeServiceAdapter
public void rebootNode(String id) { public void rebootNode(String id) {
client.rebootServer(Integer.parseInt(id)); client.rebootServer(Integer.parseInt(id));
} }
@Override
public void resumeNode(String id) {
client.startServer(Integer.parseInt(id));
}
@Override
public void suspendNode(String id) {
client.stopServer(Integer.parseInt(id));
}
} }

View File

@ -25,11 +25,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostAddNodeWithTagStrategy; import org.jclouds.slicehost.compute.strategy.SlicehostAddNodeWithTagStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostDestroyNodeStrategy; import org.jclouds.slicehost.compute.strategy.SlicehostDestroyNodeStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostGetNodeMetadataStrategy; import org.jclouds.slicehost.compute.strategy.SlicehostGetNodeMetadataStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostListNodesStrategy; import org.jclouds.slicehost.compute.strategy.SlicehostListNodesStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostRebootNodeStrategy; import org.jclouds.slicehost.compute.strategy.SlicehostLifeCycleStrategy;
/** /**
* *
@ -60,6 +62,16 @@ public class SlicehostBindComputeStrategiesByClass extends BindComputeStrategies
@Override @Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() { protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return SlicehostRebootNodeStrategy.class; return SlicehostLifeCycleStrategy.class;
}
@Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return SlicehostLifeCycleStrategy.class;
}
@Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return SlicehostLifeCycleStrategy.class;
} }
} }

View File

@ -1,52 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.slicehost.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.slicehost.SlicehostClient;
/**
*
* @author Adrian Cole
*/
@Singleton
public class SlicehostRebootNodeStrategy implements RebootNodeStrategy {
private final SlicehostClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected SlicehostRebootNodeStrategy(SlicehostClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata rebootNode(String id) {
int sliceId = Integer.parseInt(id);
client.hardRebootSlice(sliceId);
return getNode.getNode(id);
}
}

View File

@ -24,11 +24,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudAddNodeWithTagStrategy; import org.jclouds.vcloud.compute.strategy.VCloudAddNodeWithTagStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudDestroyNodeStrategy; import org.jclouds.vcloud.compute.strategy.VCloudDestroyNodeStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudGetNodeMetadataStrategy; import org.jclouds.vcloud.compute.strategy.VCloudGetNodeMetadataStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudListNodesStrategy; import org.jclouds.vcloud.compute.strategy.VCloudListNodesStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudRebootNodeStrategy; import org.jclouds.vcloud.compute.strategy.VCloudLifeCycleStrategy;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@ -55,6 +57,16 @@ public class VCloudBindComputeStrategiesByClass extends CommonVCloudBindComputeS
@Override @Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() { protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return VCloudRebootNodeStrategy.class; return VCloudLifeCycleStrategy.class;
}
@Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return VCloudLifeCycleStrategy.class;
}
@Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return VCloudLifeCycleStrategy.class;
} }
} }

View File

@ -24,11 +24,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudExpressAddNodeWithTagStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressAddNodeWithTagStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudExpressDestroyNodeStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressDestroyNodeStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudExpressGetNodeMetadataStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressGetNodeMetadataStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudExpressListNodesStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressListNodesStrategy;
import org.jclouds.vcloud.compute.strategy.VCloudExpressRebootNodeStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressLifeCycleStrategy;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -57,6 +59,16 @@ public class VCloudExpressBindComputeStrategiesByClass extends CommonVCloudBindC
@Override @Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() { protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return VCloudExpressRebootNodeStrategy.class; return VCloudExpressLifeCycleStrategy.class;
}
@Override
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
return VCloudExpressLifeCycleStrategy.class;
}
@Override
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
return VCloudExpressLifeCycleStrategy.class;
} }
} }

View File

@ -1,61 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vcloud.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.vcloud.VCloudExpressClient;
import org.jclouds.vcloud.domain.Task;
import com.google.common.base.Predicate;
/**
* @author Adrian Cole
*/
@Singleton
public class VCloudExpressRebootNodeStrategy implements RebootNodeStrategy {
private final VCloudExpressClient client;
protected final Predicate<URI> taskTester;
protected final GetNodeMetadataStrategy getNode;
@Inject
protected VCloudExpressRebootNodeStrategy(VCloudExpressClient client, Predicate<URI> taskTester,
GetNodeMetadataStrategy getNode) {
this.client = client;
this.taskTester = taskTester;
this.getNode = getNode;
}
@Override
public NodeMetadata rebootNode(String in) {
URI id = URI.create(checkNotNull(in, "node.id"));
Task task = client.resetVApp(id);
taskTester.apply(task.getHref());
return getNode.getNode(in);
}
}

View File

@ -1,61 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vcloud.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.vcloud.VCloudClient;
import org.jclouds.vcloud.domain.Task;
import com.google.common.base.Predicate;
/**
* @author Adrian Cole
*/
@Singleton
public class VCloudRebootNodeStrategy implements RebootNodeStrategy {
private final VCloudClient client;
protected final Predicate<URI> taskTester;
protected final GetNodeMetadataStrategy getNode;
@Inject
protected VCloudRebootNodeStrategy(VCloudClient client, Predicate<URI> taskTester,
GetNodeMetadataStrategy getNode) {
this.client = client;
this.taskTester = taskTester;
this.getNode = getNode;
}
@Override
public NodeMetadata rebootNode(String in) {
URI id = URI.create(checkNotNull(in, "node.id"));
Task task = client.resetVAppOrVm(id);
taskTester.apply(task.getHref());
return getNode.getNode(in);
}
}