mirror of https://github.com/apache/jclouds.git
Merge branch 'master' of github.com:jclouds/jclouds
This commit is contained in:
commit
9717198284
|
@ -56,6 +56,8 @@ import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
|||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
import org.jclouds.compute.strategy.RebootNodeStrategy;
|
||||
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.domain.Credentials;
|
||||
import org.jclouds.domain.Location;
|
||||
|
@ -82,16 +84,19 @@ public class EC2ComputeService extends BaseComputeService {
|
|||
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
|
||||
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
|
||||
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
|
||||
ResumeNodeStrategy startNodeStrategy, SuspendNodeStrategy stopNodeStrategy,
|
||||
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
|
||||
@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,
|
||||
Map<RegionAndName, KeyPair> credentialsMap, @Named("SECURITY") Map<RegionAndName, String> securityGroupMap,
|
||||
@Named("PLACEMENT") Map<RegionAndName, String> placementGroupMap,
|
||||
@Named("DELETED") Predicate<PlacementGroup> placementGroupDeleted) {
|
||||
super(context, credentialStore, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy,
|
||||
runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider,
|
||||
templateOptionsProvider, nodeRunning, nodeTerminated, utils, timeouts, executor);
|
||||
runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, startNodeStrategy,
|
||||
stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning, nodeTerminated,
|
||||
nodeSuspended, utils, timeouts, executor);
|
||||
this.ec2Client = ec2Client;
|
||||
this.credentialsMap = credentialsMap;
|
||||
this.securityGroupMap = securityGroupMap;
|
||||
|
|
|
@ -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.EC2RebootNodeStrategy;
|
||||
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.strategy.AddNodeWithTagStrategy;
|
||||
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.RebootNodeStrategy;
|
||||
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
|
||||
import org.jclouds.compute.strategy.ResumeNodeStrategy;
|
||||
import org.jclouds.compute.strategy.SuspendNodeStrategy;
|
||||
|
||||
/**
|
||||
* @author Adrian Cole
|
||||
|
@ -76,4 +80,14 @@ public class EC2BindComputeStrategiesByClass extends BindComputeStrategiesByClas
|
|||
return EC2RebootNodeStrategy.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {
|
||||
return EC2ResumeNodeStrategy.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {
|
||||
return EC2SuspendNodeStrategy.class;
|
||||
}
|
||||
|
||||
}
|
|
@ -91,7 +91,7 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
|
|||
builder.id(instance.getRegion() + "/" + providerId);
|
||||
String tag = getTagForInstance(instance);
|
||||
builder.tag(tag);
|
||||
builder.credentials(credentialStore.get(instance.getRegion() + "/" + providerId));
|
||||
builder.credentials(credentialStore.get("node#" + instance.getRegion() + "/" + providerId));
|
||||
builder.state(instanceToNodeState.get(instance.getInstanceState()));
|
||||
builder.publicAddresses(nullSafeSet(instance.getIpAddress()));
|
||||
builder.privateAddresses(nullSafeSet(instance.getPrivateIpAddress()));
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
/**
|
||||
*
|
||||
* 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.aws.ec2.compute.strategy;
|
||||
|
||||
import static org.jclouds.aws.ec2.util.EC2Utils.parseHandle;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.aws.ec2.EC2Client;
|
||||
import org.jclouds.aws.ec2.services.InstanceClient;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.ResumeNodeStrategy;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class EC2ResumeNodeStrategy implements ResumeNodeStrategy {
|
||||
private final InstanceClient client;
|
||||
private final GetNodeMetadataStrategy getNode;
|
||||
|
||||
@Inject
|
||||
protected EC2ResumeNodeStrategy(EC2Client client, GetNodeMetadataStrategy getNode) {
|
||||
this.client = client.getInstanceServices();
|
||||
this.getNode = getNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata resumeNode(String id) {
|
||||
String[] parts = parseHandle(id);
|
||||
String region = parts[0];
|
||||
String instanceId = parts[1];
|
||||
client.startInstancesInRegion(region, instanceId);
|
||||
return getNode.getNode(id);
|
||||
}
|
||||
|
||||
}
|
|
@ -79,12 +79,12 @@ public class EC2RunNodesAndAddToSetStrategy implements RunNodesAndAddToSetStrate
|
|||
|
||||
@Inject
|
||||
EC2RunNodesAndAddToSetStrategy(
|
||||
EC2Client client,
|
||||
CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions,
|
||||
@Named("PRESENT") Predicate<RunningInstance> instancePresent,
|
||||
Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,
|
||||
Function<RunningInstance, Credentials> instanceToCredentials, Map<String, Credentials> credentialStore,
|
||||
ComputeUtils utils) {
|
||||
EC2Client client,
|
||||
CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions,
|
||||
@Named("PRESENT") Predicate<RunningInstance> instancePresent,
|
||||
Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,
|
||||
Function<RunningInstance, Credentials> instanceToCredentials, Map<String, Credentials> credentialStore,
|
||||
ComputeUtils utils) {
|
||||
this.client = client;
|
||||
this.instancePresent = instancePresent;
|
||||
this.createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions = createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions;
|
||||
|
@ -96,10 +96,10 @@ public class EC2RunNodesAndAddToSetStrategy implements RunNodesAndAddToSetStrate
|
|||
|
||||
@Override
|
||||
public Map<?, Future<Void>> execute(String tag, int count, Template template, Set<NodeMetadata> goodNodes,
|
||||
Map<NodeMetadata, Exception> badNodes) {
|
||||
Map<NodeMetadata, Exception> badNodes) {
|
||||
|
||||
Reservation<? extends RunningInstance> reservation = createKeyPairAndSecurityGroupsAsNeededThenRunInstances(tag,
|
||||
count, template);
|
||||
count, template);
|
||||
|
||||
Iterable<String> ids = transform(reservation, instanceToId);
|
||||
|
||||
|
@ -111,8 +111,8 @@ public class EC2RunNodesAndAddToSetStrategy implements RunNodesAndAddToSetStrate
|
|||
populateCredentials(reservation);
|
||||
}
|
||||
|
||||
return utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(template.getOptions(),
|
||||
transform(reservation, runningInstanceToNodeMetadata), goodNodes, badNodes);
|
||||
return utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(template.getOptions(), transform(
|
||||
reservation, runningInstanceToNodeMetadata), goodNodes, badNodes);
|
||||
}
|
||||
|
||||
protected void populateCredentials(Reservation<? extends RunningInstance> reservation) {
|
||||
|
@ -120,27 +120,27 @@ public class EC2RunNodesAndAddToSetStrategy implements RunNodesAndAddToSetStrate
|
|||
Credentials credentials = instanceToCredentials.apply(instance1);
|
||||
if (credentials != null)
|
||||
for (RunningInstance instance : reservation)
|
||||
credentialStore.put(instance.getRegion() + "/" + instance.getId(), credentials);
|
||||
credentialStore.put("node#" + instance.getRegion() + "/" + instance.getId(), credentials);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Reservation<? extends RunningInstance> createKeyPairAndSecurityGroupsAsNeededThenRunInstances(String tag, int count,
|
||||
Template template) {
|
||||
Template template) {
|
||||
String region = getRegionFromLocationOrNull(template.getLocation());
|
||||
String zone = getZoneFromLocationOrNull(template.getLocation());
|
||||
|
||||
RunInstancesOptions instanceOptions = createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.execute(region,
|
||||
tag, template);
|
||||
tag, template);
|
||||
|
||||
if (EC2TemplateOptions.class.cast(template.getOptions()).isMonitoringEnabled())
|
||||
instanceOptions.enableMonitoring();
|
||||
|
||||
if (logger.isDebugEnabled())
|
||||
logger.debug(">> running %d instance region(%s) zone(%s) ami(%s) params(%s)", count, region, zone, template
|
||||
.getImage().getProviderId(), instanceOptions.buildFormParameters());
|
||||
.getImage().getProviderId(), instanceOptions.buildFormParameters());
|
||||
|
||||
return client.getInstanceServices().runInstancesInRegion(region, zone, template.getImage().getProviderId(), 1,
|
||||
count, instanceOptions);
|
||||
count, instanceOptions);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
/**
|
||||
*
|
||||
* 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.aws.ec2.compute.strategy;
|
||||
|
||||
import static org.jclouds.aws.ec2.util.EC2Utils.parseHandle;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.aws.ec2.EC2Client;
|
||||
import org.jclouds.aws.ec2.services.InstanceClient;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.SuspendNodeStrategy;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class EC2SuspendNodeStrategy implements SuspendNodeStrategy {
|
||||
private final InstanceClient client;
|
||||
private final GetNodeMetadataStrategy getNode;
|
||||
|
||||
@Inject
|
||||
protected EC2SuspendNodeStrategy(EC2Client client, GetNodeMetadataStrategy getNode) {
|
||||
this.client = client.getInstanceServices();
|
||||
this.getNode = getNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata suspendNode(String id) {
|
||||
String[] parts = parseHandle(id);
|
||||
String region = parts[0];
|
||||
String instanceId = parts[1];
|
||||
client.stopInstancesInRegion(region, true, instanceId);
|
||||
return getNode.getNode(id);
|
||||
}
|
||||
|
||||
}
|
|
@ -33,6 +33,7 @@ import org.jclouds.compute.RunNodesException;
|
|||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.domain.OperatingSystem;
|
||||
import org.jclouds.http.HttpRequest;
|
||||
import org.jclouds.scriptbuilder.domain.OsFamily;
|
||||
import org.jclouds.scriptbuilder.domain.Statement;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
|
@ -82,7 +83,7 @@ public class ComputeAndBlobStoreTogetherHappilyLiveTest extends BlobStoreAndComp
|
|||
|
||||
// using jclouds ability to detect operating systems before we launch them, we can avoid
|
||||
// the bad practice of assuming everything is ubuntu.
|
||||
uploadBlob(tag, "openjdk/install", buildScript(defaultOperatingSystem));
|
||||
uploadBlob(tag, "openjdk/install", buildScript(defaultOperatingSystem).render(OsFamily.UNIX));
|
||||
|
||||
// instead of hard-coding to amazon s3, we can use any blobstore, conceding this test is
|
||||
// configured for amz. Note we are getting temporary access to a private blob.
|
||||
|
|
|
@ -68,7 +68,7 @@ public class CredentialsStoredInBlobStoreTest {
|
|||
public void testWeCanUseBlobStoreToStoreCredentialsAcrossContexts() throws RunNodesException, IOException {
|
||||
|
||||
ComputeServiceContext computeContext = new ComputeServiceContextFactory().createContext("stub", "foo", "bar",
|
||||
ImmutableSet.of(new CredentialStoreModule(credentialsMap)));
|
||||
ImmutableSet.of(new CredentialStoreModule(credentialsMap)));
|
||||
|
||||
Set<? extends NodeMetadata> nodes = computeContext.getComputeService().runNodesWithTag("foo", 10);
|
||||
|
||||
|
@ -76,19 +76,19 @@ public class CredentialsStoredInBlobStoreTest {
|
|||
computeContext.close();
|
||||
|
||||
// recreate the compute context with the same map and ensure it still works!
|
||||
computeContext = new ComputeServiceContextFactory().createContext("stub", "foo", "bar",
|
||||
Collections.singleton(new CredentialStoreModule(credentialsMap)));
|
||||
computeContext = new ComputeServiceContextFactory().createContext("stub", "foo", "bar", Collections
|
||||
.singleton(new CredentialStoreModule(credentialsMap)));
|
||||
|
||||
verifyCredentialsFromNodesAreInContext(nodes, computeContext);
|
||||
|
||||
}
|
||||
|
||||
protected void verifyCredentialsFromNodesAreInContext(Set<? extends NodeMetadata> nodes,
|
||||
ComputeServiceContext computeContext) throws IOException {
|
||||
ComputeServiceContext computeContext) throws IOException {
|
||||
// verify each node's credential is in the map.
|
||||
assertEquals(computeContext.credentialStore().size(), 10);
|
||||
for (NodeMetadata node : nodes) {
|
||||
assertEquals(computeContext.credentialStore().get(node.getId()), node.getCredentials());
|
||||
assertEquals(computeContext.credentialStore().get("node#" + node.getId()), node.getCredentials());
|
||||
}
|
||||
|
||||
// verify the credentials are in the backing store and of a known json format
|
||||
|
@ -96,7 +96,7 @@ public class CredentialsStoredInBlobStoreTest {
|
|||
for (Entry<String, InputStream> entry : credentialsMap.entrySet()) {
|
||||
Credentials credentials = computeContext.credentialStore().get(entry.getKey());
|
||||
assertEquals(Utils.toStringAndClose(entry.getValue()), String.format(
|
||||
"{\"identity\":\"%s\",\"credential\":\"%s\"}", credentials.identity, credentials.credential));
|
||||
"{\"identity\":\"%s\",\"credential\":\"%s\"}", credentials.identity, credentials.credential));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -90,6 +90,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
|
|||
protected void assertDefaultWorks() {
|
||||
Template defaultTemplate = client.templateBuilder().build();
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "0.9.9-beta");
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX);
|
||||
assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);
|
||||
}
|
||||
|
|
|
@ -82,14 +82,14 @@ public class EC2TemplateBuilderLiveTest {
|
|||
.<Module> of(new Log4JLoggingModule()), setupProperties());
|
||||
|
||||
Template template = newContext.getComputeService().templateBuilder().hardwareId(InstanceType.M1_SMALL)
|
||||
.osVersionMatches("10.04").imageDescriptionMatches("ubuntu-images").osFamily(OsFamily.UBUNTU).build();
|
||||
.osVersionMatches("10.10").imageDescriptionMatches("ubuntu-images").osFamily(OsFamily.UBUNTU).build();
|
||||
|
||||
System.out.println(template.getHardware());
|
||||
assert (template.getImage().getProviderId().startsWith("ami-")) : template;
|
||||
assertEquals(template.getImage().getOperatingSystem().getVersion(), "10.04");
|
||||
assertEquals(template.getImage().getOperatingSystem().getVersion(), "10.10");
|
||||
assertEquals(template.getImage().getOperatingSystem().is64Bit(), false);
|
||||
assertEquals(template.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
|
||||
assertEquals(template.getImage().getVersion(), "20100921");
|
||||
assertEquals(template.getImage().getVersion(), "20101027");
|
||||
assertEquals(template.getImage().getUserMetadata().get("rootDeviceType"), "instance-store");
|
||||
assertEquals(template.getLocation().getId(), "us-east-1");
|
||||
assertEquals(getCores(template.getHardware()), 1.0d);
|
||||
|
@ -135,7 +135,7 @@ public class EC2TemplateBuilderLiveTest {
|
|||
|
||||
Template defaultTemplate = newContext.getComputeService().templateBuilder().build();
|
||||
assert (defaultTemplate.getImage().getProviderId().startsWith("ami-")) : defaultTemplate;
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "0.9.8-beta");
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "0.9.9-beta");
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX);
|
||||
assertEquals(defaultTemplate.getImage().getUserMetadata().get("rootDeviceType"), "ebs");
|
||||
|
|
|
@ -75,7 +75,7 @@ public class RunningInstanceToNodeMetadataTest {
|
|||
|
||||
RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet
|
||||
.<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of(
|
||||
"us-east-1/i-9slweygo", creds));
|
||||
"node#us-east-1/i-9slweygo", creds));
|
||||
|
||||
RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml");
|
||||
|
||||
|
|
|
@ -92,7 +92,7 @@ public class EC2RunNodesAndAddToSetStrategyTest {
|
|||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
@SuppressWarnings( { "unchecked" })
|
||||
private void assertRegionAndZoneForLocation(Location location, String region, String zone) {
|
||||
String imageId = "ami1";
|
||||
String instanceCreatedId = "instance1";
|
||||
|
@ -102,27 +102,26 @@ public class EC2RunNodesAndAddToSetStrategyTest {
|
|||
InstanceClient instanceClient = createMock(InstanceClient.class);
|
||||
RunInstancesOptions ec2Options = createMock(RunInstancesOptions.class);
|
||||
RunningInstance instance = createMock(RunningInstance.class);
|
||||
Reservation<? extends RunningInstance> reservation = new Reservation<RunningInstance>(region,
|
||||
ImmutableSet.<String> of(), ImmutableSet.<RunningInstance> of(instance), "ownerId", "requesterId",
|
||||
"reservationId");
|
||||
Reservation<? extends RunningInstance> reservation = new Reservation<RunningInstance>(region, ImmutableSet
|
||||
.<String> of(), ImmutableSet.<RunningInstance> of(instance), "ownerId", "requesterId", "reservationId");
|
||||
NodeMetadata nodeMetadata = createMock(NodeMetadata.class);
|
||||
|
||||
// setup expectations
|
||||
expect(strategy.client.getInstanceServices()).andReturn(instanceClient).atLeastOnce();
|
||||
expect(
|
||||
strategy.createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.execute(region, input.tag,
|
||||
input.template)).andReturn(ec2Options);
|
||||
strategy.createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.execute(region, input.tag,
|
||||
input.template)).andReturn(ec2Options);
|
||||
expect(input.template.getLocation()).andReturn(input.location).atLeastOnce();
|
||||
expect(input.template.getImage()).andReturn(input.image).atLeastOnce();
|
||||
expect(input.image.getProviderId()).andReturn(imageId).atLeastOnce();
|
||||
expect(instanceClient.runInstancesInRegion(region, zone, imageId, 1, input.count, ec2Options)).andReturn(
|
||||
(Reservation) reservation);
|
||||
(Reservation) reservation);
|
||||
expect(instance.getId()).andReturn(instanceCreatedId).atLeastOnce();
|
||||
// simulate a lazy credentials fetch
|
||||
Credentials creds = new Credentials("foo","bar");
|
||||
Credentials creds = new Credentials("foo", "bar");
|
||||
expect(strategy.instanceToCredentials.apply(instance)).andReturn(creds);
|
||||
expect(instance.getRegion()).andReturn(region);
|
||||
expect(strategy.credentialStore.put(region + "/" + instanceCreatedId, creds)).andReturn(null);
|
||||
expect(strategy.credentialStore.put("node#" + region + "/" + instanceCreatedId, creds)).andReturn(null);
|
||||
|
||||
expect(strategy.instancePresent.apply(instance)).andReturn(true);
|
||||
expect(input.template.getOptions()).andReturn(input.options).atLeastOnce();
|
||||
|
@ -130,8 +129,8 @@ public class EC2RunNodesAndAddToSetStrategyTest {
|
|||
|
||||
expect(strategy.runningInstanceToNodeMetadata.apply(instance)).andReturn(nodeMetadata);
|
||||
expect(
|
||||
strategy.utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(eq(input.options),
|
||||
containsNodeMetadata(nodeMetadata), eq(input.nodes), eq(input.badNodes))).andReturn(null);
|
||||
strategy.utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(eq(input.options),
|
||||
containsNodeMetadata(nodeMetadata), eq(input.nodes), eq(input.badNodes))).andReturn(null);
|
||||
|
||||
// replay mocks
|
||||
replay(instanceClient);
|
||||
|
@ -154,9 +153,9 @@ public class EC2RunNodesAndAddToSetStrategyTest {
|
|||
}
|
||||
|
||||
private static final Location REGION_AP_SOUTHEAST_1 = new LocationImpl(LocationScope.REGION, Region.AP_SOUTHEAST_1,
|
||||
Region.AP_SOUTHEAST_1, new LocationImpl(LocationScope.PROVIDER, "ec2", "ec2", null));
|
||||
Region.AP_SOUTHEAST_1, new LocationImpl(LocationScope.PROVIDER, "ec2", "ec2", null));
|
||||
private static final Location ZONE_AP_SOUTHEAST_1A = new LocationImpl(LocationScope.ZONE,
|
||||
AvailabilityZone.AP_SOUTHEAST_1A, AvailabilityZone.AP_SOUTHEAST_1A, REGION_AP_SOUTHEAST_1);
|
||||
AvailabilityZone.AP_SOUTHEAST_1A, AvailabilityZone.AP_SOUTHEAST_1A, REGION_AP_SOUTHEAST_1);
|
||||
|
||||
// /////////////////////////////////////////////////////////////////////
|
||||
@SuppressWarnings("unchecked")
|
||||
|
@ -214,7 +213,7 @@ public class EC2RunNodesAndAddToSetStrategyTest {
|
|||
Map<String, Credentials> credentialStore = createMock(Map.class);
|
||||
ComputeUtils utils = createMock(ComputeUtils.class);
|
||||
return new EC2RunNodesAndAddToSetStrategy(client, createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions,
|
||||
instanceStateRunning, runningInstanceToNodeMetadata, instanceToCredentials, credentialStore, utils);
|
||||
instanceStateRunning, runningInstanceToNodeMetadata, instanceToCredentials, credentialStore, utils);
|
||||
}
|
||||
|
||||
private void replayStrategy(EC2RunNodesAndAddToSetStrategy strategy) {
|
||||
|
|
|
@ -26,7 +26,6 @@ import static com.google.common.collect.Lists.newArrayList;
|
|||
import static com.google.common.collect.Sets.newTreeSet;
|
||||
import static org.jclouds.compute.ComputeTestUtils.buildScript;
|
||||
import static org.jclouds.compute.ComputeTestUtils.setupKeyPair;
|
||||
import static org.jclouds.scriptbuilder.domain.Statements.exec;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
import static org.testng.Assert.assertNotNull;
|
||||
|
||||
|
@ -89,10 +88,10 @@ public class PlacementGroupClientLiveTest {
|
|||
protected void setupCredentials() {
|
||||
identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity");
|
||||
credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider
|
||||
+ ".credential");
|
||||
+ ".credential");
|
||||
endpoint = checkNotNull(System.getProperty("test." + provider + ".endpoint"), "test." + provider + ".endpoint");
|
||||
apiversion = checkNotNull(System.getProperty("test." + provider + ".apiversion"), "test." + provider
|
||||
+ ".apiversion");
|
||||
+ ".apiversion");
|
||||
}
|
||||
|
||||
protected Properties setupProperties() {
|
||||
|
@ -110,14 +109,14 @@ public class PlacementGroupClientLiveTest {
|
|||
public void setupClient() throws FileNotFoundException, IOException {
|
||||
setupCredentials();
|
||||
Properties overrides = setupProperties();
|
||||
context = new ComputeServiceContextFactory().createContext(provider,
|
||||
ImmutableSet.<Module> of(new Log4JLoggingModule()), overrides);
|
||||
context = new ComputeServiceContextFactory().createContext(provider, ImmutableSet
|
||||
.<Module> of(new Log4JLoggingModule()), overrides);
|
||||
keyPair = setupKeyPair();
|
||||
|
||||
client = EC2Client.class.cast(context.getProviderSpecificContext().getApi());
|
||||
|
||||
availableTester = new RetryablePredicate<PlacementGroup>(new PlacementGroupAvailable(client), 60, 1,
|
||||
TimeUnit.SECONDS);
|
||||
TimeUnit.SECONDS);
|
||||
|
||||
deletedTester = new RetryablePredicate<PlacementGroup>(new PlacementGroupDeleted(client), 60, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
@ -126,12 +125,12 @@ public class PlacementGroupClientLiveTest {
|
|||
void testDescribe() {
|
||||
for (String region : newArrayList(Region.US_EAST_1)) {
|
||||
SortedSet<PlacementGroup> allResults = newTreeSet(client.getPlacementGroupServices()
|
||||
.describePlacementGroupsInRegion(region));
|
||||
.describePlacementGroupsInRegion(region));
|
||||
assertNotNull(allResults);
|
||||
if (allResults.size() >= 1) {
|
||||
PlacementGroup group = allResults.last();
|
||||
SortedSet<PlacementGroup> result = newTreeSet(client.getPlacementGroupServices()
|
||||
.describePlacementGroupsInRegion(region, group.getName()));
|
||||
.describePlacementGroupsInRegion(region, group.getName()));
|
||||
assertNotNull(result);
|
||||
PlacementGroup compare = result.last();
|
||||
assertEquals(compare, group);
|
||||
|
@ -160,7 +159,7 @@ public class PlacementGroupClientLiveTest {
|
|||
private void verifyPlacementGroup(String groupName) {
|
||||
assert availableTester.apply(new PlacementGroup(Region.US_EAST_1, groupName, "cluster", State.PENDING)) : group;
|
||||
Set<PlacementGroup> oneResult = client.getPlacementGroupServices().describePlacementGroupsInRegion(null,
|
||||
groupName);
|
||||
groupName);
|
||||
assertNotNull(oneResult);
|
||||
assertEquals(oneResult.size(), 1);
|
||||
group = oneResult.iterator().next();
|
||||
|
@ -195,7 +194,7 @@ public class PlacementGroupClientLiveTest {
|
|||
assertEquals(template.getImage().getId(), "us-east-1/ami-7ea24a17");
|
||||
|
||||
template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public"))
|
||||
.runScript(exec(buildScript(template.getImage().getOperatingSystem())));
|
||||
.runScript(buildScript(template.getImage().getOperatingSystem()));
|
||||
|
||||
String tag = PREFIX + "cccluster";
|
||||
context.getComputeService().destroyNodesMatching(NodePredicates.withTag(tag));
|
||||
|
@ -205,7 +204,7 @@ public class PlacementGroupClientLiveTest {
|
|||
NodeMetadata node = getOnlyElement(nodes);
|
||||
|
||||
getOnlyElement(getOnlyElement(client.getInstanceServices().describeInstancesInRegion(null,
|
||||
node.getProviderId())));
|
||||
node.getProviderId())));
|
||||
|
||||
} catch (RunNodesException e) {
|
||||
System.err.println(e.getNodeErrors().keySet());
|
||||
|
|
|
@ -64,17 +64,33 @@ public class ParseAzureStorageErrorFromXmlContent implements HttpErrorHandler {
|
|||
|
||||
public void handleError(HttpCommand command, HttpResponse response) {
|
||||
Exception exception = new HttpResponseException(command, response);
|
||||
String message = null;
|
||||
try {
|
||||
AzureStorageError error = parseErrorFromContentOrNull(command, response);
|
||||
if (response.getPayload() != null) {
|
||||
String contentType = response.getPayload().getContentMetadata().getContentType();
|
||||
if (contentType != null && (contentType.indexOf("xml") != -1 || contentType.indexOf("unknown") != -1)) {
|
||||
AzureStorageError error = utils.parseAzureStorageErrorFromContent(command, response, response
|
||||
.getPayload().getInput());
|
||||
if (error != null) {
|
||||
message = error.getMessage();
|
||||
exception = new AzureStorageResponseException(command, response, error);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
message = Utils.toStringAndClose(response.getPayload().getInput());
|
||||
} catch (IOException e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
message = message != null ? message : String.format("%s -> %s", command.getRequest().getRequestLine(),
|
||||
response.getStatusLine());
|
||||
switch (response.getStatusCode()) {
|
||||
case 401:
|
||||
exception = new AuthorizationException(command.getRequest(), error != null ? error
|
||||
.getMessage() : response.getStatusLine());
|
||||
exception = new AuthorizationException(command.getRequest(), message);
|
||||
break;
|
||||
case 404:
|
||||
|
||||
if (!command.getRequest().getMethod().equals("DELETE")) {
|
||||
String message = error != null ? error.getMessage() : String.format("%s -> %s",
|
||||
command.getRequest().getRequestLine(), response.getStatusLine());
|
||||
String path = command.getRequest().getEndpoint().getPath();
|
||||
Matcher matcher = CONTAINER_PATH.matcher(path);
|
||||
if (matcher.find()) {
|
||||
|
@ -82,15 +98,14 @@ public class ParseAzureStorageErrorFromXmlContent implements HttpErrorHandler {
|
|||
} else {
|
||||
matcher = CONTAINER_KEY_PATH.matcher(path);
|
||||
if (matcher.find()) {
|
||||
exception = new KeyNotFoundException(matcher.group(1), matcher.group(2),
|
||||
message);
|
||||
exception = new KeyNotFoundException(matcher.group(1), matcher.group(2), message);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
exception = error != null ? new AzureStorageResponseException(command, response,
|
||||
error) : new HttpResponseException(command, response);
|
||||
case 411:
|
||||
exception = new IllegalArgumentException(message);
|
||||
break;
|
||||
}
|
||||
} finally {
|
||||
releasePayload(response);
|
||||
|
@ -98,17 +113,4 @@ public class ParseAzureStorageErrorFromXmlContent implements HttpErrorHandler {
|
|||
}
|
||||
}
|
||||
|
||||
AzureStorageError parseErrorFromContentOrNull(HttpCommand command, HttpResponse response) {
|
||||
if (response.getPayload() != null) {
|
||||
try {
|
||||
String content = Utils.toStringAndClose(response.getPayload().getInput());
|
||||
if (content != null && content.indexOf('<') >= 0)
|
||||
return utils.parseAzureStorageErrorFromContent(command, response, Utils
|
||||
.toInputStream(content));
|
||||
} catch (IOException e) {
|
||||
logger.warn(e, "exception reading error from response", response);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -81,11 +81,9 @@ public class AzureBlobClientLiveTest {
|
|||
|
||||
protected void setupCredentials() {
|
||||
identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity");
|
||||
credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider
|
||||
+ ".credential");
|
||||
endpoint = checkNotNull(System.getProperty("test." + provider + ".endpoint"), "test." + provider + ".endpoint");
|
||||
apiversion = checkNotNull(System.getProperty("test." + provider + ".apiversion"), "test." + provider
|
||||
+ ".apiversion");
|
||||
credential = System.getProperty("test." + provider + ".credential");
|
||||
endpoint = System.getProperty("test." + provider + ".endpoint");
|
||||
apiversion = System.getProperty("test." + provider + ".apiversion");
|
||||
}
|
||||
|
||||
protected Properties setupProperties() {
|
||||
|
@ -93,9 +91,12 @@ public class AzureBlobClientLiveTest {
|
|||
overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
|
||||
overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
|
||||
overrides.setProperty(provider + ".identity", identity);
|
||||
overrides.setProperty(provider + ".credential", credential);
|
||||
overrides.setProperty(provider + ".endpoint", endpoint);
|
||||
overrides.setProperty(provider + ".apiversion", apiversion);
|
||||
if (credential != null)
|
||||
overrides.setProperty(provider + ".credential", credential);
|
||||
if (endpoint != null)
|
||||
overrides.setProperty(provider + ".endpoint", endpoint);
|
||||
if (apiversion != null)
|
||||
overrides.setProperty(provider + ".apiversion", apiversion);
|
||||
return overrides;
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,105 @@
|
|||
/**
|
||||
*
|
||||
* 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.azure.storage.handlers;
|
||||
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.EasyMock.reportMatcher;
|
||||
import static org.easymock.classextension.EasyMock.createMock;
|
||||
import static org.easymock.classextension.EasyMock.replay;
|
||||
import static org.easymock.classextension.EasyMock.verify;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.easymock.IArgumentMatcher;
|
||||
import org.jclouds.azure.storage.filters.SharedKeyLiteAuthentication;
|
||||
import org.jclouds.http.HttpCommand;
|
||||
import org.jclouds.http.HttpRequest;
|
||||
import org.jclouds.http.HttpResponse;
|
||||
import org.jclouds.http.functions.config.SaxParserModule;
|
||||
import org.jclouds.io.Payloads;
|
||||
import org.jclouds.util.Utils;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Guice;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@Test(groups = { "unit" })
|
||||
public class ParseAzureErrorFromXmlContentTest {
|
||||
|
||||
@Test
|
||||
public void test411WithTextHtmlIllegalArgumentException() {
|
||||
assertCodeMakes("PUT", URI
|
||||
.create("https://jclouds.blob.core.windows.net/adriancole-azureblob-413790770?restype=container"), 411,
|
||||
"Length Required", "text/html; charset=us-ascii", "<HTML><HEAD><TITLE>Length Required</TITLE>\r\n",
|
||||
IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,
|
||||
String content, Class<? extends Exception> expected) {
|
||||
|
||||
ParseAzureStorageErrorFromXmlContent function = Guice.createInjector(new SaxParserModule(), new AbstractModule() {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(SharedKeyLiteAuthentication.class).toInstance(createMock(SharedKeyLiteAuthentication.class));
|
||||
}
|
||||
|
||||
}).getInstance(ParseAzureStorageErrorFromXmlContent.class);
|
||||
|
||||
HttpCommand command = createMock(HttpCommand.class);
|
||||
HttpRequest request = new HttpRequest(method, uri);
|
||||
HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Utils
|
||||
.toInputStream(content)));
|
||||
response.getPayload().getContentMetadata().setContentType(contentType);
|
||||
|
||||
expect(command.getRequest()).andReturn(request).atLeastOnce();
|
||||
command.setException(classEq(expected));
|
||||
|
||||
replay(command);
|
||||
|
||||
function.handleError(command, response);
|
||||
|
||||
verify(command);
|
||||
}
|
||||
|
||||
public static Exception classEq(final Class<? extends Exception> in) {
|
||||
reportMatcher(new IArgumentMatcher() {
|
||||
|
||||
@Override
|
||||
public void appendTo(StringBuffer buffer) {
|
||||
buffer.append("classEq(");
|
||||
buffer.append(in);
|
||||
buffer.append(")");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(Object arg) {
|
||||
return arg.getClass() == in;
|
||||
}
|
||||
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
|
@ -234,6 +234,30 @@ See http://code.google.com/p/jclouds for details."
|
|||
([id #^ComputeService compute]
|
||||
(.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
|
||||
"Reboot all the nodes with the given tag."
|
||||
([tag] (reboot-nodes-with-tag tag *compute*))
|
||||
|
|
|
@ -52,6 +52,10 @@
|
|||
(^void destroyNode [this ^String id]
|
||||
())
|
||||
(^void rebootNode [this ^String id]
|
||||
())
|
||||
(^void suspendNode [this ^String id]
|
||||
())
|
||||
(^void resumeNode [this ^String id]
|
||||
()))))
|
||||
|
||||
(defn compute-context [^RestContextSpec spec]
|
||||
|
|
|
@ -63,52 +63,48 @@ public interface ComputeService {
|
|||
TemplateOptions templateOptions();
|
||||
|
||||
/**
|
||||
* The list hardware profiles command shows you the options including virtual cpu count,
|
||||
* memory, and disks. cpu count is not a portable quantity across clouds, as
|
||||
* they are measured differently. However, it is a good indicator of relative
|
||||
* speed within a cloud. memory is measured in megabytes and disks in
|
||||
* gigabytes.
|
||||
* The list hardware profiles command shows you the options including virtual cpu count, memory,
|
||||
* and disks. cpu count is not a portable quantity across clouds, as they are measured
|
||||
* differently. However, it is a good indicator of relative speed within a cloud. memory is
|
||||
* measured in megabytes and disks in gigabytes.
|
||||
*
|
||||
* @return a map of hardware profiles by ID, conceding that in some clouds the "id" is
|
||||
* not used.
|
||||
* @return a map of hardware profiles by ID, conceding that in some clouds the "id" is not used.
|
||||
*/
|
||||
Set<? extends Hardware> listHardwareProfiles();
|
||||
|
||||
/**
|
||||
* Images define the operating system and metadata related to a node. In some
|
||||
* clouds, Images are bound to a specific region, and their identifiers are
|
||||
* different across these regions. For this reason, you should consider
|
||||
* matching image requirements like operating system family with
|
||||
* TemplateBuilder as opposed to choosing an image explicitly. The
|
||||
* getImages() command returns a map of images by id.
|
||||
* Images define the operating system and metadata related to a node. In some clouds, Images are
|
||||
* bound to a specific region, and their identifiers are different across these regions. For this
|
||||
* reason, you should consider matching image requirements like operating system family with
|
||||
* TemplateBuilder as opposed to choosing an image explicitly. The getImages() command returns a
|
||||
* map of images by id.
|
||||
*/
|
||||
Set<? extends Image> listImages();
|
||||
|
||||
/**
|
||||
* all nodes available to the current user by id. If possible, the returned
|
||||
* set will include {@link NodeMetadata} objects.
|
||||
* all nodes available to the current user by id. If possible, the returned set will include
|
||||
* {@link NodeMetadata} objects.
|
||||
*/
|
||||
Set<? extends ComputeMetadata> listNodes();
|
||||
|
||||
/**
|
||||
* The list locations command returns all the valid locations for nodes. A
|
||||
* location has a scope, which is typically region or zone. A region is a
|
||||
* general area, like eu-west, where a zone is similar to a datacenter. If a
|
||||
* location has a parent, that implies it is within that location. For
|
||||
* example a location can be a rack, whose parent is likely to be a zone.
|
||||
* The list locations command returns all the valid locations for nodes. A location has a scope,
|
||||
* which is typically region or zone. A region is a general area, like eu-west, where a zone is
|
||||
* similar to a datacenter. If a location has a parent, that implies it is within that location.
|
||||
* For example a location can be a rack, whose parent is likely to be a zone.
|
||||
*/
|
||||
Set<? extends Location> listAssignableLocations();
|
||||
|
||||
/**
|
||||
*
|
||||
* The compute api treats nodes as a group based on a tag you specify. Using
|
||||
* this tag, you can choose to operate one or many nodes as a logical unit
|
||||
* without regard to the implementation details of the cloud.
|
||||
* The compute api treats nodes as a group based on a tag you specify. Using this tag, you can
|
||||
* choose to operate one or many nodes as a logical unit without regard to the implementation
|
||||
* details of the cloud.
|
||||
* <p/>
|
||||
*
|
||||
* The set that is returned will include credentials you can use to ssh into
|
||||
* the nodes. The "key" part of the credentials is either a password or a
|
||||
* private key. You have to inspect the value to determine this.
|
||||
* The set that is returned will include credentials you can use to ssh into the nodes. The "key"
|
||||
* part of the credentials is either a password or a private key. You have to inspect the value
|
||||
* to determine this.
|
||||
*
|
||||
* <pre>
|
||||
* if (node.getCredentials().key.startsWith("-----BEGIN RSA PRIVATE KEY-----"))
|
||||
|
@ -116,11 +112,11 @@ public interface ComputeService {
|
|||
* </pre>
|
||||
*
|
||||
* <p/>
|
||||
* Note. if all you want to do is execute a script at bootup, you should
|
||||
* consider use of the runscript option.
|
||||
* Note. if all you want to do is execute a script at bootup, you should consider use of the
|
||||
* runscript option.
|
||||
* <p/>
|
||||
* If resources such as security groups are needed, they will be reused or
|
||||
* created for you. Inbound port 22 will always be opened up.
|
||||
* If resources such as security groups are needed, they will be reused or created for you.
|
||||
* Inbound port 22 will always be opened up.
|
||||
*
|
||||
* @param tag
|
||||
* - 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.
|
||||
*
|
||||
* @throws RunNodesException
|
||||
* when there's a problem applying options to nodes. Note that
|
||||
* successful and failed nodes are a part of this exception, so be
|
||||
* sure to inspect this carefully.
|
||||
* when there's a problem applying options to nodes. Note that successful and failed
|
||||
* nodes are a part of this exception, so be sure to inspect this carefully.
|
||||
*/
|
||||
Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, Template template) throws RunNodesException;
|
||||
|
||||
/**
|
||||
* Like {@link ComputeService#runNodesWithTag(String,int,Template)}, except
|
||||
* that the template is default, equivalent to {@code
|
||||
* templateBuilder().any().options(templateOptions)}.
|
||||
* Like {@link ComputeService#runNodesWithTag(String,int,Template)}, except that the template is
|
||||
* default, equivalent to {@code templateBuilder().any().options(templateOptions)}.
|
||||
*/
|
||||
Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, TemplateOptions templateOptions)
|
||||
throws RunNodesException;
|
||||
throws RunNodesException;
|
||||
|
||||
/**
|
||||
* Like {@link ComputeService#runNodesWithTag(String,int,TemplateOptions)},
|
||||
* except that the options are default, as specified in
|
||||
* {@link ComputeService#templateOptions}.
|
||||
* Like {@link ComputeService#runNodesWithTag(String,int,TemplateOptions)}, except that the
|
||||
* options are default, as specified in {@link ComputeService#templateOptions}.
|
||||
*/
|
||||
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
|
||||
* dependent resources will also be destroyed.
|
||||
* resume the node from {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended} state,
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* nodes matching the filter are treated as a logical set. Using the delete
|
||||
* command, you can save time by removing the nodes in parallel. When the
|
||||
* last node in a set is destroyed, any indirect resources it uses, such as
|
||||
* keypairs, are also destroyed.
|
||||
* nodes matching the filter are treated as a logical set. Using the delete command, you can save
|
||||
* time by removing the nodes in parallel. When the last node in a set is destroyed, any indirect
|
||||
* resources it uses, such as keypairs, are also destroyed.
|
||||
*
|
||||
* @return list of nodes destroyed
|
||||
*/
|
||||
|
@ -174,8 +197,8 @@ public interface ComputeService {
|
|||
void rebootNode(String id);
|
||||
|
||||
/**
|
||||
* nodes matching the filter are treated as a logical set. Using this
|
||||
* command, you can save time by rebooting the nodes in parallel.
|
||||
* nodes matching the filter are treated as a logical set. Using this command, you can save time
|
||||
* by rebooting the nodes in parallel.
|
||||
*/
|
||||
void rebootNodesMatching(Predicate<NodeMetadata> filter);
|
||||
|
||||
|
@ -185,8 +208,8 @@ public interface ComputeService {
|
|||
NodeMetadata getNodeMetadata(String id);
|
||||
|
||||
/**
|
||||
* get all nodes including details such as image and ip addresses even if it
|
||||
* incurs extra requests to the service.
|
||||
* get all nodes including details such as image and ip addresses even if it incurs extra
|
||||
* requests to the service.
|
||||
*
|
||||
* @param filter
|
||||
* how to select the nodes you are interested in details on.
|
||||
|
@ -196,24 +219,22 @@ public interface ComputeService {
|
|||
/**
|
||||
* Runs the script without any additional options
|
||||
*
|
||||
* @see #runScriptOnNodesMatching(Predicate, Payload,
|
||||
* @see #runScriptOnNodesMatching(Predicate, Payload,
|
||||
* org.jclouds.compute.options.RunScriptOptions)
|
||||
* @see org.jclouds.compute.predicates.NodePredicates#runningWithTag(String)
|
||||
*/
|
||||
Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript)
|
||||
throws RunScriptOnNodesException;
|
||||
throws RunScriptOnNodesException;
|
||||
|
||||
/**
|
||||
* Run the script on all nodes with the specific tag.
|
||||
*
|
||||
* @param filter
|
||||
* Predicate-based filter to define on which nodes the script is to
|
||||
* be executed
|
||||
* Predicate-based filter to define on which nodes the script is to be executed
|
||||
* @param runScript
|
||||
* payload containing the script to run
|
||||
* @param options
|
||||
* nullable options to how to run the script, whether to override
|
||||
* credentials
|
||||
* nullable options to how to run the script, whether to override credentials
|
||||
* @return map with node identifiers and corresponding responses
|
||||
* @throws RunScriptOnNodesException
|
||||
* if anything goes wrong during script execution
|
||||
|
@ -222,6 +243,6 @@ public interface ComputeService {
|
|||
* @see org.jclouds.io.Payloads
|
||||
*/
|
||||
Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter,
|
||||
Payload runScript, RunScriptOptions options) throws RunScriptOnNodesException;
|
||||
Payload runScript, RunScriptOptions options) throws RunScriptOnNodesException;
|
||||
|
||||
}
|
||||
|
|
|
@ -36,30 +36,32 @@ public interface ComputeServiceAdapter<N, H, I, L> {
|
|||
/**
|
||||
* {@link ComputeService#runNodesWithTag(String, int, Template)} generates the parameters passed
|
||||
* into this method such that each node in the set has a unique name.
|
||||
* <p/>
|
||||
* Your responsibility is to create a node with the underlying library and return after storing
|
||||
* its credentials in the supplied map.
|
||||
* <p/>
|
||||
* Note that it is intentional to return the library native node object, as generic type
|
||||
*
|
||||
* <h4>note</h4> It is intentional to return the library native node object, as generic type
|
||||
* {@code N}. If you are not using library-native objects (such as libvirt {@code Domain}) use
|
||||
* {@link JCloudsNativeComputeServiceAdapter} instead.
|
||||
*
|
||||
* <h4>note</h4> Your responsibility is to create a node with the underlying library and return
|
||||
* after storing its credentials in the supplied map corresponding to
|
||||
* {@link ComputeServiceContext#getCredentialStore credentialStore}
|
||||
*
|
||||
* @param tag
|
||||
* used to aggregate nodes with identical configuration
|
||||
* @param name
|
||||
* unique supplied name for the node, which has the tag encoded into it.
|
||||
* @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.
|
||||
* @param credentialStore
|
||||
* once the node is started, its login user and password will be encoded based on the
|
||||
* node {@code id}
|
||||
* once the node is resumeed, its login user and password must be stored keyed on
|
||||
* {@code node#id}.
|
||||
* @return library-native representation of a node.
|
||||
*
|
||||
* @see ComputeService#runNodesWithTag(String, int, Template)
|
||||
* @see ComputeServiceContext#getCredentialStore
|
||||
*/
|
||||
N runNodeWithTagAndNameAndStoreCredentials(String tag, String name, Template template,
|
||||
Map<String, Credentials> credentialStore);
|
||||
Map<String, Credentials> credentialStore);
|
||||
|
||||
/**
|
||||
* Hardware profiles describe available cpu, memory, and disk configurations that can be used to
|
||||
|
@ -92,6 +94,10 @@ public interface ComputeServiceAdapter<N, H, I, L> {
|
|||
|
||||
void rebootNode(String id);
|
||||
|
||||
void resumeNode(String id);
|
||||
|
||||
void suspendNode(String id);
|
||||
|
||||
Iterable<N> listNodes();
|
||||
|
||||
}
|
|
@ -50,13 +50,26 @@ public interface ComputeServiceContext {
|
|||
|
||||
/**
|
||||
* retrieves a list of credentials for resources created within this context, keyed on {@code id}
|
||||
* of the resource. We are testing this approach for resources such as compute nodes, where you
|
||||
* could access this externally.
|
||||
*
|
||||
* of the resource with a namespace prefix (ex. {@code node#}. We are testing this approach for
|
||||
* resources such as compute nodes, where you could access this externally.
|
||||
* <p/>
|
||||
* <h4>accessing credentials for a node</h4>
|
||||
* <p/>
|
||||
* the key is in the form {@code node#id}.
|
||||
* <ul>
|
||||
* <li>if the node id is {@code 8}, then the key will be {@code node#8}</li>
|
||||
* <li>if the node id is {@code us-east-1/i-asdfdas}, then the key will be {@code
|
||||
* node#us-east-1/i-asdfdas}</li>
|
||||
* <li>if the node id is {@code http://cloud/instances/1}, then the key will be {@code
|
||||
* node#http://cloud/instances/1}</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Beta
|
||||
Map<String, Credentials> getCredentialStore();
|
||||
|
||||
/**
|
||||
* @see ComputeServiceContext#getCredentialStore
|
||||
*/
|
||||
@Beta
|
||||
Map<String, Credentials> credentialStore();
|
||||
|
||||
|
|
|
@ -25,6 +25,8 @@ import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
|||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
import org.jclouds.compute.strategy.RebootNodeStrategy;
|
||||
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 com.google.inject.AbstractModule;
|
||||
|
@ -42,6 +44,8 @@ public abstract class BindComputeStrategiesByClass extends AbstractModule {
|
|||
bindListNodesStrategy(defineListNodesStrategy());
|
||||
bindGetNodeMetadataStrategy(defineGetNodeMetadataStrategy());
|
||||
bindRebootNodeStrategy(defineRebootNodeStrategy());
|
||||
bindStartNodeStrategy(defineStartNodeStrategy());
|
||||
bindStopNodeStrategy(defineStopNodeStrategy());
|
||||
bindDestroyNodeStrategy(defineDestroyNodeStrategy());
|
||||
}
|
||||
|
||||
|
@ -64,6 +68,14 @@ public abstract class BindComputeStrategiesByClass extends AbstractModule {
|
|||
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) {
|
||||
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 ResumeNodeStrategy> defineStartNodeStrategy();
|
||||
|
||||
protected abstract Class<? extends SuspendNodeStrategy> defineStopNodeStrategy();
|
||||
|
||||
protected abstract Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy();
|
||||
|
||||
protected abstract Class<? extends ListNodesStrategy> defineListNodesStrategy();
|
||||
|
|
|
@ -26,6 +26,7 @@ import javax.inject.Singleton;
|
|||
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.predicates.NodeRunning;
|
||||
import org.jclouds.compute.predicates.NodeSuspended;
|
||||
import org.jclouds.compute.predicates.NodeTerminated;
|
||||
import org.jclouds.compute.predicates.ScriptStatusReturnsZero;
|
||||
import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient;
|
||||
|
@ -58,6 +59,15 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
|
|||
return timeouts.nodeTerminated == 0 ? stateTerminated : new RetryablePredicate<NodeMetadata>(stateTerminated,
|
||||
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
|
||||
@Singleton
|
||||
|
|
|
@ -38,6 +38,8 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
|
|||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
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.suppliers.DefaultLocationSupplier;
|
||||
import org.jclouds.domain.Location;
|
||||
|
@ -82,7 +84,7 @@ public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseCompu
|
|||
@Provides
|
||||
@Singleton
|
||||
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>>() {
|
||||
|
||||
@Override
|
||||
|
@ -96,7 +98,7 @@ public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseCompu
|
|||
@Provides
|
||||
@Singleton
|
||||
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>>() {
|
||||
|
||||
@Override
|
||||
|
@ -115,7 +117,7 @@ public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseCompu
|
|||
@Provides
|
||||
@Singleton
|
||||
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>>() {
|
||||
|
||||
@Override
|
||||
|
@ -156,6 +158,18 @@ public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseCompu
|
|||
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
|
||||
public static enum IdentityFunction implements Function<Object, Object> {
|
||||
INSTANCE;
|
||||
|
|
|
@ -116,9 +116,9 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
|
||||
@Inject
|
||||
protected TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,
|
||||
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,
|
||||
Supplier<Location> defaultLocation2, Provider<TemplateOptions> optionsProvider,
|
||||
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider) {
|
||||
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,
|
||||
Supplier<Location> defaultLocation2, Provider<TemplateOptions> optionsProvider,
|
||||
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider) {
|
||||
this.locations = locations;
|
||||
this.images = images;
|
||||
this.hardwares = hardwares;
|
||||
|
@ -140,7 +140,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
boolean returnVal = true;
|
||||
if (location != null && input.getLocation() != null)
|
||||
returnVal = location.equals(input.getLocation()) || location.getParent() != null
|
||||
&& location.getParent().equals(input.getLocation());
|
||||
&& location.getParent().equals(input.getLocation());
|
||||
return returnVal;
|
||||
}
|
||||
|
||||
|
@ -214,7 +214,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
returnVal = false;
|
||||
else
|
||||
returnVal = input.getDescription().contains(osDescription)
|
||||
|| input.getDescription().matches(osDescription);
|
||||
|| input.getDescription().matches(osDescription);
|
||||
}
|
||||
return returnVal;
|
||||
}
|
||||
|
@ -328,8 +328,8 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
returnVal = false;
|
||||
else
|
||||
returnVal = input.getDescription().equals(imageDescription)
|
||||
|| input.getDescription().contains(imageDescription)
|
||||
|| input.getDescription().matches(imageDescription);
|
||||
|| input.getDescription().contains(imageDescription)
|
||||
|| input.getDescription().matches(imageDescription);
|
||||
}
|
||||
return returnVal;
|
||||
}
|
||||
|
@ -384,12 +384,12 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
}
|
||||
};
|
||||
private final Predicate<Hardware> hardwarePredicate = and(hardwareIdPredicate, locationPredicate,
|
||||
hardwareCoresPredicate, hardwareRamPredicate);
|
||||
hardwareCoresPredicate, hardwareRamPredicate);
|
||||
|
||||
static final Ordering<Hardware> DEFAULT_SIZE_ORDERING = new Ordering<Hardware>() {
|
||||
public int compare(Hardware left, Hardware right) {
|
||||
return ComparisonChain.start().compare(getCores(left), getCores(right)).compare(left.getRam(), right.getRam())
|
||||
.compare(getSpace(left), getSpace(right)).result();
|
||||
.compare(getSpace(left), getSpace(right)).result();
|
||||
}
|
||||
};
|
||||
static final Ordering<Hardware> BY_CORES_ORDERING = new Ordering<Hardware>() {
|
||||
|
@ -399,16 +399,16 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
};
|
||||
static final Ordering<Image> DEFAULT_IMAGE_ORDERING = new Ordering<Image>() {
|
||||
public int compare(Image left, Image right) {
|
||||
return ComparisonChain.start()
|
||||
.compare(left.getName(), right.getName(), Ordering.<String> natural().nullsLast())
|
||||
.compare(left.getVersion(), right.getVersion(), Ordering.<String> natural().nullsLast())
|
||||
.compare(left.getOperatingSystem().getName(), right.getOperatingSystem().getName(),//
|
||||
Ordering.<String> natural().nullsLast())
|
||||
.compare(left.getOperatingSystem().getVersion(), right.getOperatingSystem().getVersion(),//
|
||||
Ordering.<String> natural().nullsLast())
|
||||
.compare(left.getOperatingSystem().getDescription(), right.getOperatingSystem().getDescription(),//
|
||||
Ordering.<String> natural().nullsLast())
|
||||
.compare(left.getOperatingSystem().getArch(), right.getOperatingSystem().getArch()).result();
|
||||
return ComparisonChain.start().compare(left.getName(), right.getName(),
|
||||
Ordering.<String> natural().nullsLast()).compare(left.getVersion(), right.getVersion(),
|
||||
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getName(),
|
||||
right.getOperatingSystem().getName(),//
|
||||
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getVersion(),
|
||||
right.getOperatingSystem().getVersion(),//
|
||||
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getDescription(),
|
||||
right.getOperatingSystem().getDescription(),//
|
||||
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getArch(),
|
||||
right.getOperatingSystem().getArch()).result();
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -427,19 +427,23 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
*/
|
||||
@Override
|
||||
public TemplateBuilder fromHardware(Hardware hardware) {
|
||||
if (hardware.getLocation() != null)
|
||||
if (currentLocationWiderThan(hardware.getLocation()))
|
||||
this.location = hardware.getLocation();
|
||||
this.minCores = getCores(hardware);
|
||||
this.minRam = hardware.getRam();
|
||||
return this;
|
||||
}
|
||||
|
||||
private boolean currentLocationWiderThan(Location location) {
|
||||
return this.location == null || (location != null && this.location.getScope().compareTo(location.getScope()) < 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public TemplateBuilder fromImage(Image image) {
|
||||
if (image.getLocation() != null)
|
||||
if (currentLocationWiderThan(image.getLocation()))
|
||||
this.location = image.getLocation();
|
||||
if (image.getOperatingSystem().getFamily() != null)
|
||||
this.osFamily = image.getOperatingSystem().getFamily();
|
||||
|
@ -539,7 +543,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
Iterable<? extends Image> supportedImages = filter(images, buildImagePredicate());
|
||||
if (Iterables.size(supportedImages) == 0)
|
||||
throw new NoSuchElementException(String.format(
|
||||
"no image matched predicate %s images that didn't match below:\n%s", imagePredicate, images));
|
||||
"no image matched predicate %s images that didn't match below:\n%s", imagePredicate, images));
|
||||
Hardware hardware = resolveSize(hardwareSorter(), supportedImages);
|
||||
Image image = resolveImage(hardware, supportedImages);
|
||||
logger.debug("<< matched image(%s)", image);
|
||||
|
@ -552,29 +556,29 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
Hardware hardware;
|
||||
try {
|
||||
Iterable<? extends Hardware> hardwaresThatAreCompatibleWithOurImages = filter(hardwaresl,
|
||||
new Predicate<Hardware>() {
|
||||
@Override
|
||||
public boolean apply(final Hardware hardware) {
|
||||
return Iterables.any(images, new Predicate<Image>() {
|
||||
new Predicate<Hardware>() {
|
||||
@Override
|
||||
public boolean apply(final Hardware hardware) {
|
||||
return Iterables.any(images, new Predicate<Image>() {
|
||||
|
||||
@Override
|
||||
public boolean apply(Image input) {
|
||||
return hardware.supportsImage().apply(input);
|
||||
}
|
||||
@Override
|
||||
public boolean apply(Image input) {
|
||||
return hardware.supportsImage().apply(input);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "hardware(" + hardware + ").supportsImage()";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "hardware(" + hardware + ").supportsImage()";
|
||||
}
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
hardware = hardwareOrdering.max(filter(hardwaresThatAreCompatibleWithOurImages, hardwarePredicate));
|
||||
} catch (NoSuchElementException exception) {
|
||||
throw new NoSuchElementException("hardwares don't support any images: " + toString() + "\n" + hardwaresl
|
||||
+ "\n" + images);
|
||||
+ "\n" + images);
|
||||
}
|
||||
logger.debug("<< matched hardware(%s)", hardware);
|
||||
return hardware;
|
||||
|
@ -682,7 +686,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
// looks verbose, but explicit <Image> type needed for this to compile
|
||||
// properly
|
||||
Predicate<Image> imagePredicate = predicates.size() == 1 ? Iterables.<Predicate<Image>> get(predicates, 0)
|
||||
: Predicates.<Image> and(predicates);
|
||||
: Predicates.<Image> and(predicates);
|
||||
return imagePredicate;
|
||||
}
|
||||
|
||||
|
@ -830,8 +834,9 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
@VisibleForTesting
|
||||
boolean nothingChangedExceptOptions() {
|
||||
return osFamily == null && location == null && imageId == null && hardwareId == null && osName == null
|
||||
&& osDescription == null && imageVersion == null && osVersion == null && osArch == null && os64Bit == null
|
||||
&& imageName == null && imageDescription == null && minCores == 0 && minRam == 0 && !biggest && !fastest;
|
||||
&& osDescription == null && imageVersion == null && osVersion == null && osArch == null
|
||||
&& os64Bit == null && imageName == null && imageDescription == null && minCores == 0 && minRam == 0
|
||||
&& !biggest && !fastest;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -845,10 +850,10 @@ public class TemplateBuilderImpl implements TemplateBuilder {
|
|||
@Override
|
||||
public String toString() {
|
||||
return "[biggest=" + biggest + ", fastest=" + fastest + ", imageName=" + imageName + ", imageDescription="
|
||||
+ imageDescription + ", imageId=" + imageId + ", imageVersion=" + imageVersion + ", location=" + location
|
||||
+ ", minCores=" + minCores + ", minRam=" + minRam + ", osFamily=" + osFamily + ", osName=" + osName
|
||||
+ ", osDescription=" + osDescription + ", osVersion=" + osVersion + ", osArch=" + osArch + ", os64Bit="
|
||||
+ os64Bit + ", hardwareId=" + hardwareId + "]";
|
||||
+ imageDescription + ", imageId=" + imageId + ", imageVersion=" + imageVersion + ", location="
|
||||
+ location + ", minCores=" + minCores + ", minRam=" + minRam + ", osFamily=" + osFamily + ", osName="
|
||||
+ osName + ", osDescription=" + osDescription + ", osVersion=" + osVersion + ", osArch=" + osArch
|
||||
+ ", os64Bit=" + os64Bit + ", hardwareId=" + hardwareId + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -74,7 +74,9 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
|
|||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
import org.jclouds.compute.strategy.RebootNodeStrategy;
|
||||
import org.jclouds.compute.strategy.ResumeNodeStrategy;
|
||||
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
|
||||
import org.jclouds.compute.strategy.SuspendNodeStrategy;
|
||||
import org.jclouds.compute.util.ComputeUtils;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.domain.Location;
|
||||
|
@ -111,10 +113,13 @@ public class BaseComputeService implements ComputeService {
|
|||
protected final RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy;
|
||||
protected final RebootNodeStrategy rebootNodeStrategy;
|
||||
protected final DestroyNodeStrategy destroyNodeStrategy;
|
||||
protected final ResumeNodeStrategy resumeNodeStrategy;
|
||||
protected final SuspendNodeStrategy suspendNodeStrategy;
|
||||
protected final Provider<TemplateBuilder> templateBuilderProvider;
|
||||
protected final Provider<TemplateOptions> templateOptionsProvider;
|
||||
protected final Predicate<NodeMetadata> nodeRunning;
|
||||
protected final Predicate<NodeMetadata> nodeTerminated;
|
||||
protected final Predicate<NodeMetadata> nodeSuspended;
|
||||
protected final ComputeUtils utils;
|
||||
protected final Timeouts timeouts;
|
||||
protected final ExecutorService executor;
|
||||
|
@ -126,9 +131,11 @@ public class BaseComputeService implements ComputeService {
|
|||
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
|
||||
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
|
||||
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
|
||||
ResumeNodeStrategy resumeNodeStrategy, SuspendNodeStrategy suspendNodeStrategy,
|
||||
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
|
||||
@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) {
|
||||
this.context = checkNotNull(context, "context");
|
||||
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
|
||||
|
@ -139,11 +146,14 @@ public class BaseComputeService implements ComputeService {
|
|||
this.getNodeMetadataStrategy = checkNotNull(getNodeMetadataStrategy, "getNodeMetadataStrategy");
|
||||
this.runNodesAndAddToSetStrategy = checkNotNull(runNodesAndAddToSetStrategy, "runNodesAndAddToSetStrategy");
|
||||
this.rebootNodeStrategy = checkNotNull(rebootNodeStrategy, "rebootNodeStrategy");
|
||||
this.resumeNodeStrategy = checkNotNull(resumeNodeStrategy, "resumeNodeStrategy");
|
||||
this.suspendNodeStrategy = checkNotNull(suspendNodeStrategy, "suspendNodeStrategy");
|
||||
this.destroyNodeStrategy = checkNotNull(destroyNodeStrategy, "destroyNodeStrategy");
|
||||
this.templateBuilderProvider = checkNotNull(templateBuilderProvider, "templateBuilderProvider");
|
||||
this.templateOptionsProvider = checkNotNull(templateOptionsProvider, "templateOptionsProvider");
|
||||
this.nodeRunning = checkNotNull(nodeRunning, "nodeRunning");
|
||||
this.nodeTerminated = checkNotNull(nodeTerminated, "nodeTerminated");
|
||||
this.nodeSuspended = checkNotNull(nodeSuspended, "nodeSuspended");
|
||||
this.utils = checkNotNull(utils, "utils");
|
||||
this.timeouts = checkNotNull(timeouts, "timeouts");
|
||||
this.executor = checkNotNull(executor, "executor");
|
||||
|
@ -174,10 +184,10 @@ public class BaseComputeService implements ComputeService {
|
|||
Set<NodeMetadata> nodes = newHashSet();
|
||||
Map<NodeMetadata, Exception> badNodes = newLinkedHashMap();
|
||||
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()))
|
||||
if (node.getCredentials() != null)
|
||||
credentialStore.put("node/" + node.getId(), node.getCredentials());
|
||||
credentialStore.put("node#" + node.getId(), node.getCredentials());
|
||||
if (executionExceptions.size() > 0 || badNodes.size() > 0) {
|
||||
throw new RunNodesException(tag, count, template, nodes, executionExceptions, badNodes);
|
||||
}
|
||||
|
@ -227,7 +237,7 @@ public class BaseComputeService implements ComputeService {
|
|||
}, timeouts.nodeRunning, 1000, TimeUnit.MILLISECONDS);
|
||||
boolean successful = tester.apply(id) && (node.get() == null || nodeTerminated.apply(node.get()));
|
||||
if (successful)
|
||||
credentialStore.remove("node/" + id);
|
||||
credentialStore.remove("node#" + id);
|
||||
logger.debug("<< destroyed node(%s) success(%s)", id, successful);
|
||||
}
|
||||
|
||||
|
@ -357,6 +367,66 @@ public class BaseComputeService implements ComputeService {
|
|||
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}
|
||||
*/
|
||||
|
|
|
@ -0,0 +1,70 @@
|
|||
/**
|
||||
*
|
||||
* 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.compute.predicates;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.ComputeService;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.domain.NodeState;
|
||||
import org.jclouds.logging.Logger;
|
||||
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
/**
|
||||
*
|
||||
* Tests to see if a node is active.
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class NodePresentAndInIntendedState implements Predicate<NodeMetadata> {
|
||||
|
||||
private final ComputeService client;
|
||||
private final NodeState intended;
|
||||
@Resource
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
||||
@Inject
|
||||
public NodePresentAndInIntendedState(NodeState intended, ComputeService client) {
|
||||
this.intended = intended;
|
||||
this.client = 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(), intended, node.getState());
|
||||
if (node.getState() == NodeState.ERROR)
|
||||
throw new IllegalStateException("node " + node.getId() + " in location " + node.getLocation()
|
||||
+ " is in error state");
|
||||
return node.getState() == intended;
|
||||
}
|
||||
|
||||
private NodeMetadata refresh(NodeMetadata node) {
|
||||
return client.getNodeMetadata(node.getId());
|
||||
}
|
||||
}
|
|
@ -19,52 +19,24 @@
|
|||
|
||||
package org.jclouds.compute.predicates;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.ComputeService;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.domain.NodeState;
|
||||
import org.jclouds.logging.Logger;
|
||||
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
/**
|
||||
*
|
||||
* Tests to see if a node is active.
|
||||
* Tests to see if a node is running.
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class NodeRunning implements Predicate<NodeMetadata> {
|
||||
|
||||
private final ComputeService client;
|
||||
|
||||
@Resource
|
||||
protected Logger logger = Logger.NULL;
|
||||
public class NodeRunning extends NodePresentAndInIntendedState {
|
||||
|
||||
@Inject
|
||||
public NodeRunning(ComputeService client) {
|
||||
this.client = 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());
|
||||
super(NodeState.RUNNING, client);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,30 +17,26 @@
|
|||
* ====================================================================
|
||||
*/
|
||||
|
||||
package org.jclouds.gogrid.util;
|
||||
package org.jclouds.compute.predicates;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.ComputeService;
|
||||
import org.jclouds.compute.domain.NodeState;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
|
||||
/**
|
||||
* @author Oleksiy Yarmula
|
||||
*
|
||||
* Tests to see if a node is suspended.
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
public class GoGridUtils {
|
||||
|
||||
/**
|
||||
* Matches nth group or returns null.
|
||||
*
|
||||
* @param stringToParse string that the pattern will be applied to
|
||||
* @param pattern regular expression {@link java.util.regex.Pattern pattern}
|
||||
* @param nthGroup number of the group to extract / return
|
||||
* @return matched group or null
|
||||
*/
|
||||
public static String parseStringByPatternAndGetNthMatchGroup(String stringToParse, Pattern pattern, int nthGroup) {
|
||||
Matcher osVersionMatcher = pattern.matcher(stringToParse);
|
||||
if (osVersionMatcher.find()) {
|
||||
return osVersionMatcher.group(nthGroup);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Singleton
|
||||
public class NodeSuspended extends NodePresentAndInIntendedState {
|
||||
|
||||
@Inject
|
||||
public NodeSuspended(ComputeService client) {
|
||||
super(NodeState.SUSPENDED, client);
|
||||
}
|
||||
}
|
|
@ -34,6 +34,7 @@ public interface ComputeServiceConstants {
|
|||
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_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_PORT_OPEN = "jclouds.compute.timeout.port-open";
|
||||
/**
|
||||
|
@ -51,7 +52,11 @@ public interface ComputeServiceConstants {
|
|||
@Inject(optional = true)
|
||||
@Named(PROPERTY_TIMEOUT_NODE_RUNNING)
|
||||
public long nodeRunning = 1200 * 1000;
|
||||
|
||||
|
||||
@Inject(optional = true)
|
||||
@Named(PROPERTY_TIMEOUT_NODE_SUSPENDED)
|
||||
public long nodeSuspended = 30 * 1000;
|
||||
|
||||
@Inject(optional = true)
|
||||
@Named(PROPERTY_TIMEOUT_SCRIPT_COMPLETE)
|
||||
public long scriptComplete = 600 * 1000;
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
*
|
||||
* 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.compute.strategy;
|
||||
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
|
||||
/**
|
||||
* Resumes a node from the state {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended}
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
public interface ResumeNodeStrategy {
|
||||
|
||||
NodeMetadata resumeNode(String id);
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
*
|
||||
* 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.compute.strategy;
|
||||
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
|
||||
/**
|
||||
* Reboots a node unless it is in the state {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended}
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
public interface SuspendNodeStrategy {
|
||||
|
||||
NodeMetadata suspendNode(String id);
|
||||
|
||||
}
|
|
@ -41,6 +41,8 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
|
|||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
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.logging.Logger;
|
||||
|
||||
|
@ -54,7 +56,7 @@ import com.google.common.collect.Iterables;
|
|||
*/
|
||||
@Singleton
|
||||
public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWithTagStrategy, DestroyNodeStrategy,
|
||||
GetNodeMetadataStrategy, ListNodesStrategy, RebootNodeStrategy {
|
||||
GetNodeMetadataStrategy, ListNodesStrategy, RebootNodeStrategy, ResumeNodeStrategy, SuspendNodeStrategy {
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
protected Logger logger = Logger.NULL;
|
||||
|
@ -65,7 +67,7 @@ public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWith
|
|||
|
||||
@Inject
|
||||
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.client = checkNotNull(client, "client");
|
||||
this.nodeMetadataAdapter = checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter");
|
||||
|
@ -101,6 +103,34 @@ public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWith
|
|||
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
|
||||
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);
|
||||
|
||||
logger.debug(">> instantiating node location(%s) name(%s) image(%s) hardware(%s)",
|
||||
template.getLocation().getId(), name, template.getImage().getProviderId(), template.getHardware()
|
||||
.getProviderId());
|
||||
template.getLocation().getId(), name, template.getImage().getProviderId(), template.getHardware()
|
||||
.getProviderId());
|
||||
|
||||
N from = client.runNodeWithTagAndNameAndStoreCredentials(tag, name, template, credentialStore);
|
||||
NodeMetadata node = nodeMetadataAdapter.apply(from);
|
||||
|
|
|
@ -63,9 +63,9 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
|
|||
|
||||
@Inject
|
||||
public StubComputeServiceAdapter(ConcurrentMap<String, NodeMetadata> nodes, Supplier<Location> location,
|
||||
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
|
||||
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix,
|
||||
@org.jclouds.rest.annotations.Provider String providerName) {
|
||||
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
|
||||
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix,
|
||||
@org.jclouds.rest.annotations.Provider String providerName) {
|
||||
this.nodes = nodes;
|
||||
this.location = location;
|
||||
this.idProvider = idProvider;
|
||||
|
@ -77,7 +77,7 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
|
|||
|
||||
@Override
|
||||
public NodeMetadata runNodeWithTagAndNameAndStoreCredentials(String tag, String name, Template template,
|
||||
Map<String, Credentials> credentialStore) {
|
||||
Map<String, Credentials> credentialStore) {
|
||||
NodeMetadataBuilder builder = new NodeMetadataBuilder();
|
||||
String id = idProvider.get() + "";
|
||||
builder.ids(id);
|
||||
|
@ -91,8 +91,8 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
|
|||
builder.privateAddresses(ImmutableSet.<String> of(privateIpPrefix + id));
|
||||
builder.credentials(new Credentials("root", passwordPrefix + id));
|
||||
NodeMetadata node = builder.build();
|
||||
credentialStore.put("node#" + node.getId(), node.getCredentials());
|
||||
nodes.put(node.getId(), node);
|
||||
credentialStore.put(node.getId(), node.getCredentials());
|
||||
StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 100);
|
||||
return node;
|
||||
}
|
||||
|
@ -100,8 +100,8 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
|
|||
@Override
|
||||
public Iterable<Hardware> listHardwareProfiles() {
|
||||
return ImmutableSet.<Hardware> of(StubComputeServiceDependenciesModule.stub("small", 1, 1740, 160),
|
||||
StubComputeServiceDependenciesModule.stub("medium", 4, 7680, 850),
|
||||
StubComputeServiceDependenciesModule.stub("large", 8, 15360, 1690));
|
||||
StubComputeServiceDependenciesModule.stub("medium", 4, 7680, 850), StubComputeServiceDependenciesModule
|
||||
.stub("large", 8, 15360, 1690));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -109,34 +109,20 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
|
|||
Location zone = location.get().getParent();
|
||||
String parentId = zone.getId();
|
||||
Credentials defaultCredentials = new Credentials("root", null);
|
||||
return ImmutableSet
|
||||
.<Image> of(
|
||||
new ImageBuilder()
|
||||
.providerId("1")
|
||||
.name(OsFamily.UBUNTU.name())
|
||||
.id(parentId + "/1")
|
||||
.location(zone)
|
||||
return ImmutableSet.<Image> of(new ImageBuilder().providerId("1").name(OsFamily.UBUNTU.name())
|
||||
.id(parentId + "/1").location(zone).operatingSystem(
|
||||
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32", false))
|
||||
.description("stub ubuntu 32").defaultCredentials(defaultCredentials).build(), //
|
||||
new ImageBuilder().providerId("2").name(OsFamily.UBUNTU.name()).id(parentId + "/2").location(zone)
|
||||
.operatingSystem(
|
||||
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32", false))
|
||||
.description("stub ubuntu 32").defaultCredentials(defaultCredentials).build(), //
|
||||
new ImageBuilder()
|
||||
.providerId("2")
|
||||
.name(OsFamily.UBUNTU.name())
|
||||
.id(parentId + "/2")
|
||||
.location(zone)
|
||||
.operatingSystem(
|
||||
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64", "ubuntu 64", true))
|
||||
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64", "ubuntu 64", true))
|
||||
.description("stub ubuntu 64").defaultCredentials(defaultCredentials).build(), //
|
||||
new ImageBuilder()
|
||||
.providerId("3")
|
||||
.name(OsFamily.CENTOS.name())
|
||||
.id(parentId + "/3")
|
||||
.location(zone)
|
||||
new ImageBuilder().providerId("3").name(OsFamily.CENTOS.name()).id(parentId + "/3").location(zone)
|
||||
.operatingSystem(
|
||||
new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64", "centos 64", true))
|
||||
new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64", "centos 64", true))
|
||||
.description("stub centos 64").defaultCredentials(defaultCredentials).build() //
|
||||
|
||||
);
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -148,9 +134,9 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
|
|||
public Iterable<Location> listLocations() {
|
||||
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
|
||||
Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region",
|
||||
provider);
|
||||
provider);
|
||||
return ImmutableSet.<Location> of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName
|
||||
+ "zone", region));
|
||||
+ "zone", region));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -189,4 +175,30 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
|
|||
StubComputeServiceDependenciesModule.setState(node, NodeState.PENDING, 0);
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -19,15 +19,8 @@
|
|||
|
||||
package org.jclouds.compute.stub.config;
|
||||
|
||||
import org.jclouds.compute.ComputeServiceAdapter;
|
||||
import org.jclouds.compute.config.JCloudsNativeStandaloneComputeServiceContextModule;
|
||||
import org.jclouds.compute.domain.Hardware;
|
||||
import org.jclouds.compute.domain.Image;
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.concurrent.SingleThreaded;
|
||||
import org.jclouds.domain.Location;
|
||||
|
||||
import com.google.inject.TypeLiteral;
|
||||
|
||||
/**
|
||||
*
|
||||
|
@ -43,8 +36,6 @@ public class StubComputeServiceContextModule extends JCloudsNativeStandaloneComp
|
|||
@Override
|
||||
protected void configure() {
|
||||
install(new StubComputeServiceDependenciesModule());
|
||||
bind(new TypeLiteral<ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location>>() {
|
||||
}).to(StubComputeServiceAdapter.class);
|
||||
super.configure();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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(),
|
||||
timeouts.nodeRunning / 1000, node.getState()));
|
||||
List<Statement> bootstrap = newArrayList();
|
||||
if (options.getRunScript() != null)
|
||||
bootstrap.add(options.getRunScript());
|
||||
if (options.getPublicKey() != null)
|
||||
bootstrap.add(new AuthorizeRSAPublicKey(options.getPublicKey()));
|
||||
if (options.getRunScript() != null)
|
||||
bootstrap.add(options.getRunScript());
|
||||
if (options.getPrivateKey() != null)
|
||||
bootstrap.add(new InstallRSAPrivateKey(options.getPrivateKey()));
|
||||
if (bootstrap.size() >= 1)
|
||||
|
|
|
@ -74,6 +74,7 @@ import org.jclouds.net.IPSocket;
|
|||
import org.jclouds.predicates.RetryablePredicate;
|
||||
import org.jclouds.predicates.SocketOpen;
|
||||
import org.jclouds.rest.AuthorizationException;
|
||||
import org.jclouds.scriptbuilder.domain.OsFamily;
|
||||
import org.jclouds.ssh.ExecResponse;
|
||||
import org.jclouds.ssh.SshClient;
|
||||
import org.jclouds.ssh.SshException;
|
||||
|
@ -82,7 +83,9 @@ import org.testng.annotations.BeforeGroups;
|
|||
import org.testng.annotations.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.inject.Guice;
|
||||
import com.google.inject.Module;
|
||||
|
||||
|
@ -236,37 +239,11 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
assertEquals(toMatch.getImage(), template.getImage());
|
||||
}
|
||||
|
||||
@Test(enabled = true, dependsOnMethods = "testCompareSizes")
|
||||
public void testCreateAndRunAService() throws Exception {
|
||||
|
||||
String tag = this.tag + "service";
|
||||
try {
|
||||
client.destroyNodesMatching(withTag(tag));
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080))
|
||||
.build();
|
||||
// note this is a dependency on the template resolution
|
||||
template.getOptions().runScript(
|
||||
RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage()
|
||||
.getOperatingSystem()));
|
||||
try {
|
||||
NodeMetadata node = getOnlyElement(client.runNodesWithTag(tag, 1, template));
|
||||
|
||||
checkHttpGet(node);
|
||||
} finally {
|
||||
client.destroyNodesMatching(withTag(tag));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected void checkHttpGet(NodeMetadata node) {
|
||||
ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080);
|
||||
}
|
||||
|
||||
@Test(enabled = true, dependsOnMethods = "testCreateAndRunAService")
|
||||
@Test(enabled = true, dependsOnMethods = "testCompareSizes")
|
||||
public void testCreateTwoNodesWithRunScript() throws Exception {
|
||||
try {
|
||||
client.destroyNodesMatching(withTag(tag));
|
||||
|
@ -299,7 +276,7 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
template = buildTemplate(client.templateBuilder());
|
||||
|
||||
template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public"))
|
||||
.runScript(newStringPayload(buildScript(template.getImage().getOperatingSystem())));
|
||||
.runScript(buildScript(template.getImage().getOperatingSystem()));
|
||||
}
|
||||
|
||||
protected void checkImageIdMatchesTemplate(NodeMetadata node) {
|
||||
|
@ -339,14 +316,14 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
public void testCredentialsCache() throws Exception {
|
||||
initializeContextAndClient();
|
||||
for (NodeMetadata node : nodes)
|
||||
assert (context.getCredentialStore().get(node.getId()) != null) : "credentials for " + node.getId();
|
||||
assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId();
|
||||
}
|
||||
|
||||
protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String tag, OperatingSystem os,
|
||||
Credentials creds) throws RunScriptOnNodesException {
|
||||
try {
|
||||
return client.runScriptOnNodesMatching(runningWithTag(tag), newStringPayload(buildScript(os)),
|
||||
overrideCredentialsWith(creds).nameTask("runScriptWithCreds"));
|
||||
return client.runScriptOnNodesMatching(runningWithTag(tag), newStringPayload(buildScript(os).render(
|
||||
OsFamily.UNIX)), overrideCredentialsWith(creds).nameTask("runScriptWithCreds"));
|
||||
} catch (SshException e) {
|
||||
throw e;
|
||||
}
|
||||
|
@ -358,7 +335,7 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
assertNotNull(node.getTag());
|
||||
assertEquals(node.getTag(), tag);
|
||||
assertEquals(node.getState(), NodeState.RUNNING);
|
||||
Credentials fromStore = context.getCredentialStore().get(node.getId());
|
||||
Credentials fromStore = context.getCredentialStore().get("node#" + node.getId());
|
||||
assertEquals(fromStore, node.getCredentials());
|
||||
assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node;
|
||||
assertNotNull(node.getCredentials());
|
||||
|
@ -413,13 +390,25 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
testGet();
|
||||
}
|
||||
|
||||
@Test(enabled = true/* , dependsOnMethods = "testCompareSizes" */)
|
||||
public void testTemplateOptions() throws Exception {
|
||||
TemplateOptions options = new TemplateOptions().withMetadata();
|
||||
Template t = client.templateBuilder().smallest().options(options).build();
|
||||
assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template";
|
||||
@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();
|
||||
}
|
||||
|
||||
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
|
||||
public void testListNodes() throws Exception {
|
||||
for (ComputeMetadata node : client.listNodes()) {
|
||||
assert node.getProviderId() != null;
|
||||
|
@ -428,6 +417,7 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
}
|
||||
}
|
||||
|
||||
@Test(enabled = true, dependsOnMethods = "testSuspendResume")
|
||||
public void testGetNodesWithDetails() throws Exception {
|
||||
for (NodeMetadata node : client.listNodesDetailsMatching(all())) {
|
||||
assert node.getProviderId() != null : node;
|
||||
|
@ -448,6 +438,52 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
}
|
||||
}
|
||||
|
||||
@Test(enabled = true, dependsOnMethods = { "testListNodes", "testGetNodesWithDetails" })
|
||||
public void testDestroyNodes() {
|
||||
client.destroyNodesMatching(withTag(tag));
|
||||
for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), withTag(tag))) {
|
||||
assert node.getState() == NodeState.TERMINATED : node;
|
||||
assertEquals(context.getCredentialStore().get("node#" + node.getId()), null);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<? extends NodeMetadata> refreshNodes() {
|
||||
return filter(client.listNodesDetailsMatching(all()), and(withTag(tag), not(TERMINATED)));
|
||||
}
|
||||
|
||||
@Test(enabled = true)
|
||||
public void testCreateAndRunAService() throws Exception {
|
||||
|
||||
String tag = this.tag + "service";
|
||||
try {
|
||||
client.destroyNodesMatching(withTag(tag));
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080))
|
||||
.build();
|
||||
// note this is a dependency on the template resolution
|
||||
template.getOptions().runScript(
|
||||
RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage()
|
||||
.getOperatingSystem()));
|
||||
try {
|
||||
NodeMetadata node = getOnlyElement(client.runNodesWithTag(tag, 1, template));
|
||||
|
||||
checkHttpGet(node);
|
||||
} finally {
|
||||
client.destroyNodesMatching(withTag(tag));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test(enabled = true/* , dependsOnMethods = "testCompareSizes" */)
|
||||
public void testTemplateOptions() throws Exception {
|
||||
TemplateOptions options = new TemplateOptions().withMetadata();
|
||||
Template t = client.templateBuilder().smallest().options(options).build();
|
||||
assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template";
|
||||
}
|
||||
|
||||
public void testListImages() throws Exception {
|
||||
for (Image image : client.listImages()) {
|
||||
assert image.getProviderId() != null : image;
|
||||
|
@ -488,7 +524,6 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
}
|
||||
}
|
||||
|
||||
@Test(enabled = true, dependsOnMethods = "testGet")
|
||||
public void testOptionToNotBlock() throws Exception {
|
||||
String tag = this.tag + "block";
|
||||
try {
|
||||
|
@ -571,7 +606,8 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
ExecResponse hello = ssh.exec("echo hello");
|
||||
assertEquals(hello.getOutput().trim(), "hello");
|
||||
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 {
|
||||
if (ssh != null)
|
||||
ssh.disconnect();
|
||||
|
@ -581,11 +617,7 @@ public abstract class BaseComputeServiceLiveTest {
|
|||
@AfterTest
|
||||
protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException {
|
||||
if (nodes != null) {
|
||||
client.destroyNodesMatching(withTag(tag));
|
||||
for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), withTag(tag))) {
|
||||
assert node.getState() == NodeState.TERMINATED : node;
|
||||
assertEquals(context.getCredentialStore().get(node.getId()), null);
|
||||
}
|
||||
testDestroyNodes();
|
||||
}
|
||||
context.close();
|
||||
}
|
||||
|
|
|
@ -19,7 +19,11 @@
|
|||
|
||||
package org.jclouds.compute;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
import static com.google.common.collect.Iterables.get;
|
||||
import static org.jclouds.util.Utils.checkNotEmpty;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
|
@ -27,18 +31,15 @@ import java.lang.reflect.UndeclaredThrowableException;
|
|||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
|
||||
import org.jclouds.compute.domain.NodeMetadata;
|
||||
import org.jclouds.compute.domain.OperatingSystem;
|
||||
import org.jclouds.compute.predicates.OperatingSystemPredicates;
|
||||
import org.jclouds.rest.HttpClient;
|
||||
import org.jclouds.scriptbuilder.domain.Statement;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.io.Files;
|
||||
import static com.google.common.collect.Iterables.get;
|
||||
|
||||
/**
|
||||
* utilities helpful in testing compute providers
|
||||
|
@ -46,15 +47,8 @@ import static com.google.common.collect.Iterables.get;
|
|||
* @author Adrian Cole
|
||||
*/
|
||||
public class ComputeTestUtils {
|
||||
public static String buildScript(OperatingSystem os) {
|
||||
if (OperatingSystemPredicates.supportsApt().apply(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 Statement buildScript(OperatingSystem os) {
|
||||
return RunScriptData.installJavaAndCurl(os);
|
||||
}
|
||||
|
||||
public static Map<String, String> setupKeyPair() throws FileNotFoundException, IOException {
|
||||
|
@ -67,8 +61,8 @@ public class ComputeTestUtils {
|
|||
checkSecretKeyFile(secretKeyFile);
|
||||
String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8);
|
||||
assert secret.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + secret;
|
||||
return ImmutableMap.<String, String> of("private", secret, "public",
|
||||
Files.toString(new File(secretKeyFile + ".pub"), Charsets.UTF_8));
|
||||
return ImmutableMap.<String, String> of("private", secret, "public", Files.toString(new File(secretKeyFile
|
||||
+ ".pub"), Charsets.UTF_8));
|
||||
}
|
||||
|
||||
public static void checkSecretKeyFile(String secretKeyFile) throws FileNotFoundException {
|
||||
|
|
|
@ -19,9 +19,11 @@
|
|||
|
||||
package org.jclouds.compute;
|
||||
|
||||
import static org.jclouds.compute.util.ComputeServiceUtils.execHttpResponse;
|
||||
import static org.jclouds.compute.util.ComputeServiceUtils.extractTargzIntoDirectory;
|
||||
import static org.jclouds.scriptbuilder.domain.Statements.exec;
|
||||
import static org.jclouds.scriptbuilder.domain.Statements.interpret;
|
||||
import static org.jclouds.scriptbuilder.domain.Statements.newStatementList;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
@ -43,7 +45,7 @@ public class RunScriptData {
|
|||
|
||||
private static String jbossHome = "/usr/local/jboss";
|
||||
|
||||
public static String installJavaAndCurl(OperatingSystem os) {
|
||||
public static Statement installJavaAndCurl(OperatingSystem os) {
|
||||
if (os == null || OperatingSystemPredicates.supportsApt().apply(os))
|
||||
return APT_RUN_SCRIPT;
|
||||
else if (OperatingSystemPredicates.supportsYum().apply(os))
|
||||
|
@ -57,50 +59,62 @@ public class RunScriptData {
|
|||
public static Statement createScriptInstallAndStartJBoss(String publicKey, OperatingSystem os) {
|
||||
Map<String, String> envVariables = ImmutableMap.of("jbossHome", jbossHome);
|
||||
Statement toReturn = new InitBuilder(
|
||||
"jboss",
|
||||
jbossHome,
|
||||
jbossHome,
|
||||
envVariables,
|
||||
ImmutableList.<Statement> of(
|
||||
new AuthorizeRSAPublicKey(publicKey),
|
||||
exec(installJavaAndCurl(os)),
|
||||
exec("rm -rf /var/cache/apt /usr/lib/vmware-tools"),// jeos hasn't enough room!
|
||||
extractTargzIntoDirectory(
|
||||
URI.create("http://commondatastorage.googleapis.com/jclouds-repo/jboss-as-distribution-6.0.0.20100911-M5.tar.gz"),
|
||||
"/usr/local"), exec("{md} " + jbossHome), exec("mv /usr/local/jboss-*/* " + jbossHome),
|
||||
exec("chmod -R oug+r+w " + jbossHome)),
|
||||
ImmutableList
|
||||
.<Statement> of(interpret("java -Xms128m -Xmx512m -XX:MaxPermSize=256m -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.endorsed.dirs=lib/endorsed -classpath bin/run.jar org.jboss.Main -b 0.0.0.0")));
|
||||
"jboss",
|
||||
jbossHome,
|
||||
jbossHome,
|
||||
envVariables,
|
||||
ImmutableList
|
||||
.<Statement> of(
|
||||
new AuthorizeRSAPublicKey(publicKey),//
|
||||
installJavaAndCurl(os),//
|
||||
// just in case iptables are being used, try to open 8080
|
||||
exec("iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT"),//
|
||||
// TODO gogrid rules only allow ports 22, 3389, 80 and 443.
|
||||
// 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-save"),//
|
||||
extractTargzIntoDirectory(
|
||||
URI
|
||||
.create("http://commondatastorage.googleapis.com/jclouds-repo/jboss-as-distribution-6.0.0.20100911-M5.tar.gz"),
|
||||
"/usr/local"), exec("{md} " + jbossHome), exec("mv /usr/local/jboss-*/* "
|
||||
+ jbossHome),//
|
||||
exec("chmod -R oug+r+w " + jbossHome)),//
|
||||
ImmutableList
|
||||
.<Statement> of(interpret("java -Xms128m -Xmx512m -XX:MaxPermSize=256m -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.endorsed.dirs=lib/endorsed -classpath bin/run.jar org.jboss.Main -b 0.0.0.0")));
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
public static final String APT_RUN_SCRIPT = new StringBuilder()//
|
||||
.append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n")//
|
||||
.append("cp /etc/apt/sources.list /etc/apt/sources.list.old\n")//
|
||||
.append(
|
||||
"sed 's~us.archive.ubuntu.com~mirror.anl.gov/pub~g' /etc/apt/sources.list.old >/etc/apt/sources.list\n")//
|
||||
.append("which curl || apt-get update -y -qq && apt-get install -f -y -qq --force-yes curl\n")//
|
||||
.append(
|
||||
"(which java && java -fullversion 2>&1|egrep -q 1.6 ) || apt-get install -f -y -qq --force-yes openjdk-6-jre\n")//
|
||||
.append("rm -rf /var/cache/apt /usr/lib/vmware-tools\n")// jeos hasn't enough room!
|
||||
.toString();
|
||||
public static String aptInstall = "apt-get install -f -y -qq --force-yes";
|
||||
|
||||
public static final String YUM_RUN_SCRIPT = new StringBuilder()
|
||||
.append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n") //
|
||||
.append("echo \"[jdkrepo]\" >> /etc/yum.repos.d/CentOS-Base.repo\n") //
|
||||
.append("echo \"name=jdkrepository\" >> /etc/yum.repos.d/CentOS-Base.repo\n") //
|
||||
.append(
|
||||
"echo \"baseurl=http://ec2-us-east-mirror.rightscale.com/epel/5/i386/\" >> /etc/yum.repos.d/CentOS-Base.repo\n")//
|
||||
.append("echo \"enabled=1\" >> /etc/yum.repos.d/CentOS-Base.repo\n")//
|
||||
.append("which curl ||yum --nogpgcheck -y install curl\n")//
|
||||
.append(
|
||||
"(which java && java -fullversion 2>&1|egrep -q 1.6 ) || yum --nogpgcheck -y install java-1.6.0-openjdk&&")//
|
||||
.append("echo \"export PATH=\\\"/usr/lib/jvm/jre-1.6.0-openjdk/bin/:\\$PATH\\\"\" >> /root/.bashrc\n")//
|
||||
.toString();
|
||||
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 String ZYPPER_RUN_SCRIPT = new StringBuilder()//
|
||||
.append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n")//
|
||||
.append("which curl || zypper install curl\n")//
|
||||
.append("(which java && java -fullversion 2>&1|egrep -q 1.6 ) || zypper install java-1.6.0-openjdk\n")//
|
||||
.toString();
|
||||
public static final Statement APT_RUN_SCRIPT = newStatementList(//
|
||||
exec(installAfterUpdatingIfNotPresent("curl")),//
|
||||
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")),//
|
||||
exec(new StringBuilder()//
|
||||
.append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n")//
|
||||
// jeos hasn't enough room!
|
||||
.append("rm -rf /var/cache/apt /usr/lib/vmware-tools\n")//
|
||||
.append("echo \"export PATH=\\\"\\$JAVA_HOME/bin/:\\$PATH\\\"\" >> /root/.bashrc")//
|
||||
.toString()));
|
||||
|
||||
public static final Statement YUM_RUN_SCRIPT = newStatementList(
|
||||
exec("which curl ||yum --nogpgcheck -y install curl"),//
|
||||
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")),//
|
||||
exec(new StringBuilder()//
|
||||
.append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n") //
|
||||
.append("echo \"export PATH=\\\"\\$JAVA_HOME/bin/:\\$PATH\\\"\" >> /root/.bashrc")//
|
||||
.toString()));
|
||||
|
||||
public static final Statement ZYPPER_RUN_SCRIPT = exec(new StringBuilder()//
|
||||
.append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n")//
|
||||
.append("which curl || zypper install curl\n")//
|
||||
.append("(which java && java -fullversion 2>&1|egrep -q 1.6 ) || zypper install java-1.6.0-openjdk\n")//
|
||||
.toString());
|
||||
}
|
||||
|
|
|
@ -121,48 +121,48 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
|
|||
SshClient client5 = createMock(SshClient.class);
|
||||
|
||||
expect(factory.create(new IPSocket("144.175.1.1", 22), new Credentials("root", "password1"))).andReturn(
|
||||
client1);
|
||||
client1);
|
||||
runScriptAndService(client1, 1);
|
||||
|
||||
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(
|
||||
new SshException("Auth fail"));
|
||||
new SshException("Auth fail"));
|
||||
client2.connect();
|
||||
try {
|
||||
runScript(client2, "runScriptWithCreds", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
|
||||
.getResourceAsStream("/runscript.sh")), 2);
|
||||
.getResourceAsStream("/runscript.sh")), 2);
|
||||
} catch (IOException e) {
|
||||
Throwables.propagate(e);
|
||||
}
|
||||
client2.disconnect();
|
||||
|
||||
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(
|
||||
client4).times(2);
|
||||
client4).times(2);
|
||||
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(client4, "bootstrap", 4);
|
||||
runScriptAndInstallSsh(client5, "bootstrap", 5);
|
||||
|
||||
expect(
|
||||
factory.create(eq(new IPSocket("144.175.1.1", 22)),
|
||||
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client1);
|
||||
factory.create(eq(new IPSocket("144.175.1.1", 22)), eq(new Credentials("root", keyPair
|
||||
.get("private"))))).andReturn(client1);
|
||||
expect(
|
||||
factory.create(eq(new IPSocket("144.175.1.2", 22)),
|
||||
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client2);
|
||||
factory.create(eq(new IPSocket("144.175.1.2", 22)), eq(new Credentials("root", keyPair
|
||||
.get("private"))))).andReturn(client2);
|
||||
expect(
|
||||
factory.create(eq(new IPSocket("144.175.1.3", 22)),
|
||||
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client3);
|
||||
factory.create(eq(new IPSocket("144.175.1.3", 22)), eq(new Credentials("root", keyPair
|
||||
.get("private"))))).andReturn(client3);
|
||||
expect(
|
||||
factory.create(eq(new IPSocket("144.175.1.4", 22)),
|
||||
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client4);
|
||||
factory.create(eq(new IPSocket("144.175.1.4", 22)), eq(new Credentials("root", keyPair
|
||||
.get("private"))))).andReturn(client4);
|
||||
expect(
|
||||
factory.create(eq(new IPSocket("144.175.1.5", 22)),
|
||||
eq(new Credentials("root", keyPair.get("private"))))).andReturn(client5);
|
||||
factory.create(eq(new IPSocket("144.175.1.5", 22)), eq(new Credentials("root", keyPair
|
||||
.get("private"))))).andReturn(client5);
|
||||
|
||||
helloAndJava(client2);
|
||||
helloAndJava(client3);
|
||||
|
@ -184,7 +184,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
|
|||
|
||||
try {
|
||||
runScript(client, "jboss", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
|
||||
.getResourceAsStream("/initscript_with_jboss.sh")), nodeId);
|
||||
.getResourceAsStream("/initscript_with_jboss.sh")), nodeId);
|
||||
} catch (IOException e) {
|
||||
Throwables.propagate(e);
|
||||
}
|
||||
|
@ -198,7 +198,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
|
|||
|
||||
try {
|
||||
runScript(client, scriptName, Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
|
||||
.getResourceAsStream("/initscript_with_java.sh")), nodeId);
|
||||
.getResourceAsStream("/initscript_with_java.sh")), nodeId);
|
||||
} catch (IOException e) {
|
||||
Throwables.propagate(e);
|
||||
}
|
||||
|
@ -251,7 +251,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
|
|||
public void testAssignability() throws Exception {
|
||||
@SuppressWarnings("unused")
|
||||
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 {
|
||||
|
@ -298,7 +298,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
|
|||
return false;
|
||||
PayloadEquals other = (PayloadEquals) o;
|
||||
return this.expected == null && other.expected == null || this.expected != null
|
||||
&& this.expected.equals(other.expected);
|
||||
&& this.expected.equals(other.expected);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -361,11 +361,31 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
|
|||
super.testReboot();
|
||||
}
|
||||
|
||||
@Test(enabled = true, dependsOnMethods = "testReboot")
|
||||
public void testSuspendResume() throws Exception {
|
||||
super.testSuspendResume();
|
||||
}
|
||||
|
||||
@Test(enabled = true, dependsOnMethods = { "testImagesCache" })
|
||||
public void testTemplateMatch() throws Exception {
|
||||
super.testTemplateMatch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testGetNodesWithDetails() throws Exception {
|
||||
super.testGetNodesWithDetails();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testListNodes() throws Exception {
|
||||
super.testListNodes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testDestroyNodes() {
|
||||
super.testDestroyNodes();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException {
|
||||
super.cleanup();
|
||||
|
|
|
@ -39,6 +39,7 @@ import org.jclouds.compute.domain.TemplateBuilder;
|
|||
import org.jclouds.compute.options.TemplateOptions;
|
||||
import org.jclouds.compute.predicates.ImagePredicates;
|
||||
import org.jclouds.domain.Location;
|
||||
import org.jclouds.domain.LocationScope;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import com.google.common.base.Supplier;
|
||||
|
@ -54,7 +55,7 @@ public class TemplateBuilderImplTest {
|
|||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void tesResolveImages() {
|
||||
public void testResolveImages() {
|
||||
Location defaultLocation = createMock(Location.class);
|
||||
Image image = createMock(Image.class);
|
||||
OperatingSystem os = createMock(OperatingSystem.class);
|
||||
|
@ -202,6 +203,8 @@ public class TemplateBuilderImplTest {
|
|||
expect(os.getArch()).andReturn(null).atLeastOnce();
|
||||
expect(os.is64Bit()).andReturn(false).atLeastOnce();
|
||||
|
||||
expect(defaultLocation.getScope()).andReturn(LocationScope.PROVIDER).atLeastOnce();
|
||||
|
||||
replay(image);
|
||||
replay(os);
|
||||
replay(defaultTemplate);
|
||||
|
@ -257,6 +260,8 @@ public class TemplateBuilderImplTest {
|
|||
expect(os.getArch()).andReturn(null).atLeastOnce();
|
||||
expect(os.is64Bit()).andReturn(false).atLeastOnce();
|
||||
|
||||
expect(defaultLocation.getScope()).andReturn(LocationScope.PROVIDER).atLeastOnce();
|
||||
|
||||
replay(image);
|
||||
replay(os);
|
||||
replay(defaultTemplate);
|
||||
|
@ -359,6 +364,70 @@ public class TemplateBuilderImplTest {
|
|||
return template;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testSuppliedImageLocationWiderThanDefault() {
|
||||
TemplateOptions from = provideTemplateOptions();
|
||||
|
||||
Location defaultLocation = createMock(Location.class);
|
||||
Image image = createMock(Image.class);
|
||||
|
||||
Hardware hardware = new HardwareBuilder().id("hardwareId").supportsImage(ImagePredicates.idEquals("foo")).build();
|
||||
|
||||
Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
|
||||
.<Location> of(defaultLocation));
|
||||
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
|
||||
.<Image> of(image));
|
||||
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
|
||||
.<Hardware> of(hardware));
|
||||
Location imageLocation = createMock(Location.class);
|
||||
OperatingSystem os = createMock(OperatingSystem.class);
|
||||
|
||||
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
|
||||
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
|
||||
TemplateOptions defaultOptions = createMock(TemplateOptions.class);
|
||||
expect(optionsProvider.get()).andReturn(from).atLeastOnce();
|
||||
|
||||
expect(defaultLocation.getId()).andReturn("location").atLeastOnce();
|
||||
|
||||
expect(image.getId()).andReturn("foo").atLeastOnce();
|
||||
expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce();
|
||||
expect(image.getOperatingSystem()).andReturn(os).atLeastOnce();
|
||||
expect(image.getName()).andReturn(null).atLeastOnce();
|
||||
expect(image.getDescription()).andReturn(null).atLeastOnce();
|
||||
expect(image.getVersion()).andReturn(null).atLeastOnce();
|
||||
|
||||
expect(os.getName()).andReturn(null).atLeastOnce();
|
||||
expect(os.getVersion()).andReturn(null).atLeastOnce();
|
||||
expect(os.getFamily()).andReturn(null).atLeastOnce();
|
||||
expect(os.getDescription()).andReturn(null).atLeastOnce();
|
||||
expect(os.getArch()).andReturn(null).atLeastOnce();
|
||||
expect(os.is64Bit()).andReturn(false).atLeastOnce();
|
||||
|
||||
expect(defaultLocation.getScope()).andReturn(LocationScope.HOST).atLeastOnce();
|
||||
|
||||
replay(defaultOptions);
|
||||
replay(imageLocation);
|
||||
replay(image);
|
||||
replay(os);
|
||||
replay(defaultLocation);
|
||||
replay(optionsProvider);
|
||||
replay(templateBuilderProvider);
|
||||
|
||||
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
|
||||
optionsProvider, templateBuilderProvider);
|
||||
|
||||
assertEquals(template.imageId("foo").locationId("location").build().getLocation(), defaultLocation);
|
||||
|
||||
verify(defaultOptions);
|
||||
verify(imageLocation);
|
||||
verify(image);
|
||||
verify(os);
|
||||
verify(defaultLocation);
|
||||
verify(optionsProvider);
|
||||
verify(templateBuilderProvider);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testSuppliedLocationWithNoOptions() {
|
||||
|
|
|
@ -76,18 +76,17 @@ END_OF_SCRIPT
|
|||
# add desired commands from the user
|
||||
cat >> $INSTANCE_HOME/bootstrap.sh <<'END_OF_SCRIPT'
|
||||
cd $INSTANCE_HOME
|
||||
echo nameserver 208.67.222.222 >> /etc/resolv.conf
|
||||
cp /etc/apt/sources.list /etc/apt/sources.list.old
|
||||
sed 's~us.archive.ubuntu.com~mirror.anl.gov/pub~g' /etc/apt/sources.list.old >/etc/apt/sources.list
|
||||
which curl || apt-get update -y -qq && apt-get install -f -y -qq --force-yes curl
|
||||
(which java && java -fullversion 2>&1|egrep -q 1.6 ) || apt-get install -f -y -qq --force-yes openjdk-6-jre
|
||||
rm -rf /var/cache/apt /usr/lib/vmware-tools
|
||||
|
||||
mkdir -p ~/.ssh
|
||||
cat >> ~/.ssh/authorized_keys <<'END_OF_FILE'
|
||||
ssh-rsa
|
||||
END_OF_FILE
|
||||
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
|
||||
rm ~/.ssh/id_rsa
|
||||
cat >> ~/.ssh/id_rsa <<'END_OF_FILE'
|
||||
|
|
|
@ -63,14 +63,15 @@ init)
|
|||
ssh-rsa
|
||||
END_OF_FILE
|
||||
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
|
||||
cp /etc/apt/sources.list /etc/apt/sources.list.old
|
||||
sed 's~us.archive.ubuntu.com~mirror.anl.gov/pub~g' /etc/apt/sources.list.old >/etc/apt/sources.list
|
||||
which curl || apt-get update -y -qq && apt-get install -f -y -qq --force-yes curl
|
||||
(which java && java -fullversion 2>&1|egrep -q 1.6 ) || apt-get install -f -y -qq --force-yes openjdk-6-jre
|
||||
rm -rf /var/cache/apt /usr/lib/vmware-tools
|
||||
|
||||
rm -rf /var/cache/apt /usr/lib/vmware-tools
|
||||
echo "export PATH=\"\$JAVA_HOME/bin/:\$PATH\"" >> /root/.bashrc
|
||||
iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT
|
||||
iptables -I RH-Firewall-1-INPUT 1 -p tcp --dport 8080 -j ACCEPT
|
||||
iptables-save
|
||||
curl -X GET -s --retry 20 http://commondatastorage.googleapis.com/jclouds-repo/jboss-as-distribution-6.0.0.20100911-M5.tar.gz |(mkdir -p /usr/local &&cd /usr/local &&tar -xpzf -)
|
||||
mkdir -p /usr/local/jboss
|
||||
mv /usr/local/jboss-*/* /usr/local/jboss
|
||||
|
|
|
@ -76,12 +76,12 @@ END_OF_SCRIPT
|
|||
# add desired commands from the user
|
||||
cat >> $INSTANCE_HOME/runScriptWithCreds.sh <<'END_OF_SCRIPT'
|
||||
cd $INSTANCE_HOME
|
||||
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
|
||||
cp /etc/apt/sources.list /etc/apt/sources.list.old
|
||||
sed 's~us.archive.ubuntu.com~mirror.anl.gov/pub~g' /etc/apt/sources.list.old >/etc/apt/sources.list
|
||||
which curl || apt-get update -y -qq && apt-get install -f -y -qq --force-yes curl
|
||||
(which java && java -fullversion 2>&1|egrep -q 1.6 ) || apt-get install -f -y -qq --force-yes openjdk-6-jre
|
||||
rm -rf /var/cache/apt /usr/lib/vmware-tools
|
||||
echo "export PATH=\"\$JAVA_HOME/bin/:\$PATH\"" >> /root/.bashrc
|
||||
|
||||
|
||||
END_OF_SCRIPT
|
||||
|
|
|
@ -17,6 +17,22 @@
|
|||
* ====================================================================
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright (C) 2010 Google Inc.
|
||||
*
|
||||
* 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 com.google.gson;
|
||||
|
||||
import java.io.IOException;
|
||||
|
|
|
@ -17,6 +17,22 @@
|
|||
* ====================================================================
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright (C) 2010 Google Inc.
|
||||
*
|
||||
* 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 com.google.gson;
|
||||
|
||||
import java.io.IOException;
|
||||
|
|
|
@ -17,6 +17,31 @@
|
|||
* ====================================================================
|
||||
*/
|
||||
|
||||
/****************************************************************************
|
||||
* Copyright (c) 1998-2009 AOL LLC.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
****************************************************************************
|
||||
*
|
||||
* @author: zhang
|
||||
* @version: $Revision$
|
||||
* @created: Apr 24, 2009
|
||||
*
|
||||
* Description: A KeySpec for PKCS#1 encoded RSA private key
|
||||
*
|
||||
****************************************************************************/
|
||||
|
||||
package net.oauth.signature.pem;
|
||||
|
||||
import java.io.IOException;
|
||||
|
|
|
@ -17,6 +17,22 @@
|
|||
* ====================================================================
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright (C) 2007 Google Inc.
|
||||
*
|
||||
* 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.concurrent;
|
||||
|
||||
import java.util.Collections;
|
||||
|
|
|
@ -21,7 +21,6 @@ package org.jclouds.http.functions;
|
|||
|
||||
import static com.google.common.base.Preconditions.checkArgument;
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
import static com.google.common.base.Throwables.propagate;
|
||||
import static com.google.common.io.Closeables.closeQuietly;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
@ -30,7 +29,6 @@ import java.io.StringReader;
|
|||
import javax.annotation.Resource;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import org.jclouds.http.HttpException;
|
||||
import org.jclouds.http.HttpRequest;
|
||||
import org.jclouds.http.HttpResponse;
|
||||
import org.jclouds.logging.Logger;
|
||||
|
@ -38,14 +36,15 @@ import org.jclouds.rest.InvocationContext;
|
|||
import org.jclouds.rest.internal.GeneratedHttpRequest;
|
||||
import org.jclouds.util.Utils;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXParseException;
|
||||
import org.xml.sax.XMLReader;
|
||||
import org.xml.sax.helpers.DefaultHandler;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
|
||||
/**
|
||||
* This object will parse the body of an HttpResponse and return the result of
|
||||
* type <T> back to the caller.
|
||||
* This object will parse the body of an HttpResponse and return the result of type <T> back to the
|
||||
* caller.
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
|
@ -108,6 +107,7 @@ public class ParseSax<T> implements Function<HttpResponse, T>, InvocationContext
|
|||
public T parse(InputSource from) {
|
||||
try {
|
||||
checkNotNull(from, "xml inputsource");
|
||||
from.setEncoding("UTF-8");
|
||||
parser.setContentHandler(getHandler());
|
||||
// This method should accept documents with a BOM (Byte-order mark)
|
||||
parser.parse(from);
|
||||
|
@ -118,16 +118,25 @@ public class ParseSax<T> implements Function<HttpResponse, T>, InvocationContext
|
|||
}
|
||||
|
||||
private T addRequestDetailsToException(Exception e) {
|
||||
String exceptionMessage = e.getMessage();
|
||||
if (e instanceof SAXParseException) {
|
||||
SAXParseException parseException = (SAXParseException) e;
|
||||
String systemId = parseException.getSystemId();
|
||||
if (systemId == null) {
|
||||
systemId = "";
|
||||
}
|
||||
exceptionMessage = String.format("Error on line %d of document %s: %s", systemId, parseException
|
||||
.getLineNumber(), parseException.getMessage());
|
||||
}
|
||||
if (request != null) {
|
||||
StringBuilder message = new StringBuilder();
|
||||
message.append("Error parsing input for ").append(request.getRequestLine()).append(": ");
|
||||
message.append(e.getMessage());
|
||||
message.append(exceptionMessage);
|
||||
logger.error(e, message.toString());
|
||||
throw new HttpException(message.toString(), e);
|
||||
throw new RuntimeException(message.toString(), e);
|
||||
} else {
|
||||
propagate(e);
|
||||
assert false : "should have propagated: " + e;
|
||||
return null;
|
||||
logger.error(e, exceptionMessage.toString());
|
||||
throw new RuntimeException(exceptionMessage.toString(), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -136,8 +145,7 @@ public class ParseSax<T> implements Function<HttpResponse, T>, InvocationContext
|
|||
}
|
||||
|
||||
/**
|
||||
* Handler that produces a useable domain object accessible after parsing
|
||||
* completes.
|
||||
* Handler that produces a useable domain object accessible after parsing completes.
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
|
|
|
@ -225,8 +225,8 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe
|
|||
}
|
||||
} else {
|
||||
connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, "0");
|
||||
// for some reason POST undoes the content length header above.
|
||||
if (connection.getRequestMethod().equals("POST"))
|
||||
// for some reason POST/PUT undoes the content length header above.
|
||||
if (connection.getRequestMethod().equals("POST") || connection.getRequestMethod().equals("PUT"))
|
||||
connection.setChunkedStreamingMode(0);
|
||||
}
|
||||
return connection;
|
||||
|
|
|
@ -47,10 +47,10 @@ import java.util.Comparator;
|
|||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
|
|
@ -68,7 +68,7 @@ public abstract class BaseHttpErrorHandlerTest {
|
|||
|
||||
HttpCommand command = createMock(HttpCommand.class);
|
||||
HttpRequest request = new HttpRequest(method, uri);
|
||||
HttpResponse response = new HttpResponse(statusCode, null, Payloads.newStringPayload(content));
|
||||
HttpResponse response = new HttpResponse(statusCode, message, Payloads.newStringPayload(content));
|
||||
|
||||
expect(command.getRequest()).andReturn(request).atLeastOnce();
|
||||
command.setException(classEq(expected));
|
||||
|
|
|
@ -34,6 +34,7 @@ import static org.jclouds.util.Utils.toStringAndClose;
|
|||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
@ -64,6 +65,8 @@ import org.testng.annotations.Optional;
|
|||
import org.testng.annotations.Parameters;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.LinkedHashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.io.InputSupplier;
|
||||
import com.google.inject.Injector;
|
||||
import com.google.inject.Module;
|
||||
|
@ -94,7 +97,7 @@ public abstract class BaseJettyTest {
|
|||
|
||||
Handler server1Handler = new AbstractHandler() {
|
||||
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
|
||||
throws IOException, ServletException {
|
||||
throws IOException, ServletException {
|
||||
if (failIfNoContentLength(request, response)) {
|
||||
return;
|
||||
} else if (target.indexOf("sleep") > 0) {
|
||||
|
@ -138,8 +141,7 @@ public abstract class BaseJettyTest {
|
|||
response.getWriter().println("test");
|
||||
} else if (request.getMethod().equals("HEAD")) {
|
||||
/*
|
||||
* NOTE: by HTML specification, HEAD response MUST NOT include a
|
||||
* body
|
||||
* NOTE: by HTML specification, HEAD response MUST NOT include a body
|
||||
*/
|
||||
response.setContentType("text/xml");
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
|
@ -185,7 +187,7 @@ public abstract class BaseJettyTest {
|
|||
}
|
||||
} else {
|
||||
for (String header : new String[] { "Content-Disposition", HttpHeaders.CONTENT_LANGUAGE,
|
||||
HttpHeaders.CONTENT_ENCODING })
|
||||
HttpHeaders.CONTENT_ENCODING })
|
||||
if (request.getHeader(header) != null) {
|
||||
response.addHeader("x-" + header, request.getHeader(header));
|
||||
}
|
||||
|
@ -206,7 +208,7 @@ public abstract class BaseJettyTest {
|
|||
protected void setupAndStartSSLServer(final int testPort) throws Exception {
|
||||
Handler server2Handler = new AbstractHandler() {
|
||||
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
|
||||
throws IOException, ServletException {
|
||||
throws IOException, ServletException {
|
||||
if (request.getMethod().equals("PUT")) {
|
||||
if (request.getContentLength() > 0) {
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
|
@ -220,8 +222,7 @@ public abstract class BaseJettyTest {
|
|||
}
|
||||
} else if (request.getMethod().equals("HEAD")) {
|
||||
/*
|
||||
* NOTE: by HTML specification, HEAD response MUST NOT include a
|
||||
* body
|
||||
* NOTE: by HTML specification, HEAD response MUST NOT include a body
|
||||
*/
|
||||
response.setContentType("text/xml");
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
|
@ -261,12 +262,12 @@ public abstract class BaseJettyTest {
|
|||
}
|
||||
|
||||
public static RestContextBuilder<IntegrationTestClient, IntegrationTestAsyncClient> newBuilder(int testPort,
|
||||
Properties properties, Module... connectionModules) {
|
||||
Properties properties, Module... connectionModules) {
|
||||
properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
|
||||
properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
|
||||
RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec("test",
|
||||
"http://localhost:" + testPort, "1", "identity", null, IntegrationTestClient.class,
|
||||
IntegrationTestAsyncClient.class, ImmutableSet.<Module> copyOf(connectionModules));
|
||||
"http://localhost:" + testPort, "1", "identity", null, IntegrationTestClient.class,
|
||||
IntegrationTestAsyncClient.class, ImmutableSet.<Module> copyOf(connectionModules));
|
||||
return createContextBuilder(contextSpec, properties);
|
||||
}
|
||||
|
||||
|
@ -300,7 +301,7 @@ public abstract class BaseJettyTest {
|
|||
}
|
||||
|
||||
protected boolean redirectEveryTwentyRequests(HttpServletRequest request, HttpServletResponse response)
|
||||
throws IOException {
|
||||
throws IOException {
|
||||
if (cycle.incrementAndGet() % 20 == 0) {
|
||||
response.sendRedirect("http://localhost:" + (testPort + 1) + "/");
|
||||
((Request) request).setHandled(true);
|
||||
|
@ -309,8 +310,20 @@ public abstract class BaseJettyTest {
|
|||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected boolean failIfNoContentLength(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
if (request.getHeader(CONTENT_LENGTH) == null) {
|
||||
Multimap<String, String> realHeaders = LinkedHashMultimap.create();
|
||||
Enumeration headers = request.getHeaderNames();
|
||||
while (headers.hasMoreElements()) {
|
||||
String header = headers.nextElement().toString();
|
||||
Enumeration values = request.getHeaders(header);
|
||||
while (values.hasMoreElements()) {
|
||||
realHeaders.put(header, values.nextElement().toString());
|
||||
}
|
||||
}
|
||||
if (realHeaders.get(CONTENT_LENGTH) == null) {
|
||||
response.getWriter().println("no content length!");
|
||||
response.getWriter().println(realHeaders.toString());
|
||||
response.sendError(500);
|
||||
((Request) request).setHandled(true);
|
||||
return true;
|
||||
|
|
|
@ -25,11 +25,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
|
|||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
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.GoGridDestroyNodeStrategy;
|
||||
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.GoGridRebootNodeStrategy;
|
||||
|
||||
/**
|
||||
*
|
||||
|
@ -59,6 +61,16 @@ public class GoGridBindComputeStrategiesByClass extends BindComputeStrategiesByC
|
|||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -26,6 +26,8 @@ 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.compute.strategy.ResumeNodeStrategy;
|
||||
import org.jclouds.compute.strategy.SuspendNodeStrategy;
|
||||
import org.jclouds.gogrid.GoGridClient;
|
||||
import org.jclouds.gogrid.domain.PowerCommand;
|
||||
import org.jclouds.gogrid.domain.Server;
|
||||
|
@ -39,14 +41,14 @@ import com.google.common.collect.Iterables;
|
|||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class GoGridRebootNodeStrategy implements RebootNodeStrategy {
|
||||
public class GoGridLifeCycleStrategy implements RebootNodeStrategy, ResumeNodeStrategy, SuspendNodeStrategy {
|
||||
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) {
|
||||
protected GoGridLifeCycleStrategy(GoGridClient client, GetNodeMetadataStrategy getNode, Timeouts timeouts) {
|
||||
this.client = client;
|
||||
this.serverLatestJobCompleted = new RetryablePredicate<Server>(new ServerLatestJobCompleted(client
|
||||
.getJobServices()), timeouts.nodeRunning * 9l / 10l);
|
||||
|
@ -57,11 +59,30 @@ public class GoGridRebootNodeStrategy implements RebootNodeStrategy {
|
|||
|
||||
@Override
|
||||
public NodeMetadata rebootNode(String id) {
|
||||
executeCommandOnServer(PowerCommand.RESTART, 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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata resumeNode(String id) {
|
||||
executeCommandOnServer(PowerCommand.START, id);
|
||||
return getNode.getNode(id);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata suspendNode(String id) {
|
||||
executeCommandOnServer(PowerCommand.STOP, id);
|
||||
return getNode.getNode(id);
|
||||
|
||||
}
|
||||
|
||||
private boolean executeCommandOnServer(PowerCommand command, String id) {
|
||||
Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(new Long(id)));
|
||||
client.getServerServices().power(server.getName(), command);
|
||||
return serverLatestJobCompleted.apply(server);
|
||||
}
|
||||
}
|
|
@ -20,6 +20,7 @@
|
|||
package org.jclouds.gogrid.compute.suppliers;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
@ -35,7 +36,6 @@ import org.jclouds.compute.reference.ComputeServiceConstants;
|
|||
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
|
||||
import org.jclouds.gogrid.GoGridClient;
|
||||
import org.jclouds.gogrid.domain.ServerImage;
|
||||
import org.jclouds.gogrid.util.GoGridUtils;
|
||||
import org.jclouds.logging.Logger;
|
||||
|
||||
import com.google.common.base.Supplier;
|
||||
|
@ -47,7 +47,8 @@ import com.google.common.collect.Sets;
|
|||
*/
|
||||
@Singleton
|
||||
public class GoGridImageSupplier implements Supplier<Set<? extends Image>> {
|
||||
public static final Pattern GOGRID_OS_NAME_PATTERN = Pattern.compile("([a-zA-Z]*)(.*)");
|
||||
public static final Pattern GOGRID_OS_PATTERN = Pattern.compile("([a-zA-Z]*).*");
|
||||
public static final Pattern GOGRID_VERSION_PATTERN = Pattern.compile(".* ([0-9.]+) .*");
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
|
@ -84,18 +85,29 @@ public class GoGridImageSupplier implements Supplier<Set<? extends Image>> {
|
|||
OsFamily osFamily = null;
|
||||
String osName = from.getOs().getName();
|
||||
String osArch = from.getArchitecture().getDescription();
|
||||
String osVersion = null;// TODO
|
||||
String osVersion = parseVersion(osName);
|
||||
String osDescription = from.getOs().getDescription();
|
||||
boolean is64Bit = (from.getOs().getName().indexOf("64") != -1 || from.getDescription().indexOf("64") != -1);
|
||||
|
||||
String matchedOs = GoGridUtils.parseStringByPatternAndGetNthMatchGroup(osName, GOGRID_OS_NAME_PATTERN, 1);
|
||||
try {
|
||||
osFamily = OsFamily.fromValue(matchedOs.toLowerCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("<< didn't match os(%s)", matchedOs);
|
||||
Matcher matcher = GOGRID_OS_PATTERN.matcher(from.getName());
|
||||
if (matcher.find()) {
|
||||
try {
|
||||
osFamily = OsFamily.fromValue(matcher.group(1).toLowerCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("<< didn't match os(%s)", from.getName());
|
||||
}
|
||||
}
|
||||
|
||||
// TODO determine DC images are in
|
||||
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
|
||||
return os;
|
||||
}
|
||||
|
||||
static String parseVersion(String name) {
|
||||
Matcher matcher = GOGRID_VERSION_PATTERN.matcher(name);
|
||||
if (matcher.find()) {
|
||||
return matcher.group(1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -82,7 +82,7 @@ import com.google.inject.Module;
|
|||
*
|
||||
* @author Oleksiy Yarmula
|
||||
*/
|
||||
@Test(enabled = false, groups = "live", testName = "gogrid.GoGridLiveTest")
|
||||
@Test(enabled = true, groups = "live", testName = "gogrid.GoGridLiveTest")
|
||||
public class GoGridLiveTestDisabled {
|
||||
|
||||
private GoGridClient client;
|
||||
|
|
|
@ -45,6 +45,7 @@ public class GoGridComputeServiceLiveTest extends BaseComputeServiceLiveTest {
|
|||
public void testTemplateBuilder() {
|
||||
Template defaultTemplate = client.templateBuilder().build();
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "5.3");
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS);
|
||||
assertEquals(defaultTemplate.getLocation().getId(), "1");
|
||||
assertEquals(getCores(defaultTemplate.getHardware()), 0.5d);
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
/**
|
||||
*
|
||||
* 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.suppliers;
|
||||
|
||||
import static org.testng.Assert.assertEquals;
|
||||
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
public class GoGridImageSupplierTest {
|
||||
|
||||
@Test
|
||||
public void testParseVersion() {
|
||||
assertEquals(GoGridImageSupplier.parseVersion("CentOS 5.3 (64-bit)"), "5.3");
|
||||
}
|
||||
|
||||
}
|
|
@ -25,11 +25,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
|
|||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
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.CloudServersDestroyNodeStrategy;
|
||||
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersGetNodeMetadataStrategy;
|
||||
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
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -40,7 +40,7 @@ import com.google.common.base.Function;
|
|||
@Singleton
|
||||
public class CloudServersImageToOperatingSystem implements
|
||||
Function<org.jclouds.rackspace.cloudservers.domain.Image, OperatingSystem> {
|
||||
public static final Pattern RACKSPACE_PATTERN = Pattern.compile("(([^ ]*) .*)");
|
||||
public static final Pattern RACKSPACE_PATTERN = Pattern.compile("(([^ ]*) ([0-9.]+) ?.*)");
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
|
@ -58,12 +58,14 @@ public class CloudServersImageToOperatingSystem implements
|
|||
osFamily = OsFamily.RHEL;
|
||||
} else if (from.getName().indexOf("Oracle EL") != -1) {
|
||||
osFamily = OsFamily.OEL;
|
||||
} else if (matcher.find()) {
|
||||
}
|
||||
if (matcher.find()) {
|
||||
try {
|
||||
osFamily = OsFamily.fromValue(matcher.group(2).toLowerCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("<< didn't match os(%s)", matcher.group(2));
|
||||
}
|
||||
osVersion = matcher.group(3);
|
||||
}
|
||||
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
|
||||
return os;
|
||||
|
|
|
@ -115,7 +115,7 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
|
|||
builder.state(serverToNodeState.get(from.getStatus()));
|
||||
builder.publicAddresses(from.getAddresses().getPublicAddresses());
|
||||
builder.privateAddresses(from.getAddresses().getPrivateAddresses());
|
||||
builder.credentials(credentialStore.get(from.getId() + ""));
|
||||
builder.credentials(credentialStore.get("node#" + from.getId()));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
|
|
|
@ -46,7 +46,7 @@ public class CloudServersAddNodeWithTagStrategy implements AddNodeWithTagStrateg
|
|||
|
||||
@Inject
|
||||
protected CloudServersAddNodeWithTagStrategy(CloudServersClient client, Map<String, Credentials> credentialStore,
|
||||
Function<Server, NodeMetadata> serverToNodeMetadata) {
|
||||
Function<Server, NodeMetadata> serverToNodeMetadata) {
|
||||
this.client = checkNotNull(client, "client");
|
||||
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
|
||||
this.serverToNodeMetadata = checkNotNull(serverToNodeMetadata, "serverToNodeMetadata");
|
||||
|
@ -54,9 +54,9 @@ public class CloudServersAddNodeWithTagStrategy implements AddNodeWithTagStrateg
|
|||
|
||||
@Override
|
||||
public NodeMetadata addNodeWithTag(String tag, String name, Template template) {
|
||||
Server from = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()),
|
||||
Integer.parseInt(template.getHardware().getProviderId()));
|
||||
credentialStore.put(from.getId() + "", new Credentials("root", from.getAdminPass()));
|
||||
Server from = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()), Integer
|
||||
.parseInt(template.getHardware().getProviderId()));
|
||||
credentialStore.put("node#" + from.getId(), new Credentials("root", from.getAdminPass()));
|
||||
return serverToNodeMetadata.apply(from);
|
||||
}
|
||||
|
||||
|
|
|
@ -25,6 +25,8 @@ 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.compute.strategy.ResumeNodeStrategy;
|
||||
import org.jclouds.compute.strategy.SuspendNodeStrategy;
|
||||
import org.jclouds.rackspace.cloudservers.CloudServersClient;
|
||||
import org.jclouds.rackspace.cloudservers.domain.RebootType;
|
||||
|
||||
|
@ -32,12 +34,12 @@ import org.jclouds.rackspace.cloudservers.domain.RebootType;
|
|||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class CloudServersRebootNodeStrategy implements RebootNodeStrategy {
|
||||
public class CloudServersLifeCycleStrategy implements RebootNodeStrategy, SuspendNodeStrategy, ResumeNodeStrategy {
|
||||
private final CloudServersClient client;
|
||||
private final GetNodeMetadataStrategy getNode;
|
||||
|
||||
@Inject
|
||||
protected CloudServersRebootNodeStrategy(CloudServersClient client, GetNodeMetadataStrategy getNode) {
|
||||
protected CloudServersLifeCycleStrategy(CloudServersClient client, GetNodeMetadataStrategy getNode) {
|
||||
this.client = client;
|
||||
this.getNode = getNode;
|
||||
}
|
||||
|
@ -50,4 +52,14 @@ public class CloudServersRebootNodeStrategy implements RebootNodeStrategy {
|
|||
return getNode.getNode(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata suspendNode(String id) {
|
||||
throw new UnsupportedOperationException("suspend not supported");
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata resumeNode(String id) {
|
||||
throw new UnsupportedOperationException("resume not supported");
|
||||
}
|
||||
|
||||
}
|
|
@ -36,6 +36,7 @@ import java.util.Set;
|
|||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.jclouds.Constants;
|
||||
import org.jclouds.domain.Credentials;
|
||||
import org.jclouds.http.HttpResponseException;
|
||||
import org.jclouds.io.Payload;
|
||||
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
|
||||
|
@ -407,7 +408,7 @@ public class CloudServersClientLiveTest {
|
|||
IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0), 22);
|
||||
socketTester.apply(socket);
|
||||
|
||||
SshClient client = sshFactory.create(socket, "root", pass);
|
||||
SshClient client = sshFactory.create(socket, new Credentials("root", pass));
|
||||
try {
|
||||
client.connect();
|
||||
Payload etcPasswd = client.get("/etc/jclouds.txt");
|
||||
|
@ -422,7 +423,7 @@ public class CloudServersClientLiveTest {
|
|||
private ExecResponse exec(Server details, String pass, String command) throws IOException {
|
||||
IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0), 22);
|
||||
socketTester.apply(socket);
|
||||
SshClient client = sshFactory.create(socket, "root", pass);
|
||||
SshClient client = sshFactory.create(socket, new Credentials("root", pass));
|
||||
try {
|
||||
client.connect();
|
||||
return client.exec(command);
|
||||
|
|
|
@ -52,6 +52,7 @@ public class CloudServersComputeServiceLiveTest extends BaseComputeServiceLiveTe
|
|||
public void testTemplateBuilder() {
|
||||
Template defaultTemplate = client.templateBuilder().build();
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "9.10");
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
|
||||
assertEquals(defaultTemplate.getLocation().getId(), "DFW1");
|
||||
assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);
|
||||
|
@ -76,4 +77,9 @@ public class CloudServersComputeServiceLiveTest extends BaseComputeServiceLiveTe
|
|||
}
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = UnsupportedOperationException.class)
|
||||
public void testSuspendResume() throws Exception {
|
||||
super.testSuspendResume();
|
||||
}
|
||||
|
||||
}
|
|
@ -44,7 +44,7 @@ public class CloudServersImageToImageTest {
|
|||
new ImageBuilder()
|
||||
.name("CentOS 5.2")
|
||||
.operatingSystem(
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true)
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true)
|
||||
.build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null))
|
||||
.ids("2").version("1286712000000").build());
|
||||
}
|
||||
|
|
|
@ -68,7 +68,7 @@ public class ServerToNodeMetadataTest {
|
|||
Server server = ParseServerFromJsonResponseTest.parseServer();
|
||||
|
||||
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
|
||||
.<String, Credentials> of("1234", creds), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
|
||||
.<String, Credentials> of("node#1234", creds), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
|
||||
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
|
||||
|
||||
NodeMetadata metadata = parser.apply(server);
|
||||
|
@ -123,12 +123,12 @@ public class ServerToNodeMetadataTest {
|
|||
assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses(
|
||||
ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")).tag(
|
||||
"NOTAG-sample-server").imageId("2").operatingSystem(
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true).build())
|
||||
.id("1234").providerId("1234").name("sample-server").location(
|
||||
new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0",
|
||||
"e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas",
|
||||
"description", null))).userMetadata(
|
||||
ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2").is64Bit(
|
||||
true).build()).id("1234").providerId("1234").name("sample-server").location(
|
||||
new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0",
|
||||
"e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas",
|
||||
"description", null))).userMetadata(
|
||||
ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
|
||||
|
||||
}
|
||||
|
||||
|
@ -152,11 +152,11 @@ public class ServerToNodeMetadataTest {
|
|||
ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes(
|
||||
ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true)
|
||||
.bootDevice(true).build())).build()).operatingSystem(
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true).build())
|
||||
.id("1234").providerId("1234").name("sample-server").location(
|
||||
new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0",
|
||||
"e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas",
|
||||
"description", null))).userMetadata(
|
||||
ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2").is64Bit(
|
||||
true).build()).id("1234").providerId("1234").name("sample-server").location(
|
||||
new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0",
|
||||
"e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas",
|
||||
"description", null))).userMetadata(
|
||||
ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
|
||||
}
|
||||
}
|
|
@ -161,12 +161,12 @@
|
|||
<category name="jclouds.ssh">
|
||||
<priority value="DEBUG" />
|
||||
<appender-ref ref="ASYNCSSH" />
|
||||
</category><!--
|
||||
</category>
|
||||
<category name="jclouds.wire">
|
||||
<priority value="DEBUG" />
|
||||
<appender-ref ref="ASYNCWIRE" />
|
||||
</category>
|
||||
--><category name="jclouds.blobstore">
|
||||
<category name="jclouds.blobstore">
|
||||
<priority value="DEBUG" />
|
||||
<appender-ref ref="ASYNCBLOBSTORE" />
|
||||
</category>
|
||||
|
|
|
@ -6,11 +6,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
|
|||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
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.RimuHostingDestroyNodeStrategy;
|
||||
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.RimuHostingRebootNodeStrategy;
|
||||
|
||||
public class RimuHostingBindComputeStrategiesByClass extends BindComputeStrategiesByClass {
|
||||
@Override
|
||||
|
@ -35,6 +37,16 @@ public class RimuHostingBindComputeStrategiesByClass extends BindComputeStrategi
|
|||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -45,7 +45,7 @@ public class RimuHostingComputeServiceContextModule extends BaseComputeServiceCo
|
|||
|
||||
@Override
|
||||
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
|
||||
return template.hardwareId("MIRO1B").osFamily(UBUNTU).os64Bit(false).imageNameMatches(".*10\\.?04.*");
|
||||
return template.hardwareId("MIRO1B").osFamily(UBUNTU).os64Bit(false).osVersionMatches("9.10");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -105,7 +105,7 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
|
|||
builder.hardware(null);// TODO
|
||||
builder.state(runningStateToNodeState.get(from.getState()));
|
||||
builder.publicAddresses(getPublicAddresses.apply(from));
|
||||
builder.credentials(credentialStore.get(from.getId() + ""));
|
||||
builder.credentials(credentialStore.get("node#" + from.getId()));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
|
|
|
@ -48,7 +48,7 @@ public class RimuHostingAddNodeWithTagStrategy implements AddNodeWithTagStrategy
|
|||
|
||||
@Inject
|
||||
protected RimuHostingAddNodeWithTagStrategy(RimuHostingClient client, Map<String, Credentials> credentialStore,
|
||||
Function<Server, NodeMetadata> serverToNodeMetadata) {
|
||||
Function<Server, NodeMetadata> serverToNodeMetadata) {
|
||||
this.client = client;
|
||||
this.credentialStore = credentialStore;
|
||||
this.serverToNodeMetadata = serverToNodeMetadata;
|
||||
|
@ -56,12 +56,11 @@ public class RimuHostingAddNodeWithTagStrategy implements AddNodeWithTagStrategy
|
|||
|
||||
@Override
|
||||
public NodeMetadata addNodeWithTag(String tag, String name, Template template) {
|
||||
NewServerResponse serverResponse = client.createServer(name,
|
||||
checkNotNull(template.getImage().getProviderId(), "imageId"),
|
||||
checkNotNull(template.getHardware().getProviderId(), "hardwareId"));
|
||||
NewServerResponse serverResponse = client.createServer(name, checkNotNull(template.getImage().getProviderId(),
|
||||
"imageId"), checkNotNull(template.getHardware().getProviderId(), "hardwareId"));
|
||||
Server from = client.getServer(serverResponse.getServer().getId());
|
||||
credentialStore.put(from.getId() + "", new Credentials("root", serverResponse.getNewInstanceRequest()
|
||||
.getCreateOptions().getPassword()));
|
||||
credentialStore.put("node#" + from.getId(), new Credentials("root", serverResponse.getNewInstanceRequest()
|
||||
.getCreateOptions().getPassword()));
|
||||
return serverToNodeMetadata.apply(from);
|
||||
}
|
||||
|
||||
|
|
|
@ -25,6 +25,8 @@ 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.compute.strategy.ResumeNodeStrategy;
|
||||
import org.jclouds.compute.strategy.SuspendNodeStrategy;
|
||||
import org.jclouds.rimuhosting.miro.RimuHostingClient;
|
||||
|
||||
/**
|
||||
|
@ -32,12 +34,12 @@ import org.jclouds.rimuhosting.miro.RimuHostingClient;
|
|||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class RimuHostingRebootNodeStrategy implements RebootNodeStrategy {
|
||||
public class RimuHostingLifeCycleStrategy implements RebootNodeStrategy, SuspendNodeStrategy, ResumeNodeStrategy {
|
||||
private final RimuHostingClient client;
|
||||
private final GetNodeMetadataStrategy getNode;
|
||||
|
||||
@Inject
|
||||
protected RimuHostingRebootNodeStrategy(RimuHostingClient client, GetNodeMetadataStrategy getNode) {
|
||||
protected RimuHostingLifeCycleStrategy(RimuHostingClient client, GetNodeMetadataStrategy getNode) {
|
||||
this.client = client;
|
||||
this.getNode = getNode;
|
||||
}
|
||||
|
@ -50,4 +52,14 @@ public class RimuHostingRebootNodeStrategy implements RebootNodeStrategy {
|
|||
return getNode.getNode(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata suspendNode(String id) {
|
||||
throw new UnsupportedOperationException("suspend not supported");
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata resumeNode(String id) {
|
||||
throw new UnsupportedOperationException("resume not supported");
|
||||
}
|
||||
|
||||
}
|
|
@ -46,7 +46,7 @@ import com.google.common.collect.Sets;
|
|||
*/
|
||||
@Singleton
|
||||
public class RimuHostingImageSupplier implements Supplier<Set<? extends Image>> {
|
||||
public static final Pattern RIMU_PATTERN = Pattern.compile("([^0-9]*)(.*)");
|
||||
public static final Pattern RIMU_PATTERN = Pattern.compile("([a-zA-Z]+) ?([0-9.]+) .*");
|
||||
private final RimuHostingClient sync;
|
||||
|
||||
@Inject
|
||||
|
@ -77,23 +77,21 @@ public class RimuHostingImageSupplier implements Supplier<Set<? extends Image>>
|
|||
|
||||
protected OperatingSystem parseOs(final org.jclouds.rimuhosting.miro.domain.Image from) {
|
||||
OsFamily osFamily = null;
|
||||
String osName = null;
|
||||
String osName = from.getId();
|
||||
String osArch = null;
|
||||
String osVersion = null;
|
||||
String osDescription = from.getId();
|
||||
String osDescription = from.getDescription();
|
||||
boolean is64Bit = from.getId().indexOf("64") != -1;
|
||||
|
||||
osDescription = from.getId();
|
||||
|
||||
Matcher matcher = RIMU_PATTERN.matcher(from.getId());
|
||||
Matcher matcher = RIMU_PATTERN.matcher(osDescription);
|
||||
if (matcher.find()) {
|
||||
try {
|
||||
osFamily = OsFamily.fromValue(matcher.group(1).toLowerCase());
|
||||
osVersion = matcher.group(2).toLowerCase();
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("<< didn't match os(%s)", matcher.group(2));
|
||||
logger.debug("<< didn't match os(%s)", osDescription);
|
||||
}
|
||||
}
|
||||
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
|
||||
return os;
|
||||
return new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
|
||||
}
|
||||
}
|
|
@ -56,15 +56,13 @@ public class RimuHostingClientLiveTest {
|
|||
|
||||
protected String provider = "rimuhosting";
|
||||
protected String identity;
|
||||
protected String credential;
|
||||
protected String endpoint;
|
||||
protected String apiversion;
|
||||
|
||||
protected void setupCredentials() {
|
||||
identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity");
|
||||
endpoint = checkNotNull(System.getProperty("test." + provider + ".endpoint"), "test." + provider + ".endpoint");
|
||||
apiversion = checkNotNull(System.getProperty("test." + provider + ".apiversion"), "test." + provider
|
||||
+ ".apiversion");
|
||||
endpoint = System.getProperty("test." + provider + ".endpoint");
|
||||
apiversion = System.getProperty("test." + provider + ".apiversion");
|
||||
}
|
||||
|
||||
protected Properties setupProperties() {
|
||||
|
@ -72,8 +70,10 @@ public class RimuHostingClientLiveTest {
|
|||
overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
|
||||
overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
|
||||
overrides.setProperty(provider + ".identity", identity);
|
||||
overrides.setProperty(provider + ".endpoint", endpoint);
|
||||
overrides.setProperty(provider + ".apiversion", apiversion);
|
||||
if (endpoint != null)
|
||||
overrides.setProperty(provider + ".endpoint", endpoint);
|
||||
if (apiversion != null)
|
||||
overrides.setProperty(provider + ".apiversion", apiversion);
|
||||
return overrides;
|
||||
}
|
||||
|
||||
|
|
|
@ -48,6 +48,7 @@ public class RimuHostingComputeServiceLiveTest extends BaseComputeServiceLiveTes
|
|||
public void testTemplateBuilder() {
|
||||
Template defaultTemplate = client.templateBuilder().build();
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), false);
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "9.10");
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
|
||||
assertEquals(defaultTemplate.getLocation().getId(), "DCDALLAS");
|
||||
assertEquals(defaultTemplate.getHardware().getProviderId(), "MIRO1B");
|
||||
|
|
|
@ -44,12 +44,17 @@
|
|||
<artifactId>libvirt</artifactId>
|
||||
<version>0.4.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.jna</groupId>
|
||||
<artifactId>jna</artifactId>
|
||||
<version>3.0.9</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.jna</groupId>
|
||||
<artifactId>jna</artifactId>
|
||||
<version>3.0.9</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jamesmurty.utils</groupId>
|
||||
<artifactId>java-xmlbuilder</artifactId>
|
||||
<version>0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>jclouds-core</artifactId>
|
||||
|
|
|
@ -19,46 +19,87 @@
|
|||
|
||||
package org.jclouds.libvirt.compute.functions;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.util.List;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.xpath.XPathConstants;
|
||||
import javax.xml.xpath.XPathExpression;
|
||||
import javax.xml.xpath.XPathExpressionException;
|
||||
import javax.xml.xpath.XPathFactory;
|
||||
|
||||
import org.jclouds.compute.domain.Hardware;
|
||||
import org.jclouds.compute.domain.HardwareBuilder;
|
||||
import org.jclouds.compute.domain.Processor;
|
||||
import org.jclouds.compute.domain.Volume;
|
||||
import org.jclouds.compute.domain.internal.VolumeImpl;
|
||||
import org.libvirt.Domain;
|
||||
import org.libvirt.LibvirtException;
|
||||
import org.libvirt.StorageVol;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import com.jamesmurty.utils.XMLBuilder;
|
||||
|
||||
/**
|
||||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class DomainToHardware implements Function<Domain, Hardware> {
|
||||
|
||||
@Override
|
||||
public Hardware apply(Domain from) {
|
||||
HardwareBuilder builder = new HardwareBuilder();
|
||||
try {
|
||||
builder.id(from.getUUIDString());
|
||||
@Override
|
||||
public Hardware apply(Domain from) {
|
||||
HardwareBuilder builder = new HardwareBuilder();
|
||||
|
||||
builder.providerId(from.getID() + "");
|
||||
builder.name(from.getName());
|
||||
List<Processor> processors = Lists.newArrayList();
|
||||
for (int i = 0; i < from.getInfo().nrVirtCpu; i++) {
|
||||
processors.add(new Processor(i + 1, 1));
|
||||
}
|
||||
builder.processors(processors);
|
||||
try {
|
||||
builder.id(from.getUUIDString());
|
||||
builder.providerId(from.getID() + "");
|
||||
builder.name(from.getName());
|
||||
List<Processor> processors = Lists.newArrayList();
|
||||
for (int i = 0; i < from.getInfo().nrVirtCpu; i++) {
|
||||
processors.add(new Processor(i + 1, 1));
|
||||
}
|
||||
builder.processors(processors);
|
||||
|
||||
builder.ram((int) from.getInfo().maxMem);
|
||||
// TODO volumes
|
||||
} catch (LibvirtException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
builder.ram((int) from.getInfo().maxMem);
|
||||
// TODO volumes
|
||||
List<Volume> volumes = Lists.newArrayList();
|
||||
XMLBuilder xmlBuilder = XMLBuilder.parse(new InputSource(new StringReader(from.getXMLDesc(0))));
|
||||
Document doc = xmlBuilder.getDocument();
|
||||
XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//devices/disk[@device='disk']/source/@file");
|
||||
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
|
||||
String diskFileName = nodes.item(0).getNodeValue();
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
StorageVol storageVol = from.getConnect().storageVolLookupByPath(diskFileName);
|
||||
String id = storageVol.getKey();
|
||||
float size = new Long(storageVol.getInfo().capacity).floatValue();
|
||||
volumes.add(new VolumeImpl(id, Volume.Type.LOCAL, size, null, true, false));
|
||||
}
|
||||
builder.volumes((List<Volume>) volumes);
|
||||
} catch (LibvirtException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (XPathExpressionException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (ParserConfigurationException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (SAXException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -53,16 +53,16 @@ import com.google.common.collect.ImmutableMap;
|
|||
public class DomainToNodeMetadata implements Function<Domain, NodeMetadata> {
|
||||
|
||||
public static final Map<DomainInfo.DomainState, NodeState> domainStateToNodeState = ImmutableMap
|
||||
.<DomainInfo.DomainState, NodeState> builder()
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_RUNNING, NodeState.RUNNING)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_BLOCKED, NodeState.PENDING)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_PAUSED, NodeState.SUSPENDED)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTDOWN, NodeState.SUSPENDED)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF, NodeState.SUSPENDED)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_CRASHED, NodeState.ERROR)//
|
||||
.<DomainInfo.DomainState, NodeState> builder().put(DomainInfo.DomainState.VIR_DOMAIN_RUNNING,
|
||||
NodeState.RUNNING)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_BLOCKED, NodeState.PENDING)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_PAUSED, NodeState.SUSPENDED)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTDOWN, NodeState.SUSPENDED)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_SHUTOFF, NodeState.SUSPENDED)//
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_CRASHED, NodeState.ERROR)//
|
||||
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_NOSTATE, NodeState.UNRECOGNIZED)//
|
||||
.build();
|
||||
.put(DomainInfo.DomainState.VIR_DOMAIN_NOSTATE, NodeState.UNRECOGNIZED)//
|
||||
.build();
|
||||
|
||||
private final Function<Domain, Hardware> findHardwareForDomain;
|
||||
private final FindLocationForDomain findLocationForDomain;
|
||||
|
@ -71,7 +71,7 @@ public class DomainToNodeMetadata implements Function<Domain, NodeMetadata> {
|
|||
|
||||
@Inject
|
||||
DomainToNodeMetadata(Map<String, Credentials> credentialStore, Function<Domain, Hardware> findHardwareForDomain,
|
||||
FindLocationForDomain findLocationForDomain, FindImageForDomain findImageForDomain) {
|
||||
FindLocationForDomain findLocationForDomain, FindImageForDomain findImageForDomain) {
|
||||
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
|
||||
this.findHardwareForDomain = checkNotNull(findHardwareForDomain, "findHardwareForDomain");
|
||||
this.findLocationForDomain = checkNotNull(findLocationForDomain, "findLocationForDomain");
|
||||
|
@ -96,7 +96,7 @@ public class DomainToNodeMetadata implements Function<Domain, NodeMetadata> {
|
|||
builder.state(domainStateToNodeState.get(from.getInfo().state));
|
||||
// builder.publicAddresses(ImmutableSet.<String> of(from.publicAddress));
|
||||
// builder.privateAddresses(ImmutableSet.<String> of(from.privateAddress));
|
||||
builder.credentials(credentialStore.get(from.getUUIDString()));
|
||||
builder.credentials(credentialStore.get("node#" + from.getUUIDString()));
|
||||
|
||||
} catch (LibvirtException e) {
|
||||
// TODO Auto-generated catch block
|
||||
|
|
|
@ -52,7 +52,7 @@ public class LibvirtImageToImage implements Function<org.jclouds.libvirt.Image,
|
|||
OsFamily family = null;
|
||||
try {
|
||||
family = OsFamily.fromValue(from.name);
|
||||
builder.operatingSystem(new OperatingSystemBuilder().name(from.name).family(family).build());
|
||||
builder.operatingSystem(new OperatingSystemBuilder().name(from.name).family(family).description("ubuntu").build());
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("<< didn't match os(%s)", from);
|
||||
}
|
||||
|
|
|
@ -1,12 +1,41 @@
|
|||
/**
|
||||
*
|
||||
* 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.libvirt.compute.strategy;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.xpath.XPathConstants;
|
||||
import javax.xml.xpath.XPathExpression;
|
||||
import javax.xml.xpath.XPathExpressionException;
|
||||
import javax.xml.xpath.XPathFactory;
|
||||
|
||||
import org.jclouds.compute.ComputeService;
|
||||
import org.jclouds.compute.ComputeServiceAdapter;
|
||||
|
@ -17,11 +46,20 @@ import org.jclouds.libvirt.Image;
|
|||
import org.libvirt.Connect;
|
||||
import org.libvirt.Domain;
|
||||
import org.libvirt.LibvirtException;
|
||||
import org.libvirt.StoragePool;
|
||||
import org.libvirt.StorageVol;
|
||||
import org.libvirt.jna.Libvirt;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import com.google.common.base.Throwables;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.jamesmurty.utils.XMLBuilder;
|
||||
|
||||
/**
|
||||
* defines the connection between the {@link Libvirt} implementation and the jclouds
|
||||
|
@ -30,6 +68,7 @@ import com.google.common.collect.Lists;
|
|||
*/
|
||||
@Singleton
|
||||
public class LibvirtComputeServiceAdapter implements ComputeServiceAdapter<Domain, Domain, Image, Datacenter> {
|
||||
|
||||
private final Connect client;
|
||||
|
||||
@Inject
|
||||
|
@ -38,35 +77,97 @@ public class LibvirtComputeServiceAdapter implements ComputeServiceAdapter<Domai
|
|||
}
|
||||
|
||||
@Override
|
||||
public Domain createNodeAndStoreCredentials(String tag, String name, Template template,
|
||||
Map<String, Credentials> credentialStore) {
|
||||
public Domain runNodeWithTagAndNameAndStoreCredentials(String tag, String name, Template template,
|
||||
Map<String, Credentials> credentialStore) {
|
||||
// create the backend object using parameters from the template.
|
||||
// Domain from = client.createDomainInDC(template.getLocation().getId(), name,
|
||||
// Integer.parseInt(template.getImage().getProviderId()),
|
||||
// Integer.parseInt(template.getHardware().getProviderId()));
|
||||
// store the credentials so that later functions can use them
|
||||
// credentialStore.put(from.id + "", new Credentials(from.loginUser, from.password));
|
||||
return null;
|
||||
|
||||
String[] domains;
|
||||
try {
|
||||
domains = client.listDefinedDomains();
|
||||
|
||||
Domain domain = null;
|
||||
String xmlDesc = "";
|
||||
for (String domainName : domains) {
|
||||
domain = client.domainLookupByName(domainName);
|
||||
if (domainName.equals("ttylinux")) {
|
||||
domain = client.domainLookupByName(domainName);
|
||||
xmlDesc = domain.getXMLDesc(0);
|
||||
System.out.println("domain: " + domain.getUUIDString());
|
||||
|
||||
XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(xmlDesc)));
|
||||
|
||||
Document doc = builder.getDocument();
|
||||
|
||||
XPathExpression expr = null;
|
||||
NodeList nodes = null;
|
||||
String xpathString = "//devices/disk[@device='disk']/source/@file"; // +
|
||||
expr = XPathFactory.newInstance().newXPath().compile(xpathString);
|
||||
nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
|
||||
String diskFileName = nodes.item(0).getNodeValue();
|
||||
|
||||
System.out.println("\n *** diskFileName " + diskFileName);
|
||||
|
||||
StorageVol storageVol = client.storageVolLookupByPath(diskFileName);
|
||||
System.out.println(storageVol.getXMLDesc(0));
|
||||
|
||||
// cloning volume
|
||||
String poolName = "default";
|
||||
StoragePool storagePool = client.storagePoolLookupByName(poolName);
|
||||
StorageVol clonedVol = cloneVolume(storagePool, storageVol);
|
||||
|
||||
// System.out.println(generateClonedDomainXML(xmlDesc));
|
||||
domain = client.domainDefineXML(generateClonedDomainXML(xmlDesc));
|
||||
}
|
||||
}
|
||||
return domain;
|
||||
} catch (LibvirtException e) {
|
||||
return propogate(e);
|
||||
} catch (Exception e) {
|
||||
return propogate(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<Domain> listHardware() {
|
||||
public Iterable<Domain> listHardwareProfiles() {
|
||||
return listNodes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<Image> listImages() {
|
||||
return ImmutableSet.of();
|
||||
// return ImmutableSet.of();
|
||||
// TODO
|
||||
// return client.listImages();
|
||||
|
||||
List<Image> images = Lists.newArrayList();
|
||||
images.add(new Image(1, "ubuntu"));
|
||||
return images;
|
||||
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public Iterable<Domain> listNodes() {
|
||||
// try {
|
||||
// List<Domain> domains = Lists.newArrayList();
|
||||
// for (int domain : client.listDomains()) {
|
||||
// domains.add(client.domainLookupByID(domain));
|
||||
// }
|
||||
// return domains;
|
||||
// } catch (LibvirtException e) {
|
||||
// return propogate(e);
|
||||
// }
|
||||
// }
|
||||
|
||||
@Override
|
||||
public Iterable<Domain> listNodes() {
|
||||
try {
|
||||
List<Domain> domains = Lists.newArrayList();
|
||||
for (int domain : client.listDomains()) {
|
||||
domains.add(client.domainLookupByID(domain));
|
||||
for (String domain : client.listDefinedDomains()) {
|
||||
domains.add(client.domainLookupByName(domain));
|
||||
}
|
||||
return domains;
|
||||
} catch (LibvirtException e) {
|
||||
|
@ -80,6 +181,12 @@ public class LibvirtComputeServiceAdapter implements ComputeServiceAdapter<Domai
|
|||
return null;
|
||||
}
|
||||
|
||||
protected <T> T propogate(Exception e) {
|
||||
Throwables.propagate(e);
|
||||
assert false;
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<Datacenter> listLocations() {
|
||||
return ImmutableSet.of(new Datacenter(1, "SFO"));
|
||||
|
@ -111,4 +218,89 @@ public class LibvirtComputeServiceAdapter implements ComputeServiceAdapter<Domai
|
|||
propogate(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void createDomain() throws LibvirtException {
|
||||
Domain domain = client.domainDefineXML("<domain type='test' id='2'>" + " <name>deftest</name>"
|
||||
+ " <uuid>004b96e1-2d78-c30f-5aa5-f03c87d21e70</uuid>" + " <memory>8388608</memory>"
|
||||
+ " <vcpu>2</vcpu>" + " <os><type arch='i686'>hvm</type></os>" + " <on_reboot>restart</on_reboot>"
|
||||
+ " <on_poweroff>destroy</on_poweroff>" + " <on_crash>restart</on_crash>" + "</domain>");
|
||||
|
||||
}
|
||||
|
||||
private static StorageVol cloneVolume(StoragePool storagePool, StorageVol from) throws LibvirtException,
|
||||
XPathExpressionException, ParserConfigurationException, SAXException, IOException, TransformerException {
|
||||
String fromXML = from.getXMLDesc(0);
|
||||
String clonedXML = generateClonedVolumeXML(fromXML);
|
||||
System.out.println(clonedXML);
|
||||
// return null;
|
||||
return storagePool.storageVolCreateXMLFrom(clonedXML, from, 0);
|
||||
}
|
||||
|
||||
private static String generateClonedVolumeXML(String fromXML) throws ParserConfigurationException, SAXException,
|
||||
IOException, XPathExpressionException, TransformerException {
|
||||
|
||||
Properties outputProperties = new Properties();
|
||||
// Explicitly identify the output as an XML document
|
||||
outputProperties.put(javax.xml.transform.OutputKeys.METHOD, "xml");
|
||||
// Pretty-print the XML output (doesn't work in all cases)
|
||||
outputProperties.put(javax.xml.transform.OutputKeys.INDENT, "yes");
|
||||
// Get 2-space indenting when using the Apache transformer
|
||||
outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "2");
|
||||
|
||||
XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML)));
|
||||
|
||||
String cloneAppend = "-clone";
|
||||
builder.xpathFind("//volume/name").t(cloneAppend);
|
||||
builder.xpathFind("//volume/key").t(cloneAppend);
|
||||
builder.xpathFind("//volume/target/path").t(cloneAppend);
|
||||
|
||||
return builder.asString(outputProperties);
|
||||
}
|
||||
|
||||
private static String generateClonedDomainXML(String fromXML) throws ParserConfigurationException, SAXException,
|
||||
IOException, XPathExpressionException, TransformerException {
|
||||
|
||||
Properties outputProperties = new Properties();
|
||||
// Explicitly identify the output as an XML document
|
||||
outputProperties.put(javax.xml.transform.OutputKeys.METHOD, "xml");
|
||||
// Pretty-print the XML output (doesn't work in all cases)
|
||||
outputProperties.put(javax.xml.transform.OutputKeys.INDENT, "yes");
|
||||
// Get 2-space indenting when using the Apache transformer
|
||||
outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "2");
|
||||
|
||||
XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML)));
|
||||
|
||||
String cloneAppend = "-clone";
|
||||
|
||||
builder.xpathFind("//domain/name").t(cloneAppend);
|
||||
// change uuid domain
|
||||
Element oldChild = builder.xpathFind("//domain/uuid").getElement();
|
||||
Node newNode = oldChild.cloneNode(true);
|
||||
newNode.getFirstChild().setNodeValue(UUID.randomUUID().toString());
|
||||
builder.getDocument().getDocumentElement().replaceChild(newNode, oldChild);
|
||||
|
||||
builder.xpathFind("//domain/devices/disk/source").a("file", "/var/lib/libvirt/images/ttylinux.img-clone");
|
||||
// TODO generate valid MAC address
|
||||
builder.xpathFind("//domain/devices/interface/mac").a("address", "52:54:00:5c:dd:eb");
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -35,7 +35,7 @@ public class LibvirtComputeServiceContextBuilderTest {
|
|||
.createContext(new StandaloneComputeServiceContextSpec<Domain, Domain, Image, Datacenter>("libvirt",
|
||||
"test:///default", "1", "identity", "credential", new LibvirtComputeServiceContextModule(),
|
||||
ImmutableSet.<Module> of()));
|
||||
System.err.println(context.getComputeService().listNodes());
|
||||
//System.err.println(context.getComputeService().
|
||||
context.close();
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
/**
|
||||
*
|
||||
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
|
||||
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
|
||||
*
|
||||
* ====================================================================
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
|
@ -23,7 +23,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
|
|||
|
||||
import org.jclouds.compute.ComputeServiceContext;
|
||||
import org.jclouds.compute.ComputeServiceContextFactory;
|
||||
import org.jclouds.compute.RunNodesException;
|
||||
import org.jclouds.compute.StandaloneComputeServiceContextSpec;
|
||||
import org.jclouds.compute.domain.Template;
|
||||
import org.jclouds.libvirt.Datacenter;
|
||||
import org.jclouds.libvirt.Image;
|
||||
import org.jclouds.libvirt.compute.domain.LibvirtComputeServiceContextModule;
|
||||
|
@ -63,9 +65,26 @@ public class LibvirtExperimentLiveTest {
|
|||
endpoint, apiversion, identity, credential, new LibvirtComputeServiceContextModule(), ImmutableSet
|
||||
.<Module> of()));
|
||||
|
||||
context.getComputeService().listNodes();
|
||||
System.out.println("images " + context.getComputeService().listImages());
|
||||
System.out.println("nodes " + context.getComputeService().listNodes());
|
||||
System.out.println("hardware profiles " + context.getComputeService().listHardwareProfiles());
|
||||
|
||||
Template defaultTemplate = context.getComputeService().templateBuilder()
|
||||
.hardwareId("c7ff2039-a9f1-a659-7f91-e0f82f59d52e").imageId("1") //.locationId("")
|
||||
.build();
|
||||
|
||||
/*
|
||||
* We will probably make a default template out of properties at some point
|
||||
* You can control the default template via overriding a method in standalonecomputeservicexontextmodule
|
||||
*/
|
||||
|
||||
|
||||
// context.getComputeService().templateOptions().;
|
||||
context.getComputeService().runNodesWithTag("ttylinux", 1, defaultTemplate);
|
||||
|
||||
} finally {
|
||||
} catch (RunNodesException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (context != null)
|
||||
context.close();
|
||||
}
|
||||
|
|
|
@ -130,7 +130,7 @@
|
|||
<!-- ======================= -->
|
||||
|
||||
<root>
|
||||
<priority value="WARN" />
|
||||
<priority value="DEBUG" />
|
||||
</root>
|
||||
|
||||
</log4j:configuration>
|
|
@ -96,4 +96,10 @@ public class ServerManager {
|
|||
|
||||
public void rebootServer(int serverId) {
|
||||
}
|
||||
|
||||
public void stopServer(int serverId) {
|
||||
}
|
||||
|
||||
public void startServer(int serverId) {
|
||||
}
|
||||
}
|
|
@ -80,4 +80,15 @@ public class ServerManagerComputeServiceAdapter implements ComputeServiceAdapter
|
|||
public void rebootNode(String 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));
|
||||
}
|
||||
}
|
|
@ -25,11 +25,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
|
|||
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
|
||||
import org.jclouds.compute.strategy.ListNodesStrategy;
|
||||
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.SlicehostDestroyNodeStrategy;
|
||||
import org.jclouds.slicehost.compute.strategy.SlicehostGetNodeMetadataStrategy;
|
||||
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
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -19,11 +19,14 @@
|
|||
|
||||
package org.jclouds.slicehost.compute.config;
|
||||
|
||||
import static org.jclouds.compute.domain.OsFamily.UBUNTU;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.jclouds.compute.config.BaseComputeServiceContextModule;
|
||||
import org.jclouds.compute.domain.TemplateBuilder;
|
||||
import org.jclouds.compute.internal.BaseComputeService;
|
||||
import org.jclouds.domain.Location;
|
||||
import org.jclouds.domain.LocationScope;
|
||||
|
@ -31,6 +34,7 @@ import org.jclouds.domain.internal.LocationImpl;
|
|||
import org.jclouds.rest.annotations.Provider;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.inject.Injector;
|
||||
import com.google.inject.Provides;
|
||||
|
||||
/**
|
||||
|
@ -47,6 +51,11 @@ public class SlicehostComputeServiceContextModule extends BaseComputeServiceCont
|
|||
return new LocationImpl(LocationScope.ZONE, "DFW1", "Dallas, TX", provider);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
|
||||
return template.osFamily(UBUNTU).os64Bit(true);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
Set<? extends Location> provideLocations(Location location) {
|
||||
|
|
|
@ -125,7 +125,7 @@ public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> {
|
|||
}
|
||||
|
||||
}));
|
||||
builder.credentials(credentialStore.get(from.getId() + ""));
|
||||
builder.credentials(credentialStore.get("node#" + from.getId()));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
|
|
|
@ -40,7 +40,7 @@ import com.google.common.base.Function;
|
|||
@Singleton
|
||||
public class SlicehostImageToOperatingSystem implements
|
||||
Function<org.jclouds.slicehost.domain.Image, OperatingSystem> {
|
||||
public static final Pattern SLICEHOST_PATTERN = Pattern.compile("(([^ ]*) .*)");
|
||||
public static final Pattern SLICEHOST_PATTERN = Pattern.compile("(([^ ]*) ([0-9.]+) ?.*)");
|
||||
|
||||
@Resource
|
||||
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
|
||||
|
@ -52,18 +52,20 @@ public class SlicehostImageToOperatingSystem implements
|
|||
String osArch = null;
|
||||
String osVersion = null;
|
||||
String osDescription = from.getName();
|
||||
boolean is64Bit = true;
|
||||
Matcher matcher = SLICEHOST_PATTERN.matcher(from.getName());
|
||||
boolean is64Bit = !from.getName().endsWith("32-bit");
|
||||
if (from.getName().indexOf("Red Hat EL") != -1) {
|
||||
osFamily = OsFamily.RHEL;
|
||||
} else if (from.getName().indexOf("Oracle EL") != -1) {
|
||||
osFamily = OsFamily.OEL;
|
||||
} else if (matcher.find()) {
|
||||
}
|
||||
Matcher matcher = SLICEHOST_PATTERN.matcher(from.getName());
|
||||
if (matcher.find()) {
|
||||
try {
|
||||
osFamily = OsFamily.fromValue(matcher.group(2).toLowerCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("<< didn't match os(%s)", matcher.group(2));
|
||||
}
|
||||
osVersion = matcher.group(3);
|
||||
}
|
||||
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
|
||||
return os;
|
||||
|
|
|
@ -57,7 +57,7 @@ public class SlicehostAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
|
|||
public NodeMetadata addNodeWithTag(String tag, String name, Template template) {
|
||||
Slice from = client.createSlice(name, Integer.parseInt(template.getImage().getProviderId()),
|
||||
Integer.parseInt(template.getHardware().getProviderId()));
|
||||
credentialStore.put(from.getId() + "", new Credentials("root", from.getRootPassword()));
|
||||
credentialStore.put("node#" + from.getId(), new Credentials("root", from.getRootPassword()));
|
||||
return sliceToNodeMetadata.apply(from);
|
||||
}
|
||||
}
|
|
@ -25,6 +25,8 @@ 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.compute.strategy.ResumeNodeStrategy;
|
||||
import org.jclouds.compute.strategy.SuspendNodeStrategy;
|
||||
import org.jclouds.slicehost.SlicehostClient;
|
||||
|
||||
/**
|
||||
|
@ -32,12 +34,12 @@ import org.jclouds.slicehost.SlicehostClient;
|
|||
* @author Adrian Cole
|
||||
*/
|
||||
@Singleton
|
||||
public class SlicehostRebootNodeStrategy implements RebootNodeStrategy {
|
||||
public class SlicehostLifeCycleStrategy implements RebootNodeStrategy, SuspendNodeStrategy, ResumeNodeStrategy {
|
||||
private final SlicehostClient client;
|
||||
private final GetNodeMetadataStrategy getNode;
|
||||
|
||||
@Inject
|
||||
protected SlicehostRebootNodeStrategy(SlicehostClient client, GetNodeMetadataStrategy getNode) {
|
||||
protected SlicehostLifeCycleStrategy(SlicehostClient client, GetNodeMetadataStrategy getNode) {
|
||||
this.client = client;
|
||||
this.getNode = getNode;
|
||||
}
|
||||
|
@ -49,4 +51,14 @@ public class SlicehostRebootNodeStrategy implements RebootNodeStrategy {
|
|||
return getNode.getNode(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata suspendNode(String id) {
|
||||
throw new UnsupportedOperationException("suspend not supported");
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeMetadata resumeNode(String id) {
|
||||
throw new UnsupportedOperationException("resume not supported");
|
||||
}
|
||||
|
||||
}
|
|
@ -48,6 +48,7 @@ public class SlicehostComputeServiceLiveTest extends BaseComputeServiceLiveTest
|
|||
public void testTemplateBuilder() {
|
||||
Template defaultTemplate = client.templateBuilder().build();
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "9.10");
|
||||
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
|
||||
assertEquals(defaultTemplate.getLocation().getId(), "DFW1");
|
||||
assertEquals(getCores(defaultTemplate.getHardware()), 0.25d);
|
||||
|
|
|
@ -66,7 +66,7 @@ public class SliceToNodeMetadataTest {
|
|||
Slice slice = SliceHandlerTest.parseSlice();
|
||||
|
||||
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap
|
||||
.<String, Credentials> of("1", creds), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
|
||||
.<String, Credentials> of("node#1", creds), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
|
||||
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
|
||||
|
||||
NodeMetadata metadata = parser.apply(slice);
|
||||
|
@ -112,9 +112,9 @@ public class SliceToNodeMetadataTest {
|
|||
assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses(
|
||||
ImmutableSet.of("174.143.212.229")).privateAddresses(ImmutableSet.of("10.176.164.199")).tag("jclouds")
|
||||
.imageId("2").operatingSystem(
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true)
|
||||
.build()).id("1").providerId("1").name("jclouds-foo").location(provider).userMetadata(
|
||||
ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2")
|
||||
.is64Bit(true).build()).id("1").providerId("1").name("jclouds-foo").location(provider)
|
||||
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -136,8 +136,8 @@ public class SliceToNodeMetadataTest {
|
|||
ImmutableList.of(new Processor(0.25, 1.0))).ram(256).volumes(
|
||||
ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(1.0f).durable(true)
|
||||
.bootDevice(true).build())).build()).operatingSystem(
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true)
|
||||
.build()).id("1").providerId("1").name("jclouds-foo").location(provider).userMetadata(
|
||||
ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2")
|
||||
.is64Bit(true).build()).id("1").providerId("1").name("jclouds-foo").location(provider)
|
||||
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build());
|
||||
}
|
||||
}
|
|
@ -42,19 +42,29 @@ public class SlicehostImageToImageTest {
|
|||
Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
|
||||
|
||||
@Test
|
||||
public void testApplyWhereImageNotFound() throws UnknownHostException {
|
||||
assertEquals(
|
||||
convertImage(),
|
||||
new ImageBuilder()
|
||||
.name("CentOS 5.2")
|
||||
.operatingSystem(
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true)
|
||||
.build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null))
|
||||
.ids("2").build());
|
||||
public void test() throws UnknownHostException {
|
||||
assertEquals(convertImage(), new ImageBuilder().name("CentOS 5.2").operatingSystem(
|
||||
new OperatingSystemBuilder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(
|
||||
true).build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)).ids(
|
||||
"2").build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test32() throws UnknownHostException {
|
||||
assertEquals(convertImage("/test_get_image32.xml"), new ImageBuilder().name("Ubuntu 10.10 (maverick) 32-bit")
|
||||
.operatingSystem(
|
||||
new OperatingSystemBuilder().family(OsFamily.UBUNTU).version("10.10").description(
|
||||
"Ubuntu 10.10 (maverick) 32-bit").build()).description(
|
||||
"Ubuntu 10.10 (maverick) 32-bit").defaultCredentials(new Credentials("root", null)).ids("70")
|
||||
.build());
|
||||
}
|
||||
|
||||
public static Image convertImage() {
|
||||
org.jclouds.slicehost.domain.Image image = ImageHandlerTest.parseImage();
|
||||
return convertImage("/test_get_image.xml");
|
||||
}
|
||||
|
||||
public static Image convertImage(String resource) {
|
||||
org.jclouds.slicehost.domain.Image image = ImageHandlerTest.parseImage(resource);
|
||||
|
||||
SlicehostImageToImage parser = new SlicehostImageToImage(new SlicehostImageToOperatingSystem());
|
||||
|
||||
|
|
|
@ -42,12 +42,16 @@ public class ImageHandlerTest {
|
|||
static ParseSax<Image> createParser() {
|
||||
Injector injector = Guice.createInjector(new SaxParserModule());
|
||||
ParseSax<Image> parser = (ParseSax<Image>) injector.getInstance(ParseSax.Factory.class).create(
|
||||
injector.getInstance(ImageHandler.class));
|
||||
injector.getInstance(ImageHandler.class));
|
||||
return parser;
|
||||
}
|
||||
|
||||
public static Image parseImage() {
|
||||
InputStream is = ImageHandlerTest.class.getResourceAsStream("/test_get_image.xml");
|
||||
return parseImage("/test_get_image.xml");
|
||||
}
|
||||
|
||||
public static Image parseImage(String resource) {
|
||||
InputStream is = ImageHandlerTest.class.getResourceAsStream(resource);
|
||||
return createParser().parse(is);
|
||||
}
|
||||
|
||||
|
@ -56,4 +60,9 @@ public class ImageHandlerTest {
|
|||
assertEquals(parseImage(), expects);
|
||||
}
|
||||
|
||||
public void test32() {
|
||||
Image expects = new Image(70, "Ubuntu 10.10 (maverick) 32-bit");
|
||||
assertEquals(parseImage("/test_get_image32.xml"), expects);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -41,13 +41,15 @@ public class ImagesHandlerTest extends BaseHandlerTest {
|
|||
|
||||
ParseSax<Set<? extends Image>> createParser() {
|
||||
ParseSax<Set<? extends Image>> parser = (ParseSax<Set<? extends Image>>) factory.create(injector
|
||||
.getInstance(ImagesHandler.class));
|
||||
.getInstance(ImagesHandler.class));
|
||||
return parser;
|
||||
}
|
||||
|
||||
public void test() {
|
||||
InputStream is = getClass().getResourceAsStream("/test_list_images.xml");
|
||||
Set<? extends Image> expects = ImmutableSet.of(new Image(2, "CentOS 5.2"), new Image(3, "Gentoo 2008.0"),
|
||||
Set<? extends Image> expects = ImmutableSet.of(
|
||||
|
||||
new Image(2, "CentOS 5.2"), new Image(3, "Gentoo 2008.0"),
|
||||
|
||||
new Image(4, "Debian 5.0 (lenny)"),
|
||||
|
||||
|
@ -63,8 +65,10 @@ public class ImagesHandlerTest extends BaseHandlerTest {
|
|||
|
||||
new Image(11, "Ubuntu 8.10 (intrepid)"),
|
||||
|
||||
new Image(12, "Red Hat EL 5.3"),
|
||||
new Image(70, "Ubuntu 10.10 (maverick) 32-bit"),
|
||||
|
||||
new Image(12, "Red Hat EL 5.3"),
|
||||
|
||||
new Image(13, "Fedora 11 (Leonidas)")
|
||||
|
||||
);
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<images type="array">
|
||||
<image>
|
||||
<name>Ubuntu 10.10 (maverick) 32-bit</name>
|
||||
<id type="integer">70</id>
|
||||
</image>
|
||||
</images>
|
|
@ -1,47 +1,51 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<images type="array">
|
||||
<image>
|
||||
<name>CentOS 5.2</name>
|
||||
<id type="integer">2</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Gentoo 2008.0</name>
|
||||
<id type="integer">3</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Debian 5.0 (lenny)</name>
|
||||
<id type="integer">4</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Fedora 10 (Cambridge)</name>
|
||||
<id type="integer">5</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>CentOS 5.3</name>
|
||||
<id type="integer">7</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Ubuntu 9.04 (jaunty)</name>
|
||||
<id type="integer">8</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Arch 2009.02</name>
|
||||
<id type="integer">9</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Ubuntu 8.04.2 LTS (hardy)</name>
|
||||
<id type="integer">10</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Ubuntu 8.10 (intrepid)</name>
|
||||
<id type="integer">11</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Red Hat EL 5.3</name>
|
||||
<id type="integer">12</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Fedora 11 (Leonidas)</name>
|
||||
<id type="integer">13</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>CentOS 5.2</name>
|
||||
<id type="integer">2</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Gentoo 2008.0</name>
|
||||
<id type="integer">3</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Debian 5.0 (lenny)</name>
|
||||
<id type="integer">4</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Fedora 10 (Cambridge)</name>
|
||||
<id type="integer">5</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>CentOS 5.3</name>
|
||||
<id type="integer">7</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Ubuntu 9.04 (jaunty)</name>
|
||||
<id type="integer">8</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Arch 2009.02</name>
|
||||
<id type="integer">9</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Ubuntu 8.04.2 LTS (hardy)</name>
|
||||
<id type="integer">10</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Ubuntu 8.10 (intrepid)</name>
|
||||
<id type="integer">11</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Ubuntu 10.10 (maverick) 32-bit</name>
|
||||
<id type="integer">70</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Red Hat EL 5.3</name>
|
||||
<id type="integer">12</id>
|
||||
</image>
|
||||
<image>
|
||||
<name>Fedora 11 (Leonidas)</name>
|
||||
<id type="integer">13</id>
|
||||
</image>
|
||||
</images>
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue