There can be only one retryable predicate; use Predicates2.retry decorator

This commit is contained in:
Adrian Cole 2013-01-13 20:30:34 -08:00
parent 6a8ac673aa
commit a49a060152
107 changed files with 1131 additions and 2179 deletions

View File

@ -18,6 +18,7 @@
*/ */
package org.jclouds.atmos.util; package org.jclouds.atmos.util;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.util.Predicates2.retry;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
@ -40,7 +41,6 @@ import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpException; import org.jclouds.http.HttpException;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -87,7 +87,7 @@ public class AtmosUtils {
} }
public static void deletePathAndEnsureGone(final AtmosClient sync, String path) { public static void deletePathAndEnsureGone(final AtmosClient sync, String path) {
checkState(new RetryablePredicate<String>(new Predicate<String>() { checkState(retry(new Predicate<String>() {
public boolean apply(String in) { public boolean apply(String in) {
try { try {
sync.deletePath(in); sync.deletePath(in);

View File

@ -19,6 +19,7 @@
package org.jclouds.atmos; package org.jclouds.atmos;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail; import static org.testng.Assert.fail;
@ -42,7 +43,6 @@ import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.io.payloads.InputStreamPayload; import org.jclouds.io.payloads.InputStreamPayload;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.util.Strings2; import org.jclouds.util.Strings2;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -328,7 +328,7 @@ public class AtmosClientLiveTest extends BaseBlobStoreIntegrationTest {
getApi().deletePath(path); getApi().deletePath(path);
} catch (KeyNotFoundException ex) { } catch (KeyNotFoundException ex) {
} }
checkState(new RetryablePredicate<String>(new Predicate<String>() { checkState(retry(new Predicate<String>() {
public boolean apply(String in) { public boolean apply(String in) {
try { try {
return !getApi().pathExists(in); return !getApi().pathExists(in);

View File

@ -27,7 +27,6 @@ import org.jclouds.cloudservers.compute.functions.CloudServersImageToImage;
import org.jclouds.cloudservers.compute.functions.CloudServersImageToOperatingSystem; import org.jclouds.cloudservers.compute.functions.CloudServersImageToOperatingSystem;
import org.jclouds.cloudservers.compute.functions.FlavorToHardware; import org.jclouds.cloudservers.compute.functions.FlavorToHardware;
import org.jclouds.cloudservers.compute.functions.ServerToNodeMetadata; import org.jclouds.cloudservers.compute.functions.ServerToNodeMetadata;
import org.jclouds.cloudservers.compute.predicates.GetImageWhenStatusActivePredicateWithResult;
import org.jclouds.cloudservers.compute.strategy.CloudServersComputeServiceAdapter; import org.jclouds.cloudservers.compute.strategy.CloudServersComputeServiceAdapter;
import org.jclouds.cloudservers.domain.Flavor; import org.jclouds.cloudservers.domain.Flavor;
import org.jclouds.cloudservers.domain.ImageStatus; import org.jclouds.cloudservers.domain.ImageStatus;
@ -40,9 +39,9 @@ import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.functions.IdentityFunction; import org.jclouds.functions.IdentityFunction;
import org.jclouds.predicates.PredicateWithResult;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -85,10 +84,6 @@ public class CloudServersComputeServiceContextModule extends
bind(new TypeLiteral<ImageExtension>() { bind(new TypeLiteral<ImageExtension>() {
}).to(CloudServersImageExtension.class); }).to(CloudServersImageExtension.class);
bind(new TypeLiteral<PredicateWithResult<Integer, Image>>() {
}).to(GetImageWhenStatusActivePredicateWithResult.class);
} }
@VisibleForTesting @VisibleForTesting

View File

@ -21,10 +21,11 @@ package org.jclouds.cloudservers.compute.extensions;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
@ -36,16 +37,20 @@ import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.domain.Server; import org.jclouds.cloudservers.domain.Server;
import org.jclouds.compute.domain.CloneImageTemplate; import org.jclouds.compute.domain.CloneImageTemplate;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.ImageTemplate; import org.jclouds.compute.domain.ImageTemplate;
import org.jclouds.compute.domain.ImageTemplateBuilder; import org.jclouds.compute.domain.ImageTemplateBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.PredicateWithResult;
import org.jclouds.predicates.Retryables;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.UncheckedTimeoutException;
/** /**
* CloudServers implementation of {@link ImageExtension} * CloudServers implementation of {@link ImageExtension}
@ -62,20 +67,16 @@ public class CloudServersImageExtension implements ImageExtension {
private final CloudServersClient client; private final CloudServersClient client;
private final ListeningExecutorService userExecutor; private final ListeningExecutorService userExecutor;
private final PredicateWithResult<Integer, Image> imageAvailablePredicate; private final Supplier<Location> location;
@com.google.inject.Inject(optional = true) private final Predicate<AtomicReference<Image>> imageAvailablePredicate;
@Named("IMAGE_MAX_WAIT")
private long maxWait = 3600;
@com.google.inject.Inject(optional = true)
@Named("IMAGE_WAIT_PERIOD")
private long waitPeriod = 1;
@Inject @Inject
public CloudServersImageExtension(CloudServersClient client, public CloudServersImageExtension(CloudServersClient client, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, Supplier<Location> location,
PredicateWithResult<Integer, Image> imageAvailablePredicate) { @Named(TIMEOUT_IMAGE_AVAILABLE) Predicate<AtomicReference<Image>> imageAvailablePredicate) {
this.client = checkNotNull(client, "client"); this.client = checkNotNull(client, "client");
this.userExecutor = checkNotNull(userExecutor, "userExecutor"); this.userExecutor = checkNotNull(userExecutor, "userExecutor");
this.location = checkNotNull(location, "location");
this.imageAvailablePredicate = checkNotNull(imageAvailablePredicate, "imageAvailablePredicate"); this.imageAvailablePredicate = checkNotNull(imageAvailablePredicate, "imageAvailablePredicate");
} }
@ -93,17 +94,25 @@ public class CloudServersImageExtension implements ImageExtension {
checkState(template instanceof CloneImageTemplate, checkState(template instanceof CloneImageTemplate,
" openstack-nova only supports creating images through cloning."); " openstack-nova only supports creating images through cloning.");
CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; CloneImageTemplate cloneTemplate = (CloneImageTemplate) template;
final org.jclouds.cloudservers.domain.Image image = client.createImageFromServer(cloneTemplate.getName(), org.jclouds.cloudservers.domain.Image csImage = client.createImageFromServer(cloneTemplate.getName(),
Integer.parseInt(cloneTemplate.getSourceNodeId())); Integer.parseInt(cloneTemplate.getSourceNodeId()));
final AtomicReference<Image> image = new AtomicReference<Image>(new ImageBuilder()
.location(location.get())
.ids(csImage.getId() + "")
.description(cloneTemplate.getName())
.operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build())
.status(Image.Status.PENDING).build());
return userExecutor.submit(new Callable<Image>() { return userExecutor.submit(new Callable<Image>() {
@Override @Override
public Image call() throws Exception { public Image call() throws Exception {
return Retryables.retryGettingResultOrFailing(imageAvailablePredicate, image.getId(), maxWait, waitPeriod, if (imageAvailablePredicate.apply(image))
TimeUnit.SECONDS, "Image was not created within the time limit, Giving up! [Limit: " + maxWait return image.get();
+ " secs.]"); // TODO: get rid of the expectation that the image will be available, as it is very brittle
throw new UncheckedTimeoutException("Image was not created within the time limit: " + image.get());
} }
}); });
} }
@Override @Override

View File

@ -1,99 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.cloudservers.compute.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import org.jclouds.cloudservers.CloudServersClient;
import org.jclouds.cloudservers.options.ListOptions;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.predicates.PredicateWithResult;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
*
* @author David Alves
*
*/
public final class GetImageWhenStatusActivePredicateWithResult implements PredicateWithResult<Integer, Image> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final CloudServersClient client;
private final Function<org.jclouds.cloudservers.domain.Image, Image> cloudserversImageToImage;
private org.jclouds.cloudservers.domain.Image result;
private RuntimeException lastFailure;
@Inject
public GetImageWhenStatusActivePredicateWithResult(CloudServersClient client,
Function<org.jclouds.cloudservers.domain.Image, Image> cloudserversImageToImage) {
this.client = client;
this.cloudserversImageToImage = cloudserversImageToImage;
}
@Override
public boolean apply(Integer input) {
result = checkNotNull(findImage(input));
switch (result.getStatus()) {
case ACTIVE:
logger.info("<< Image %s is available for use. %s", input, result);
return true;
case QUEUED:
case PREPARING:
case SAVING:
logger.debug("<< Image %s is not available yet. %s", input, result);
return false;
default:
lastFailure = new IllegalStateException("Image " + input + " was not created. " + result);
throw lastFailure;
}
}
@Override
public Image getResult() {
return cloudserversImageToImage.apply(result);
}
@Override
public Throwable getLastFailure() {
return lastFailure;
}
private org.jclouds.cloudservers.domain.Image findImage(final int id) {
return Iterables.tryFind(client.listImages(new ListOptions().withDetails()),
new Predicate<org.jclouds.cloudservers.domain.Image>() {
@Override
public boolean apply(org.jclouds.cloudservers.domain.Image input) {
return input.getId() == id;
}
}).orNull();
}
}

View File

@ -18,9 +18,11 @@
*/ */
package org.jclouds.cloudservers; package org.jclouds.cloudservers;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withFile; import static org.jclouds.cloudservers.options.CreateServerOptions.Builder.withFile;
import static org.jclouds.cloudservers.options.CreateSharedIpGroupOptions.Builder.withServer; import static org.jclouds.cloudservers.options.CreateSharedIpGroupOptions.Builder.withServer;
import static org.jclouds.cloudservers.options.ListOptions.Builder.withDetails; import static org.jclouds.cloudservers.options.ListOptions.Builder.withDetails;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -30,7 +32,6 @@ import java.lang.reflect.UndeclaredThrowableException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.cloudservers.domain.BackupSchedule; import org.jclouds.cloudservers.domain.BackupSchedule;
import org.jclouds.cloudservers.domain.DailyBackup; import org.jclouds.cloudservers.domain.DailyBackup;
@ -49,7 +50,6 @@ import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.domain.LoginCredentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshException; import org.jclouds.ssh.SshException;
@ -91,7 +91,7 @@ public class CloudServersClientLiveTest extends BaseComputeServiceContextLiveTes
client = injector.getInstance(CloudServersClient.class); client = injector.getInstance(CloudServersClient.class);
sshFactory = injector.getInstance(SshClient.Factory.class); sshFactory = injector.getInstance(SshClient.Factory.class);
SocketOpen socketOpen = injector.getInstance(SocketOpen.class); SocketOpen socketOpen = injector.getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<HostAndPort>(socketOpen, 120, 1, TimeUnit.SECONDS); socketTester = retry(socketOpen, 120, 1, SECONDS);
injector.injectMembers(socketOpen); // add logger injector.injectMembers(socketOpen); // add logger
} }

View File

@ -0,0 +1,95 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.cloudservers.compute.extensions;
import static org.testng.Assert.assertEquals;
import org.jclouds.cloudservers.internal.BaseCloudServersComputeServiceExpectTest;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageTemplate;
import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.net.HttpHeaders;
import com.google.common.util.concurrent.Futures;
/**
*
* @author David Alves
*
*/
@Test(groups = "unit", testName = "CloudServersImageExtensionExpectTest")
public class CloudServersImageExtensionExpectTest extends BaseCloudServersComputeServiceExpectTest<ComputeService> {
private HttpRequest getServerDetail = HttpRequest.builder().method("GET")
.endpoint("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/servers/1234?format=json&now=1257695648897")
.addHeader(HttpHeaders.ACCEPT, "application/json")
.addHeader("X-Auth-Token", authToken).build();
private HttpResponse getServerResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/test_get_server_detail.json")).build();
HttpRequest createImage = HttpRequest.builder().method("POST")
.endpoint("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images?format=json&now=1257695648897")
.addHeader("Accept", "application/json")
.addHeader("X-Auth-Token", authToken)
.payload(
payloadFromStringWithContentType(
"{\"image\":{\"serverId\":1234,\"name\":\"test\"}}",
"application/json")).build();
HttpResponse createImageResponse = HttpResponse.builder().statusCode(200)
.payload(
payloadFromStringWithContentType(
"{\"image\":{\"id\":2,\"serverId\":1234,\"name\":\"test\",\"status\":\"SAVING\"}}",
"application/json")).build();
private HttpRequest getImage = HttpRequest.builder().method("GET")
.endpoint("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/2?format=json&now=1257695648897")
.addHeader(HttpHeaders.ACCEPT, "application/json")
.addHeader("X-Auth-Token", authToken).build();
private HttpResponse getImageResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/test_get_image_active.json")).build();
public void testCreateImage() {
Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();
requestResponseMap.put(initialAuth, responseWithAuth);
requestResponseMap.put(getServerDetail, getServerResponse).build();
requestResponseMap.put(createImage, createImageResponse).build();
requestResponseMap.put(getImage, getImageResponse).build();
ImageExtension apiThatCreatesImage = requestsSendResponses(requestResponseMap.build()).getImageExtension().get();
ImageTemplate newImageTemplate = apiThatCreatesImage.buildImageTemplateFromNode("test", "1234");
Image image = Futures.getUnchecked(apiThatCreatesImage.createImage(newImageTemplate));
assertEquals(image.getId(), "2");
}
public ComputeService apply(ComputeServiceContext input) {
return input.getComputeService();
}
}

View File

@ -1,97 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.cloudservers.compute.predicates;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.net.URI;
import java.util.Map;
import org.jclouds.cloudservers.internal.BaseCloudServersComputeServiceExpectTest;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Image;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.predicates.PredicateWithResult;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.net.HttpHeaders;
import com.google.inject.Injector;
/**
*
* @author David Alves
*
*/
@Test(groups = "unit", testName = "GetImageWhenStatusActivePredicateWithResultExpectTest")
public class GetImageWhenStatusActivePredicateWithResultExpectTest extends
BaseCloudServersComputeServiceExpectTest<Injector> {
private final HttpRequest listImagesDetail = HttpRequest
.builder()
.method("GET")
.endpoint(
URI.create("https://lon.servers.api.rackspacecloud.com/v1.0/10001786/images/detail?format=json&now=1257695648897"))
.headers(ImmutableMultimap.<String, String> builder()
.put(HttpHeaders.ACCEPT, "application/json")
.put("X-Auth-Token", authToken).build()).build();
private final HttpResponse listImagesResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/test_list_images_detail_imageextension.json")).build();
private final Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()
.put(listImagesDetail, listImagesResponse).put(initialAuth, responseWithAuth).build();
public void testReturnsFalseOnQueuedAndSavingAndTrueOnActive() {
Injector injector = requestsSendResponses(requestResponseMap);
PredicateWithResult<Integer, Image> predicate = injector
.getInstance(GetImageWhenStatusActivePredicateWithResult.class);
assertTrue(predicate.apply(2));// ACTIVE
assertFalse(predicate.apply(743));// SAVING
assertFalse(predicate.apply(744));// QUEUED
assertFalse(predicate.apply(747));// PREPARING
}
public void testFailsOnOtherStatuses() {
Injector injector = requestsSendResponses(requestResponseMap);
PredicateWithResult<Integer, Image> predicate = injector
.getInstance(GetImageWhenStatusActivePredicateWithResult.class);
assertTrue(illegalStateExceptionThrown(predicate, 745));// UNRECOGNIZED
assertTrue(illegalStateExceptionThrown(predicate, 746));// UNKNOWN
assertTrue(illegalStateExceptionThrown(predicate, 748));// FAILED
}
private boolean illegalStateExceptionThrown(PredicateWithResult<Integer, Image> predicate, Integer id) {
try {
predicate.apply(id);
} catch (IllegalStateException e) {
return true;
}
return false;
}
@Override
public Injector apply(ComputeServiceContext input) {
return input.utils().injector();
}
}

View File

@ -0,0 +1,11 @@
{
"image" : {
"id" : 2,
"name" : "CentOS 5.2",
"serverId" : 12,
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"status" : "ACTIVE",
"progress" : 100
}
}

View File

@ -18,7 +18,8 @@
*/ */
package org.jclouds.cloudsigma.compute.config; package org.jclouds.cloudsigma.compute.config;
import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.util.Predicates2.retry;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -46,10 +47,9 @@ import org.jclouds.compute.domain.OsFamilyVersion64Bit;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.functions.IdentityFunction; import org.jclouds.functions.IdentityFunction;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -114,10 +114,8 @@ public class CloudSigmaComputeServiceContextModule extends
@Provides @Provides
@Singleton @Singleton
protected Predicate<DriveInfo> supplyDriveUnclaimed(DriveClaimed driveClaimed, protected Predicate<DriveInfo> supplyDriveUnclaimed(DriveClaimed driveClaimed, Timeouts timeouts) {
ComputeServiceConstants.Timeouts timeouts) { return retry(Predicates.not(driveClaimed), timeouts.nodeRunning, 1000, MILLISECONDS);
return new RetryablePredicate<DriveInfo>(Predicates.not(driveClaimed), timeouts.nodeRunning, 1000,
TimeUnit.MILLISECONDS);
} }
@Provides @Provides

View File

@ -17,13 +17,13 @@
* under the License. * under the License.
*/ */
package org.jclouds.cloudsigma; package org.jclouds.cloudsigma;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jclouds.cloudsigma.domain.ClaimType; import org.jclouds.cloudsigma.domain.ClaimType;
@ -47,7 +47,6 @@ import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.domain.LoginCredentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.sshj.config.SshjSshClientModule;
@ -92,10 +91,8 @@ public class CloudSigmaClientLiveTest extends BaseComputeServiceContextLiveTest
cloudSigmaContext = view.unwrap(); cloudSigmaContext = view.unwrap();
client = cloudSigmaContext.getApi(); client = cloudSigmaContext.getApi();
driveNotClaimed = new RetryablePredicate<DriveInfo>(Predicates.not(new DriveClaimed(client)), maxDriveImageTime, driveNotClaimed = retry(Predicates.not(new DriveClaimed(client)), maxDriveImageTime, 1, SECONDS);
1, TimeUnit.SECONDS); socketTester = retry(new InetSocketAddressConnect(), maxDriveImageTime, 1, SECONDS);
socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), maxDriveImageTime, 1,
TimeUnit.SECONDS);
if (template == null || template.getImageId() == null) { if (template == null || template.getImageId() == null) {
imageId = view.getComputeService().templateBuilder().build().getImage().getId(); imageId = view.getComputeService().templateBuilder().build().getImage().getId();

View File

@ -18,7 +18,9 @@
*/ */
package org.jclouds.cloudstack.compute.config; package org.jclouds.cloudstack.compute.config;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import static org.jclouds.util.Predicates2.retry;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -65,7 +67,6 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier; import org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;
@ -183,8 +184,7 @@ public class CloudStackComputeServiceContextModule extends
@Provides @Provides
@Singleton @Singleton
protected Predicate<String> jobComplete(JobComplete jobComplete) { protected Predicate<String> jobComplete(JobComplete jobComplete) {
// TODO: parameterize return retry(jobComplete, 1200, 1, 5, SECONDS);
return new RetryablePredicate<String>(jobComplete, 1200, 1, 5, TimeUnit.SECONDS);
} }
@Provides @Provides

View File

@ -17,20 +17,17 @@
* under the License. * under the License.
*/ */
package org.jclouds.cloudstack.compute; package org.jclouds.cloudstack.compute;
import static com.google.common.collect.Iterables.getFirst; import static com.google.common.collect.Iterables.getFirst;
import static com.google.inject.name.Names.bindProperties; import static com.google.inject.name.Names.bindProperties;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import org.jclouds.cloudstack.domain.FirewallRule; import static org.jclouds.util.Predicates2.retry;
import org.jclouds.cloudstack.functions.GetFirewallRulesByVirtualMachine;
import org.jclouds.cloudstack.functions.GetIPForwardingRulesByVirtualMachine;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertFalse;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -39,6 +36,7 @@ import org.jclouds.cloudstack.compute.config.CloudStackComputeServiceContextModu
import org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions; import org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;
import org.jclouds.cloudstack.compute.strategy.CloudStackComputeServiceAdapter; import org.jclouds.cloudstack.compute.strategy.CloudStackComputeServiceAdapter;
import org.jclouds.cloudstack.compute.strategy.OptionsConverter; import org.jclouds.cloudstack.compute.strategy.OptionsConverter;
import org.jclouds.cloudstack.domain.FirewallRule;
import org.jclouds.cloudstack.domain.IPForwardingRule; import org.jclouds.cloudstack.domain.IPForwardingRule;
import org.jclouds.cloudstack.domain.Network; import org.jclouds.cloudstack.domain.Network;
import org.jclouds.cloudstack.domain.NetworkType; import org.jclouds.cloudstack.domain.NetworkType;
@ -46,9 +44,11 @@ import org.jclouds.cloudstack.domain.ServiceOffering;
import org.jclouds.cloudstack.domain.User; import org.jclouds.cloudstack.domain.User;
import org.jclouds.cloudstack.domain.VirtualMachine; import org.jclouds.cloudstack.domain.VirtualMachine;
import org.jclouds.cloudstack.domain.Zone; import org.jclouds.cloudstack.domain.Zone;
import org.jclouds.cloudstack.internal.BaseCloudStackClientLiveTest; import org.jclouds.cloudstack.functions.GetFirewallRulesByVirtualMachine;
import org.jclouds.cloudstack.functions.GetIPForwardingRulesByVirtualMachine;
import org.jclouds.cloudstack.functions.StaticNATVirtualMachineInNetwork; import org.jclouds.cloudstack.functions.StaticNATVirtualMachineInNetwork;
import org.jclouds.cloudstack.functions.ZoneIdToZone; import org.jclouds.cloudstack.functions.ZoneIdToZone;
import org.jclouds.cloudstack.internal.BaseCloudStackClientLiveTest;
import org.jclouds.cloudstack.predicates.JobComplete; import org.jclouds.cloudstack.predicates.JobComplete;
import org.jclouds.cloudstack.predicates.TemplatePredicates; import org.jclouds.cloudstack.predicates.TemplatePredicates;
import org.jclouds.cloudstack.suppliers.GetCurrentUser; import org.jclouds.cloudstack.suppliers.GetCurrentUser;
@ -62,7 +62,6 @@ import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCred
import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate; import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.annotations.Identity; import org.jclouds.rest.annotations.Identity;
import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
@ -129,7 +128,7 @@ public class CloudStackComputeServiceAdapterLiveTest extends BaseCloudStackClien
@Provides @Provides
@Singleton @Singleton
protected Predicate<String> jobComplete(JobComplete jobComplete) { protected Predicate<String> jobComplete(JobComplete jobComplete) {
return new RetryablePredicate<String>(jobComplete, 1200, 1, 5, TimeUnit.SECONDS); return retry(jobComplete, 1200, 1, 5, SECONDS);
} }
@Provides @Provides

View File

@ -19,8 +19,10 @@
package org.jclouds.cloudstack.features; package org.jclouds.cloudstack.features;
import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Iterables.find;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.cloudstack.predicates.NetworkPredicates.hasLoadBalancerService; import static org.jclouds.cloudstack.predicates.NetworkPredicates.hasLoadBalancerService;
import static org.jclouds.cloudstack.predicates.NetworkPredicates.isVirtualNetwork; import static org.jclouds.cloudstack.predicates.NetworkPredicates.isVirtualNetwork;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -28,7 +30,6 @@ import static org.testng.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.cloudstack.domain.AsyncJob; import org.jclouds.cloudstack.domain.AsyncJob;
import org.jclouds.cloudstack.domain.JobResult; import org.jclouds.cloudstack.domain.JobResult;
@ -40,7 +41,6 @@ import org.jclouds.cloudstack.domain.PublicIPAddress;
import org.jclouds.cloudstack.domain.VirtualMachine; import org.jclouds.cloudstack.domain.VirtualMachine;
import org.jclouds.cloudstack.internal.BaseCloudStackClientLiveTest; import org.jclouds.cloudstack.internal.BaseCloudStackClientLiveTest;
import org.jclouds.cloudstack.predicates.LoadBalancerRuleActive; import org.jclouds.cloudstack.predicates.LoadBalancerRuleActive;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.ssh.SshException; import org.jclouds.ssh.SshException;
import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
@ -60,16 +60,14 @@ public class LoadBalancerClientLiveTest extends BaseCloudStackClientLiveTest {
private PublicIPAddress ip = null; private PublicIPAddress ip = null;
private VirtualMachine vm; private VirtualMachine vm;
private LoadBalancerRule rule; private LoadBalancerRule rule;
private RetryablePredicate<LoadBalancerRule> loadBalancerRuleActive; private Predicate<LoadBalancerRule> loadBalancerRuleActive;
private Network network; private Network network;
private boolean networksDisabled; private boolean networksDisabled;
@BeforeGroups(groups = "live") @BeforeGroups(groups = "live")
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
loadBalancerRuleActive = retry(new LoadBalancerRuleActive(client), 60, 1, 1, SECONDS);
loadBalancerRuleActive = new RetryablePredicate<LoadBalancerRule>(new LoadBalancerRuleActive(client), 60, 1, 1,
TimeUnit.SECONDS);
prefix += "rule"; prefix += "rule";
try { try {
network = find(client.getNetworkClient().listNetworks(), network = find(client.getNetworkClient().listNetworks(),

View File

@ -36,8 +36,6 @@ import org.jclouds.cloudstack.domain.Volume;
import org.jclouds.cloudstack.internal.BaseCloudStackClientLiveTest; import org.jclouds.cloudstack.internal.BaseCloudStackClientLiveTest;
import org.jclouds.cloudstack.options.ListSnapshotsOptions; import org.jclouds.cloudstack.options.ListSnapshotsOptions;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.PredicateCallable;
import org.jclouds.predicates.Retryables;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -121,18 +119,10 @@ public class SnapshotClientLiveTest extends BaseCloudStackClientLiveTest {
public void testCreateSnapshotFromVolume() { public void testCreateSnapshotFromVolume() {
final Volume volume = getPreferredVolume(); //fail fast if none final Volume volume = getPreferredVolume(); //fail fast if none
logger.info("creating snapshot from volume %s", volume);
Snapshot snapshot = Retryables.retryGettingResultOrFailing(new PredicateCallable<Snapshot>() { AsyncCreateResponse job = client.getSnapshotClient().createSnapshot(volume.getId());
public Snapshot call() { assertTrue(jobComplete.apply(job.getJobId()));
logger.info("creating snapshot from volume %s", volume); Snapshot snapshot = findSnapshotWithId(job.getId());
AsyncCreateResponse job = client.getSnapshotClient().createSnapshot(volume.getId());
assertTrue(jobComplete.apply(job.getJobId()));
return findSnapshotWithId(job.getId());
}
protected void onFailure() {
logger.info("failed creating snapshot (retrying): %s", getLastFailure());
}
}, null, 60*1000, "failed to create snapshot");
logger.info("created snapshot %s from volume %s", snapshot, volume); logger.info("created snapshot %s from volume %s", snapshot, volume);
checkSnapshot(snapshot); checkSnapshot(snapshot);
client.getSnapshotClient().deleteSnapshot(snapshot.getId()); client.getSnapshotClient().deleteSnapshot(snapshot.getId());

View File

@ -19,6 +19,7 @@
package org.jclouds.cloudstack.features; package org.jclouds.cloudstack.features;
import static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.zoneId; import static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.zoneId;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -44,7 +45,6 @@ import org.jclouds.cloudstack.options.ListNetworksOptions;
import org.jclouds.cloudstack.options.ListVolumesOptions; import org.jclouds.cloudstack.options.ListVolumesOptions;
import org.jclouds.cloudstack.options.RegisterTemplateOptions; import org.jclouds.cloudstack.options.RegisterTemplateOptions;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -186,7 +186,7 @@ public class TemplateClientLiveTest extends BaseCloudStackClientLiveTest {
return t2.getStatus() == Template.Status.DOWNLOADED; return t2.getStatus() == Template.Status.DOWNLOADED;
} }
}; };
assertTrue(new RetryablePredicate<Template>(templateReadyPredicate, 60000).apply(registeredTemplate)); assertTrue(retry(templateReadyPredicate, 60000).apply(registeredTemplate));
// Create a VM that uses this template // Create a VM that uses this template
vmForRegistration = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network, registeredTemplate.getId(), client, jobComplete, virtualMachineRunning); vmForRegistration = VirtualMachineClientLiveTest.createVirtualMachineInNetwork(network, registeredTemplate.getId(), client, jobComplete, virtualMachineRunning);

View File

@ -52,7 +52,6 @@ import org.jclouds.cloudstack.options.ListNetworkOfferingsOptions;
import org.jclouds.cloudstack.options.ListNetworksOptions; import org.jclouds.cloudstack.options.ListNetworksOptions;
import org.jclouds.cloudstack.options.ListTemplatesOptions; import org.jclouds.cloudstack.options.ListTemplatesOptions;
import org.jclouds.cloudstack.options.ListVirtualMachinesOptions; import org.jclouds.cloudstack.options.ListVirtualMachinesOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.util.InetAddresses2; import org.jclouds.util.InetAddresses2;
import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -87,7 +86,7 @@ public class VirtualMachineClientLiveTest extends BaseCloudStackClientLiveTest {
}; };
public static VirtualMachine createVirtualMachine(CloudStackClient client, String defaultTemplate, public static VirtualMachine createVirtualMachine(CloudStackClient client, String defaultTemplate,
RetryablePredicate<String> jobComplete, RetryablePredicate<VirtualMachine> virtualMachineRunning) { Predicate<String> jobComplete, Predicate<VirtualMachine> virtualMachineRunning) {
Set<Network> networks = client.getNetworkClient().listNetworks(isDefault(true)); Set<Network> networks = client.getNetworkClient().listNetworks(isDefault(true));
if (networks.size() > 0) { if (networks.size() > 0) {
Network network = get(filter(networks, new Predicate<Network>() { Network network = get(filter(networks, new Predicate<Network>() {
@ -116,15 +115,15 @@ public class VirtualMachineClientLiveTest extends BaseCloudStackClientLiveTest {
} }
public static VirtualMachine createVirtualMachineWithSecurityGroupInZone(String zoneId, String templateId, String groupId, public static VirtualMachine createVirtualMachineWithSecurityGroupInZone(String zoneId, String templateId, String groupId,
CloudStackClient client, RetryablePredicate<String> jobComplete, CloudStackClient client, Predicate<String> jobComplete,
RetryablePredicate<VirtualMachine> virtualMachineRunning) { Predicate<VirtualMachine> virtualMachineRunning) {
return createVirtualMachineWithOptionsInZone(new DeployVirtualMachineOptions().securityGroupId(groupId), zoneId, return createVirtualMachineWithOptionsInZone(new DeployVirtualMachineOptions().securityGroupId(groupId), zoneId,
templateId, client, jobComplete, virtualMachineRunning); templateId, client, jobComplete, virtualMachineRunning);
} }
public static VirtualMachine createVirtualMachineInNetwork(Network network, String templateId, public static VirtualMachine createVirtualMachineInNetwork(Network network, String templateId,
CloudStackClient client, RetryablePredicate<String> jobComplete, CloudStackClient client, Predicate<String> jobComplete,
RetryablePredicate<VirtualMachine> virtualMachineRunning) { Predicate<VirtualMachine> virtualMachineRunning) {
DeployVirtualMachineOptions options = new DeployVirtualMachineOptions(); DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();
String zoneId = network.getZoneId(); String zoneId = network.getZoneId();
options.networkId(network.getId()); options.networkId(network.getId());
@ -134,7 +133,7 @@ public class VirtualMachineClientLiveTest extends BaseCloudStackClientLiveTest {
public static VirtualMachine createVirtualMachineInNetworkWithIp( public static VirtualMachine createVirtualMachineInNetworkWithIp(
CloudStackClient client, String templateId, Set<Network> networks, Map<String, String> ipToNetwork, CloudStackClient client, String templateId, Set<Network> networks, Map<String, String> ipToNetwork,
RetryablePredicate<String> jobComplete, RetryablePredicate<VirtualMachine> virtualMachineRunning) { Predicate<String> jobComplete, Predicate<VirtualMachine> virtualMachineRunning) {
DeployVirtualMachineOptions options = new DeployVirtualMachineOptions(); DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();
@ -152,8 +151,8 @@ public class VirtualMachineClientLiveTest extends BaseCloudStackClientLiveTest {
} }
public static VirtualMachine createVirtualMachineWithOptionsInZone(DeployVirtualMachineOptions options, String zoneId, public static VirtualMachine createVirtualMachineWithOptionsInZone(DeployVirtualMachineOptions options, String zoneId,
String templateId, CloudStackClient client, RetryablePredicate<String> jobComplete, String templateId, CloudStackClient client, Predicate<String> jobComplete,
RetryablePredicate<VirtualMachine> virtualMachineRunning) { Predicate<VirtualMachine> virtualMachineRunning) {
String serviceOfferingId = DEFAULT_SIZE_ORDERING.min(client.getOfferingClient().listServiceOfferings()).getId(); String serviceOfferingId = DEFAULT_SIZE_ORDERING.min(client.getOfferingClient().listServiceOfferings()).getId();
System.out.printf("serviceOfferingId %s, templateId %s, zoneId %s, options %s%n", serviceOfferingId, templateId, System.out.printf("serviceOfferingId %s, templateId %s, zoneId %s, options %s%n", serviceOfferingId, templateId,

View File

@ -40,8 +40,6 @@ import org.jclouds.cloudstack.domain.Zone;
import org.jclouds.cloudstack.internal.BaseCloudStackClientLiveTest; import org.jclouds.cloudstack.internal.BaseCloudStackClientLiveTest;
import org.jclouds.cloudstack.options.ListVolumesOptions; import org.jclouds.cloudstack.options.ListVolumesOptions;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.PredicateCallable;
import org.jclouds.predicates.Retryables;
import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -152,15 +150,11 @@ public class VolumeClientLiveTest extends BaseCloudStackClientLiveTest {
} }
protected Volume createPreferredVolumeFromDisk() { protected Volume createPreferredVolumeFromDisk() {
return Retryables.retryGettingResultOrFailing(new PredicateCallable<Volume>() { AsyncCreateResponse job = client.getVolumeClient().createVolumeFromDiskOfferingInZone(prefix + "-jclouds-volume",
public Volume call() { getPreferredDiskOffering().getId(), zoneId);
AsyncCreateResponse job = client.getVolumeClient().createVolumeFromDiskOfferingInZone( assertTrue(jobComplete.apply(job.getJobId()));
prefix+"-jclouds-volume", getPreferredDiskOffering().getId(), zoneId); logger.info("created volume " + job.getId());
assertTrue(jobComplete.apply(job.getJobId())); return findVolumeWithId(job.getId());
logger.info("created volume "+job.getId());
return findVolumeWithId(job.getId());
}
}, null, 60*1000, "failed to create volume");
} }
public void testCreateVolumeFromDiskofferingInZoneAndDeleteVolume() { public void testCreateVolumeFromDiskofferingInZoneAndDeleteVolume() {
@ -178,36 +172,22 @@ public class VolumeClientLiveTest extends BaseCloudStackClientLiveTest {
checkVolume(volume); checkVolume(volume);
final VirtualMachine virtualMachine = getPreferredVirtualMachine(); VirtualMachine virtualMachine = getPreferredVirtualMachine();
logger.info("attaching volume %s to vm %s", volume, virtualMachine);
AsyncCreateResponse job = client.getVolumeClient().attachVolume(volume.getId(), virtualMachine.getId());
assertTrue(jobComplete.apply(job.getJobId()));
Volume attachedVolume = findVolumeWithId(volume.getId());
Volume attachedVolume = Retryables.retryGettingResultOrFailing(new PredicateCallable<Volume>() {
public Volume call() {
logger.info("attaching volume %s to vm %s", volume, virtualMachine);
AsyncCreateResponse job = client.getVolumeClient().attachVolume(volume.getId(), virtualMachine.getId());
assertTrue(jobComplete.apply(job.getJobId()));
return findVolumeWithId(volume.getId());
}
int failures=0;
protected void onFailure() {
logger.info("failed attaching volume (retrying): %s", getLastFailure());
if (failures++==0) logger.warn(getLastFailure(), "first failure attaching volume");
}
}, null, 60*1000, "failed to attach volume");
checkVolume(attachedVolume); checkVolume(attachedVolume);
assertEquals(virtualMachine.getId(), attachedVolume.getVirtualMachineId()); assertEquals(virtualMachine.getId(), attachedVolume.getVirtualMachineId());
assertNotNull(attachedVolume.getAttached()); assertNotNull(attachedVolume.getAttached());
Volume detachedVolume = Retryables.retryGettingResultOrFailing(new PredicateCallable<Volume>() { logger.info("detaching volume %s from vm %s", volume, virtualMachine);
public Volume call() { job = client.getVolumeClient().detachVolume(volume.getId());
logger.info("detaching volume %s from vm %s", volume, virtualMachine); assertTrue(jobComplete.apply(job.getJobId()));
AsyncCreateResponse job = client.getVolumeClient().detachVolume(volume.getId()); Volume detachedVolume = findVolumeWithId(volume.getId());
assertTrue(jobComplete.apply(job.getJobId()));
return findVolumeWithId(volume.getId());
}
protected void onFailure() {
logger.debug("failed detaching volume (retrying): %s", getLastFailure());
}
}, null, 60*1000, "failed to detach volume");
checkVolume(detachedVolume); checkVolume(detachedVolume);
assertNull(detachedVolume.getAttached()); assertNull(detachedVolume.getAttached());
@ -219,17 +199,11 @@ public class VolumeClientLiveTest extends BaseCloudStackClientLiveTest {
public void testCreateVolumeFromSnapshotInZoneAndDeleteVolume() { public void testCreateVolumeFromSnapshotInZoneAndDeleteVolume() {
logger.info("testCreateVolumeFromSnapshotInZoneAndDeleteVolume (takes ~3m)"); logger.info("testCreateVolumeFromSnapshotInZoneAndDeleteVolume (takes ~3m)");
assertNotNull(getPreferredSnapshot()); assertNotNull(getPreferredSnapshot());
Volume volume = Retryables.retryGettingResultOrFailing(new PredicateCallable<Volume>() {
public Volume call() { AsyncCreateResponse job = client.getVolumeClient().createVolumeFromSnapshotInZone(prefix + "-jclouds-volume",
AsyncCreateResponse job = client.getVolumeClient().createVolumeFromSnapshotInZone( getPreferredSnapshot().getId(), zoneId);
prefix+"-jclouds-volume", getPreferredSnapshot().getId(), zoneId); assertTrue(jobComplete.apply(job.getJobId()));
assertTrue(jobComplete.apply(job.getJobId())); Volume volume = findVolumeWithId(job.getId());
return findVolumeWithId(job.getId());
}
protected void onFailure() {
logger.debug("failed creating volume (retrying): %s", getLastFailure());
}
}, null, 60*1000, "failed to create volume");
checkVolume(volume); checkVolume(volume);
client.getVolumeClient().deleteVolume(volume.getId()); client.getVolumeClient().deleteVolume(volume.getId());

View File

@ -20,12 +20,13 @@ package org.jclouds.cloudstack.internal;
import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.get; import static com.google.common.collect.Iterables.get;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Properties; import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jclouds.cloudstack.CloudStackAsyncClient; import org.jclouds.cloudstack.CloudStackAsyncClient;
@ -53,7 +54,6 @@ import org.jclouds.compute.ComputeService;
import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.internal.BaseGenericComputeServiceContextLiveTest; import org.jclouds.compute.internal.BaseGenericComputeServiceContextLiveTest;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.sshj.config.SshjSshClientModule;
@ -156,12 +156,12 @@ public class BaseCloudStackClientLiveTest extends BaseGenericComputeServiceConte
protected User user; protected User user;
protected Predicate<HostAndPort> socketTester; protected Predicate<HostAndPort> socketTester;
protected RetryablePredicate<String> jobComplete; protected Predicate<String> jobComplete;
protected RetryablePredicate<String> adminJobComplete; protected Predicate<String> adminJobComplete;
protected RetryablePredicate<VirtualMachine> virtualMachineRunning; protected Predicate<VirtualMachine> virtualMachineRunning;
protected RetryablePredicate<VirtualMachine> adminVirtualMachineRunning; protected Predicate<VirtualMachine> adminVirtualMachineRunning;
protected RetryablePredicate<VirtualMachine> virtualMachineDestroyed; protected Predicate<VirtualMachine> virtualMachineDestroyed;
protected RetryablePredicate<VirtualMachine> adminVirtualMachineDestroyed; protected Predicate<VirtualMachine> adminVirtualMachineDestroyed;
protected SshClient.Factory sshFactory; protected SshClient.Factory sshFactory;
protected Injector injector; protected Injector injector;
@ -223,23 +223,20 @@ public class BaseCloudStackClientLiveTest extends BaseGenericComputeServiceConte
injector = cloudStackContext.utils().injector(); injector = cloudStackContext.utils().injector();
sshFactory = injector.getInstance(SshClient.Factory.class); sshFactory = injector.getInstance(SshClient.Factory.class);
socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), 180, 1, 1, TimeUnit.SECONDS); socketTester = retry(new InetSocketAddressConnect(), 180, 1, 1, SECONDS);
injector.injectMembers(socketTester); injector.injectMembers(socketTester);
jobComplete = new RetryablePredicate<String>(new JobComplete(client), 1200, 1, 5, TimeUnit.SECONDS);
jobComplete = retry(new JobComplete(client), 1200, 1, 5, SECONDS);
injector.injectMembers(jobComplete); injector.injectMembers(jobComplete);
adminJobComplete = new RetryablePredicate<String>(new JobComplete(adminClient), 1200, 1, 5, TimeUnit.SECONDS); adminJobComplete = retry(new JobComplete(adminClient), 1200, 1, 5, SECONDS);
injector.injectMembers(adminJobComplete); injector.injectMembers(adminJobComplete);
virtualMachineRunning = new RetryablePredicate<VirtualMachine>(new VirtualMachineRunning(client), 600, 5, 5, virtualMachineRunning = retry(new VirtualMachineRunning(client), 600, 5, 5, SECONDS);
TimeUnit.SECONDS);
injector.injectMembers(virtualMachineRunning); injector.injectMembers(virtualMachineRunning);
adminVirtualMachineRunning = new RetryablePredicate<VirtualMachine>(new VirtualMachineRunning(adminClient), 600, adminVirtualMachineRunning = retry(new VirtualMachineRunning(adminClient), 600, 5, 5, SECONDS);
5, 5, TimeUnit.SECONDS);
injector.injectMembers(adminVirtualMachineRunning); injector.injectMembers(adminVirtualMachineRunning);
virtualMachineDestroyed = new RetryablePredicate<VirtualMachine>(new VirtualMachineDestroyed(client), 600, 5, 5, virtualMachineDestroyed = retry(new VirtualMachineDestroyed(client), 600, 5, 5, SECONDS);
TimeUnit.SECONDS);
injector.injectMembers(virtualMachineDestroyed); injector.injectMembers(virtualMachineDestroyed);
adminVirtualMachineDestroyed = new RetryablePredicate<VirtualMachine>(new VirtualMachineDestroyed(adminClient), adminVirtualMachineDestroyed = retry(new VirtualMachineDestroyed(adminClient), 600, 5, 5, SECONDS);
600, 5, 5, TimeUnit.SECONDS);
injector.injectMembers(adminVirtualMachineDestroyed); injector.injectMembers(adminVirtualMachineDestroyed);
reuseOrAssociate = new ReuseOrAssociateNewPublicIPAddress(client, new BlockUntilJobCompletesAndReturnResult( reuseOrAssociate = new ReuseOrAssociateNewPublicIPAddress(client, new BlockUntilJobCompletesAndReturnResult(
client, jobComplete)); client, jobComplete));

View File

@ -18,26 +18,27 @@
*/ */
package org.jclouds.cloudwatch; package org.jclouds.cloudwatch;
import com.google.common.base.Predicate; import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.Iterables; import static java.util.concurrent.TimeUnit.MINUTES;
import com.google.common.collect.Sets; import static org.jclouds.util.Predicates2.retry;
import com.google.common.reflect.TypeToken;
import java.util.Date;
import java.util.Set;
import org.jclouds.apis.BaseContextLiveTest; import org.jclouds.apis.BaseContextLiveTest;
import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.Dimension;
import org.jclouds.cloudwatch.domain.MetricDatum; import org.jclouds.cloudwatch.domain.MetricDatum;
import org.jclouds.cloudwatch.domain.Unit; import org.jclouds.cloudwatch.domain.Unit;
import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.jclouds.cloudwatch.options.ListMetricsOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.util.Date; import com.google.common.base.Predicate;
import java.util.Set; import com.google.common.collect.Iterables;
import java.util.concurrent.TimeUnit; import com.google.common.collect.Sets;
import com.google.common.reflect.TypeToken;
import static com.google.common.base.Preconditions.checkArgument;
/** /**
* Tests behavior of {@code CloudWatch}. * Tests behavior of {@code CloudWatch}.
@ -91,12 +92,11 @@ public class CloudWatchLiveTest extends BaseContextLiveTest<RestContext<CloudWat
ListMetricsOptions lmo = ListMetricsOptions.Builder.namespace(namespace) ListMetricsOptions lmo = ListMetricsOptions.Builder.namespace(namespace)
.dimension(new Dimension("BaseMetricName", metricName)); .dimension(new Dimension("BaseMetricName", metricName));
boolean success = new RetryablePredicate<ListMetricsOptions>(new Predicate<ListMetricsOptions>() { boolean success = retry(new Predicate<ListMetricsOptions>() {
@Override
public boolean apply(ListMetricsOptions options) { public boolean apply(ListMetricsOptions options) {
return Iterables.size(CloudWatch.listMetrics(api, null, options)) == 11; return Iterables.size(CloudWatch.listMetrics(api, null, options)) == 11;
} }
}, 20, 1, TimeUnit.MINUTES).apply(lmo); }, 20, 1, MINUTES).apply(lmo);
if (!success) { if (!success) {
Assert.fail("Unable to gather the created CloudWatch data within the time (20m) allotted."); Assert.fail("Unable to gather the created CloudWatch data within the time (20m) allotted.");

View File

@ -20,11 +20,12 @@ package org.jclouds.cloudwatch.features;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.jclouds.util.Predicates2.retry;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.cloudwatch.domain.Datapoint; import org.jclouds.cloudwatch.domain.Datapoint;
import org.jclouds.cloudwatch.domain.Dimension; import org.jclouds.cloudwatch.domain.Dimension;
@ -40,7 +41,6 @@ import org.jclouds.cloudwatch.domain.Unit;
import org.jclouds.cloudwatch.internal.BaseCloudWatchApiLiveTest; import org.jclouds.cloudwatch.internal.BaseCloudWatchApiLiveTest;
import org.jclouds.cloudwatch.options.ListMetricsOptions; import org.jclouds.cloudwatch.options.ListMetricsOptions;
import org.jclouds.collect.IterableWithMarker; import org.jclouds.collect.IterableWithMarker;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -88,12 +88,11 @@ public class MetricApiLiveTest extends BaseCloudWatchApiLiveTest {
ListMetricsOptions lmo = ListMetricsOptions.Builder.namespace(namespace) ListMetricsOptions lmo = ListMetricsOptions.Builder.namespace(namespace)
.dimension(new Dimension("BaseMetricName", metricName)); .dimension(new Dimension("BaseMetricName", metricName));
boolean success = new RetryablePredicate<ListMetricsOptions>(new Predicate<ListMetricsOptions>() { boolean success = retry(new Predicate<ListMetricsOptions>() {
@Override
public boolean apply(ListMetricsOptions options) { public boolean apply(ListMetricsOptions options) {
return Iterables.size(api().list(options)) == 2; return Iterables.size(api().list(options)) == 2;
} }
}, 20, 1, TimeUnit.MINUTES).apply(lmo); }, 20, 1, MINUTES).apply(lmo);
if (!success) { if (!success) {
Assert.fail("Unable to gather the created CloudWatch data within the time (20m) allotted."); Assert.fail("Unable to gather the created CloudWatch data within the time (20m) allotted.");

View File

@ -22,6 +22,8 @@ import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Iterables.transform;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER; import static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;
@ -30,6 +32,7 @@ import static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTa
import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsValuesOfEmptyString; import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsValuesOfEmptyString;
import static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_GENERATE_INSTANCE_NAMES; import static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_GENERATE_INSTANCE_NAMES;
import static org.jclouds.ec2.util.Tags.resourceToTagsAsMap; import static org.jclouds.ec2.util.Tags.resourceToTagsAsMap;
import static org.jclouds.util.Predicates2.retry;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@ -79,7 +82,6 @@ import org.jclouds.ec2.domain.KeyPair;
import org.jclouds.ec2.domain.RunningInstance; import org.jclouds.ec2.domain.RunningInstance;
import org.jclouds.ec2.domain.Tag; import org.jclouds.ec2.domain.Tag;
import org.jclouds.ec2.util.TagFilterBuilder; import org.jclouds.ec2.util.TagFilterBuilder;
import org.jclouds.predicates.Retryables;
import org.jclouds.scriptbuilder.functions.InitAdminAccess; import org.jclouds.scriptbuilder.functions.InitAdminAccess;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
@ -293,22 +295,21 @@ public class EC2ComputeService extends BaseComputeService {
// Also in #445, in aws-ec2 the deleteSecurityGroup sometimes fails after terminating the final VM using a // Also in #445, in aws-ec2 the deleteSecurityGroup sometimes fails after terminating the final VM using a
// given security group, if called very soon after the VM's state reports terminated. Empirically, it seems that // given security group, if called very soon after the VM's state reports terminated. Empirically, it seems that
// waiting a small time (e.g. enabling logging or debugging!) then the tests pass. We therefore retry. // waiting a small time (e.g. enabling logging or debugging!) then the tests pass. We therefore retry.
final int maxAttempts = 3; // TODO: this could be moved to a config module, also the narrative above made more concise
Retryables.retryNumTimes(new Predicate<Void>() { retry(new Predicate<RegionAndName>() {
@Override public boolean apply(RegionAndName input) {
public boolean apply(Void input) { try {
try { logger.debug(">> deleting incidentalResources(%s)", input);
logger.debug(">> deleting incidentalResources(%s @ %s)", region, group); deleteSecurityGroup(input.getRegion(), input.getName());
deleteSecurityGroup(region, group); deleteKeyPair(input.getRegion(), input.getName()); // not executed if securityGroup was in use
deleteKeyPair(region, group); // not executed if securityGroup was in use logger.debug("<< deleted incidentalResources(%s)", input);
logger.debug("<< deleted incidentalResources(%s @ %s)", region, group); return true;
return true; } catch (IllegalStateException e) {
} catch (IllegalStateException e) { logger.debug("<< inUse incidentalResources(%s @ %s)", input);
logger.debug("<< inUse incidentalResources(%s @ %s)", region, group); return false;
return false;
}
} }
}, (Void)null, maxAttempts); }
}, SECONDS.toMillis(3), 50, 1000, MILLISECONDS).apply(new RegionAndName(region, group));
} }
/** /**

View File

@ -17,12 +17,12 @@
* under the License. * under the License.
*/ */
package org.jclouds.ec2.compute.config; package org.jclouds.ec2.compute.config;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT; import static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT;
import static org.jclouds.util.Predicates2.retry;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -51,15 +51,12 @@ import org.jclouds.ec2.compute.loaders.CreateSecurityGroupIfNeeded;
import org.jclouds.ec2.compute.loaders.LoadPublicIpForInstanceOrNull; import org.jclouds.ec2.compute.loaders.LoadPublicIpForInstanceOrNull;
import org.jclouds.ec2.compute.loaders.RegionAndIdToImage; import org.jclouds.ec2.compute.loaders.RegionAndIdToImage;
import org.jclouds.ec2.compute.options.EC2TemplateOptions; import org.jclouds.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.ec2.compute.predicates.GetImageWhenStatusAvailablePredicateWithResult;
import org.jclouds.ec2.compute.predicates.SecurityGroupPresent; import org.jclouds.ec2.compute.predicates.SecurityGroupPresent;
import org.jclouds.ec2.domain.Image.ImageState; import org.jclouds.ec2.domain.Image.ImageState;
import org.jclouds.ec2.domain.InstanceState; import org.jclouds.ec2.domain.InstanceState;
import org.jclouds.ec2.domain.KeyPair; import org.jclouds.ec2.domain.KeyPair;
import org.jclouds.ec2.domain.RunningInstance; import org.jclouds.ec2.domain.RunningInstance;
import org.jclouds.ec2.reference.EC2Constants; import org.jclouds.ec2.reference.EC2Constants;
import org.jclouds.predicates.PredicateWithResult;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -136,8 +133,6 @@ public class EC2ComputeServiceDependenciesModule extends AbstractModule {
}).to(EC2ImageParser.class); }).to(EC2ImageParser.class);
bind(new TypeLiteral<ImageExtension>() { bind(new TypeLiteral<ImageExtension>() {
}).to(EC2ImageExtension.class); }).to(EC2ImageExtension.class);
bind(new TypeLiteral<PredicateWithResult<String, Image>>() {
}).to(GetImageWhenStatusAvailablePredicateWithResult.class);
} }
/** /**
@ -185,8 +180,8 @@ public class EC2ComputeServiceDependenciesModule extends AbstractModule {
@Singleton @Singleton
@Named("SECURITY") @Named("SECURITY")
protected Predicate<RegionAndName> securityGroupEventualConsistencyDelay(SecurityGroupPresent in, protected Predicate<RegionAndName> securityGroupEventualConsistencyDelay(SecurityGroupPresent in,
@Named(PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT) long msDelay) { @Named(PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT) long msDelay) {
return new RetryablePredicate<RegionAndName>(in, msDelay, 100l, TimeUnit.MILLISECONDS); return retry(in, msDelay, 100l, MILLISECONDS);
} }
} }

View File

@ -21,10 +21,15 @@ package org.jclouds.ec2.compute.extensions;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.getOnlyElement;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;
import static org.jclouds.location.predicates.LocationPredicates.idEquals;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
@ -32,23 +37,27 @@ import javax.inject.Named;
import org.jclouds.Constants; import org.jclouds.Constants;
import org.jclouds.aws.util.AWSUtils; import org.jclouds.aws.util.AWSUtils;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.CloneImageTemplate; import org.jclouds.compute.domain.CloneImageTemplate;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.ImageTemplate; import org.jclouds.compute.domain.ImageTemplate;
import org.jclouds.compute.domain.ImageTemplateBuilder; import org.jclouds.compute.domain.ImageTemplateBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.ec2.EC2Client; import org.jclouds.ec2.EC2Client;
import org.jclouds.ec2.domain.Reservation; import org.jclouds.ec2.domain.Reservation;
import org.jclouds.ec2.domain.RunningInstance; import org.jclouds.ec2.domain.RunningInstance;
import org.jclouds.ec2.options.CreateImageOptions; import org.jclouds.ec2.options.CreateImageOptions;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.PredicateWithResult;
import org.jclouds.predicates.Retryables;
import com.google.common.collect.Iterables; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.UncheckedTimeoutException;
/** /**
* EC2 implementation of {@link ImageExtension} please note that {@link #createImage(ImageTemplate)} * EC2 implementation of {@link ImageExtension} please note that {@link #createImage(ImageTemplate)}
@ -64,20 +73,17 @@ public class EC2ImageExtension implements ImageExtension {
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final EC2Client ec2Client; private final EC2Client ec2Client;
private final ListeningExecutorService userExecutor; private final ListeningExecutorService userExecutor;
private final PredicateWithResult<String, Image> imageReadyPredicate; private final Supplier<Set<? extends Location>> locations;
@com.google.inject.Inject(optional = true) private final Predicate<AtomicReference<Image>> imageAvailablePredicate;
@Named("IMAGE_MAX_WAIT")
private long maxWait = 3600;
@com.google.inject.Inject(optional = true)
@Named("IMAGE_WAIT_PERIOD")
private long waitPeriod = 1;
@Inject @Inject
public EC2ImageExtension(EC2Client ec2Client, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, public EC2ImageExtension(EC2Client ec2Client, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
PredicateWithResult<String, Image> imageReadyPredicate) { @Memoized Supplier<Set<? extends Location>> locations,
this.ec2Client = checkNotNull(ec2Client); @Named(TIMEOUT_IMAGE_AVAILABLE) Predicate<AtomicReference<Image>> imageAvailablePredicate) {
this.userExecutor = checkNotNull(userExecutor); this.ec2Client = checkNotNull(ec2Client, "ec2Client");
this.imageReadyPredicate = imageReadyPredicate; this.userExecutor = checkNotNull(userExecutor, "userExecutor");
this.locations = checkNotNull(locations, "locations");
this.imageAvailablePredicate = checkNotNull(imageAvailablePredicate, "imageAvailablePredicate");
} }
@Override @Override
@ -85,8 +91,8 @@ public class EC2ImageExtension implements ImageExtension {
String[] parts = AWSUtils.parseHandle(id); String[] parts = AWSUtils.parseHandle(id);
String region = parts[0]; String region = parts[0];
String instanceId = parts[1]; String instanceId = parts[1];
Reservation<? extends RunningInstance> instance = Iterables.getOnlyElement(ec2Client.getInstanceServices() Reservation<? extends RunningInstance> instance = getOnlyElement(ec2Client.getInstanceServices()
.describeInstancesInRegion(region, instanceId)); .describeInstancesInRegion(region, instanceId));
if (instance == null) if (instance == null)
throw new NoSuchElementException("Cannot find server with id: " + id); throw new NoSuchElementException("Cannot find server with id: " + id);
CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build();
@ -98,18 +104,27 @@ public class EC2ImageExtension implements ImageExtension {
checkState(template instanceof CloneImageTemplate, " ec2 only supports creating images through cloning."); checkState(template instanceof CloneImageTemplate, " ec2 only supports creating images through cloning.");
CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; CloneImageTemplate cloneTemplate = (CloneImageTemplate) template;
String[] parts = AWSUtils.parseHandle(cloneTemplate.getSourceNodeId()); String[] parts = AWSUtils.parseHandle(cloneTemplate.getSourceNodeId());
final String region = parts[0]; String region = parts[0];
String instanceId = parts[1]; String instanceId = parts[1];
final String imageId = ec2Client.getAMIServices().createImageInRegion(region, cloneTemplate.getName(), String imageId = ec2Client.getAMIServices().createImageInRegion(region, cloneTemplate.getName(), instanceId,
instanceId, CreateImageOptions.NONE); CreateImageOptions.NONE);
final AtomicReference<Image> image = new AtomicReference<Image>(new ImageBuilder()
.location(find(locations.get(), idEquals(region)))
.id(region + "/" + imageId)
.providerId(imageId)
.description(cloneTemplate.getName())
.operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build())
.status(Image.Status.PENDING).build());
return userExecutor.submit(new Callable<Image>() { return userExecutor.submit(new Callable<Image>() {
@Override @Override
public Image call() throws Exception { public Image call() throws Exception {
return Retryables.retryGettingResultOrFailing(imageReadyPredicate, region + "/" + imageId, maxWait, if (imageAvailablePredicate.apply(image))
waitPeriod, TimeUnit.SECONDS, "Image was not created within the time limit, Giving up! [Limit: " return image.get();
+ maxWait + " secs.]"); // TODO: get rid of the expectation that the image will be available, as it is very brittle
throw new UncheckedTimeoutException("Image was not created within the time limit: " + image.get());
} }
}); });
} }

View File

@ -20,9 +20,10 @@ package org.jclouds.ec2.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -41,7 +42,6 @@ import org.jclouds.ec2.domain.RunningInstance;
import org.jclouds.ec2.features.WindowsApi; import org.jclouds.ec2.features.WindowsApi;
import org.jclouds.javax.annotation.Nullable; import org.jclouds.javax.annotation.Nullable;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -103,8 +103,8 @@ public class PasswordCredentialsFromWindowsInstance implements Function<RunningI
}; };
// TODO: parameterize // TODO: parameterize
RetryablePredicate<String> passwordReadyRetryable = new RetryablePredicate<String>(passwordReady, 600, 10, Predicate<String> passwordReadyRetryable = retry(passwordReady, 600, 10, SECONDS);
TimeUnit.SECONDS);
logger.debug(">> awaiting password data for instance(%s/%s)", instance.getRegion(), instance.getId()); logger.debug(">> awaiting password data for instance(%s/%s)", instance.getRegion(), instance.getId());
if (passwordReadyRetryable.apply(instance.getId())) { if (passwordReadyRetryable.apply(instance.getId())) {
credentials = pwDataToLoginCredentials.apply(new PasswordDataAndPrivateKey(data.get(), privateKey)); credentials = pwDataToLoginCredentials.apply(new PasswordDataAndPrivateKey(data.get(), privateKey));

View File

@ -1,94 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.ec2.compute.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import org.jclouds.aws.util.AWSUtils;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.ec2.EC2Client;
import org.jclouds.ec2.compute.functions.EC2ImageParser;
import org.jclouds.ec2.options.DescribeImagesOptions;
import org.jclouds.logging.Logger;
import org.jclouds.predicates.PredicateWithResult;
import com.google.common.collect.Iterables;
/**
* §
* @author David Alves
*
*/
public final class GetImageWhenStatusAvailablePredicateWithResult implements PredicateWithResult<String, Image> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final EC2Client ec2Client;
private final EC2ImageParser ec2ImageToImage;
private org.jclouds.ec2.domain.Image result;
private RuntimeException lastFailure;
@Inject
public GetImageWhenStatusAvailablePredicateWithResult(EC2Client ec2Client, EC2ImageParser ec2ImageToImage) {
this.ec2Client = ec2Client;
this.ec2ImageToImage = ec2ImageToImage;
}
@Override
public boolean apply(String input) {
String[] parts = AWSUtils.parseHandle(input);
String region = parts[0];
String imageId = parts[1];
result = checkNotNull(findImage(imageId, region));
switch (result.getImageState()) {
case AVAILABLE:
logger.info("<< Image %s is available for use.", input);
return true;
case UNRECOGNIZED:
logger.debug("<< Image %s is not available yet.", input);
return false;
default:
lastFailure = new IllegalStateException("Image was not created: " + input);
throw lastFailure;
}
}
@Override
public Image getResult() {
return ec2ImageToImage.apply(result);
}
@Override
public Throwable getLastFailure() {
return lastFailure;
}
private org.jclouds.ec2.domain.Image findImage(String id, String region) {
return Iterables.getOnlyElement(ec2Client.getAMIServices().describeImagesInRegion(region,
new DescribeImagesOptions().imageIds(id)));
}
}

View File

@ -18,10 +18,11 @@
*/ */
package org.jclouds.ec2; package org.jclouds.ec2;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.ec2.options.RunInstancesOptions.Builder.asType; import static org.jclouds.ec2.options.RunInstancesOptions.Builder.asType;
import static org.jclouds.util.Predicates2.retry;
import static org.jclouds.scriptbuilder.domain.Statements.exec; import static org.jclouds.scriptbuilder.domain.Statements.exec;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail; import static org.testng.Assert.fail;
@ -31,7 +32,6 @@ import java.net.UnknownHostException;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import org.jclouds.aws.AWSResponseException; import org.jclouds.aws.AWSResponseException;
@ -51,7 +51,6 @@ import org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;
import org.jclouds.ec2.predicates.InstanceHasIpAddress; import org.jclouds.ec2.predicates.InstanceHasIpAddress;
import org.jclouds.ec2.predicates.InstanceStateRunning; import org.jclouds.ec2.predicates.InstanceStateRunning;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.jclouds.scriptbuilder.ScriptBuilder; import org.jclouds.scriptbuilder.ScriptBuilder;
import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.OsFamily;
@ -61,6 +60,7 @@ import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
@ -90,9 +90,9 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest extends BaseComputeS
private String instanceId; private String instanceId;
private String address; private String address;
private RetryablePredicate<HostAndPort> socketTester; private Predicate<HostAndPort> socketTester;
private RetryablePredicate<RunningInstance> hasIpTester; private Predicate<RunningInstance> hasIpTester;
private RetryablePredicate<RunningInstance> runningTester; private Predicate<RunningInstance> runningTester;
@BeforeClass(groups = { "integration", "live" }) @BeforeClass(groups = { "integration", "live" })
public void setupContext() { public void setupContext() {
@ -100,11 +100,10 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest extends BaseComputeS
Injector injector = view.utils().injector(); Injector injector = view.utils().injector();
client = injector.getInstance(EC2Client.class); client = injector.getInstance(EC2Client.class);
sshFactory = injector.getInstance(SshClient.Factory.class); sshFactory = injector.getInstance(SshClient.Factory.class);
runningTester = new RetryablePredicate<RunningInstance>(new InstanceStateRunning(client), 180, 5, runningTester = retry(new InstanceStateRunning(client), 180, 5,SECONDS);
TimeUnit.SECONDS); hasIpTester = retry(new InstanceHasIpAddress(client), 180, 5, SECONDS);
hasIpTester = new RetryablePredicate<RunningInstance>(new InstanceHasIpAddress(client), 180, 5, TimeUnit.SECONDS);
SocketOpen socketOpen = injector.getInstance(SocketOpen.class); SocketOpen socketOpen = injector.getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<HostAndPort>(socketOpen, 180, 1, TimeUnit.SECONDS); socketTester = retry(socketOpen, 180, 1, SECONDS);
} }
@Test(enabled = false) @Test(enabled = false)

View File

@ -18,10 +18,12 @@
*/ */
package org.jclouds.ec2; package org.jclouds.ec2;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.ec2.options.CreateSnapshotOptions.Builder.withDescription; import static org.jclouds.ec2.options.CreateSnapshotOptions.Builder.withDescription;
import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds; import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds;
import static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.withKernelId; import static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.withKernelId;
import static org.jclouds.ec2.options.RunInstancesOptions.Builder.withKeyName; import static org.jclouds.ec2.options.RunInstancesOptions.Builder.withKeyName;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
@ -29,7 +31,6 @@ import java.net.UnknownHostException;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import org.jclouds.aws.AWSResponseException; import org.jclouds.aws.AWSResponseException;
@ -59,7 +60,6 @@ import org.jclouds.ec2.predicates.VolumeAttached;
import org.jclouds.ec2.predicates.VolumeAvailable; import org.jclouds.ec2.predicates.VolumeAvailable;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.jclouds.scriptbuilder.InitScript; import org.jclouds.scriptbuilder.InitScript;
import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.OsFamily;
@ -107,15 +107,15 @@ public class EBSBootEC2ClientLiveTest extends BaseComputeServiceContextLiveTest
private KeyPair keyPair; private KeyPair keyPair;
private String securityGroupName; private String securityGroupName;
private RetryablePredicate<HostAndPort> socketTester; private Predicate<HostAndPort> socketTester;
private RetryablePredicate<Attachment> attachTester; private Predicate<Attachment> attachTester;
private RetryablePredicate<Volume> volumeTester; private Predicate<Volume> volumeTester;
private RunningInstance instance; private RunningInstance instance;
private RetryablePredicate<RunningInstance> runningTester; private Predicate<RunningInstance> runningTester;
private RetryablePredicate<RunningInstance> stoppedTester; private Predicate<RunningInstance> stoppedTester;
private RetryablePredicate<RunningInstance> terminatedTester; private Predicate<RunningInstance> terminatedTester;
private Volume volume; private Volume volume;
private RetryablePredicate<Snapshot> snapshotTester; private Predicate<Snapshot> snapshotTester;
private Snapshot snapshot; private Snapshot snapshot;
private Image ebsImage; private Image ebsImage;
private RunningInstance ebsInstance; private RunningInstance ebsInstance;
@ -130,25 +130,24 @@ public class EBSBootEC2ClientLiveTest extends BaseComputeServiceContextLiveTest
client = injector.getInstance(EC2Client.class); client = injector.getInstance(EC2Client.class);
sshFactory = injector.getInstance(SshClient.Factory.class); sshFactory = injector.getInstance(SshClient.Factory.class);
SocketOpen socketOpen = injector.getInstance(SocketOpen.class); SocketOpen socketOpen = injector.getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<HostAndPort>(socketOpen, 120, 1, TimeUnit.SECONDS); socketTester = retry(socketOpen, 120, 1, SECONDS);
VolumeAvailable volumeAvailable = injector.getInstance(VolumeAvailable.class); VolumeAvailable volumeAvailable = injector.getInstance(VolumeAvailable.class);
volumeTester = new RetryablePredicate<Volume>(volumeAvailable, 60, 1, TimeUnit.SECONDS); volumeTester = retry(volumeAvailable, 60, 1, SECONDS);
SnapshotCompleted snapshotCompleted = injector.getInstance(SnapshotCompleted.class); SnapshotCompleted snapshotCompleted = injector.getInstance(SnapshotCompleted.class);
snapshotTester = new RetryablePredicate<Snapshot>(snapshotCompleted, 120, 3, TimeUnit.SECONDS); snapshotTester = retry(snapshotCompleted, 120, 3, SECONDS);
VolumeAttached volumeAttached = injector.getInstance(VolumeAttached.class); VolumeAttached volumeAttached = injector.getInstance(VolumeAttached.class);
attachTester = new RetryablePredicate<Attachment>(volumeAttached, 60, 1, TimeUnit.SECONDS); attachTester = retry(volumeAttached, 60, 1, SECONDS);
runningTester = new RetryablePredicate<RunningInstance>(new InstanceStateRunning(client), 180, 5, runningTester = retry(new InstanceStateRunning(client), 180, 5, SECONDS);
TimeUnit.SECONDS);
InstanceStateStopped instanceStateStopped = injector.getInstance(InstanceStateStopped.class); InstanceStateStopped instanceStateStopped = injector.getInstance(InstanceStateStopped.class);
stoppedTester = new RetryablePredicate<RunningInstance>(instanceStateStopped, 60, 1, TimeUnit.SECONDS); stoppedTester = retry(instanceStateStopped, 60, 1, SECONDS);
InstanceStateTerminated instanceStateTerminated = injector.getInstance(InstanceStateTerminated.class); InstanceStateTerminated instanceStateTerminated = injector.getInstance(InstanceStateTerminated.class);
terminatedTester = new RetryablePredicate<RunningInstance>(instanceStateTerminated, 60, 1, TimeUnit.SECONDS); terminatedTester = retry(instanceStateTerminated, 60, 1, SECONDS);
injector.injectMembers(socketOpen); // add logger injector.injectMembers(socketOpen); // add logger
} }
@ -297,9 +296,7 @@ public class EBSBootEC2ClientLiveTest extends BaseComputeServiceContextLiveTest
output = ssh.exec(script + " status"); output = ssh.exec(script + " status");
assert !output.getOutput().trim().equals("") : output; assert !output.getOutput().trim().equals("") : output;
Predicate<String> scriptTester = retry(new ScriptTester(ssh, SCRIPT_END), 600, 10, SECONDS);
RetryablePredicate<String> scriptTester = new RetryablePredicate<String>(new ScriptTester(ssh, SCRIPT_END),
600, 10, TimeUnit.SECONDS);
scriptTester.apply(script); scriptTester.apply(script);
} finally { } finally {
if (ssh != null) if (ssh != null)

View File

@ -0,0 +1,87 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.ec2.compute.extensions;
import static org.testng.Assert.assertEquals;
import javax.ws.rs.core.MediaType;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageTemplate;
import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.ec2.compute.internal.BaseEC2ComputeServiceExpectTest;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Futures;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "EC2ImageExtensionExpectTest")
public class EC2ImageExtensionExpectTest extends BaseEC2ComputeServiceExpectTest {
public void testCreateImage() {
Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();
requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);
requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);
requestResponseMap.put(describeImagesRequest, describeImagesResponse);
requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);
requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);
requestResponseMap.put(describeSecurityGroupRequest, describeSecurityGroupResponse);
requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);
requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);
requestResponseMap.put(describeInstanceRequest, describeInstanceResponse);
HttpRequest createImageRequest = formSigner.filter(HttpRequest.builder().method("POST")
.endpoint("https://ec2." + region + ".amazonaws.com/")
.addHeader("Host", "ec2." + region + ".amazonaws.com")
.addFormParam("Action", "CreateImage")
.addFormParam("InstanceId", "i-2baa5550")
.addFormParam("Name", "test").build());
HttpResponse createImageResponse = HttpResponse.builder()
.statusCode(200)
.payload(payloadFromStringWithContentType(
"<CreateImageResponse><imageId>ami-be3adfd7</imageId></CreateImageResponse>", MediaType.APPLICATION_XML)).build();
requestResponseMap.put(createImageRequest, createImageResponse);
HttpRequest describeImageRequest = formSigner.filter(HttpRequest.builder().method("POST")
.endpoint("https://ec2." + region + ".amazonaws.com/")
.addHeader("Host", "ec2." + region + ".amazonaws.com")
.addFormParam("Action", "DescribeImages")
.addFormParam("ImageId.1", "ami-be3adfd7").build());
requestResponseMap.put(describeImageRequest, describeImagesResponse);
ImageExtension apiThatCreatesImage = requestsSendResponses(requestResponseMap.build()).getImageExtension().get();
ImageTemplate newImageTemplate = apiThatCreatesImage.buildImageTemplateFromNode("test", "us-east-1/i-2baa5550");
Image image = Futures.getUnchecked(apiThatCreatesImage.createImage(newImageTemplate));
assertEquals(image.getId(), "us-east-1/ami-be3adfd7");
}
}

View File

@ -1,120 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.ec2.compute.predicates;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Image;
import org.jclouds.ec2.compute.internal.BaseEC2ComputeServiceContextExpectTest;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.predicates.PredicateWithResult;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
/**
*
* @author David Alves
*/
@Test(groups = "unit", testName = "GetImageWhenStatusAvailablePredicateWithResultExpectTest")
public class GetImageWhenStatusAvailablePredicateWithResultExpectTest extends BaseEC2ComputeServiceContextExpectTest<Injector> {
protected HttpRequest describeRegionsRequest = HttpRequest.builder()
.method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.payload(payloadFromStringWithContentType(
"Action=DescribeRegions&Signature=s5OXKqaaeKhJW5FVrRntuMsUL4Ed5fjzgUWeukU96ko%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2010-06-15&AWSAccessKeyId=identity",
"application/x-www-form-urlencoded")).build();
protected HttpRequest describeImagesRequest0 = HttpRequest.builder()
.method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.payload(payloadFromStringWithContentType(
"Action=DescribeImages&ImageId.1=ami-0&Signature=k9douTXFWkAZecPiZfBLUm3LIS3bTLanMV/%2BWrB1jFA%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2010-06-15&AWSAccessKeyId=identity",
"application/x-www-form-urlencoded")).build();
protected HttpRequest describeImagesRequest1 = HttpRequest.builder()
.method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.payload(payloadFromStringWithContentType(
"Action=DescribeImages&ImageId.1=ami-1&Signature=IVunQEvp8vTKTIxXex2Uh5SWQY1PJCx0ExUe9FRujBY%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2010-06-15&AWSAccessKeyId=identity",
"application/x-www-form-urlencoded")).build();
protected HttpRequest describeImagesRequest2 = HttpRequest.builder()
.method("POST")
.endpoint("https://ec2.us-east-1.amazonaws.com/")
.addHeader("Host", "ec2.us-east-1.amazonaws.com")
.payload(payloadFromStringWithContentType(
"Action=DescribeImages&ImageId.1=ami-2&Signature=8TfP8BJlg1hiY6EqUbS73A7PQO7dlpqnRMyi7hPu76U%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2010-06-15&AWSAccessKeyId=identity",
"application/x-www-form-urlencoded")).build();
protected HttpResponse describeRegionsResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/regionEndpoints.xml", MediaType.APPLICATION_XML)).build();
protected HttpResponse describeImagesResponse0 = HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/describe_images_imageextension0.xml",
MediaType.APPLICATION_XML)).build();
protected HttpResponse describeImagesResponse1 = HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/describe_images_imageextension1.xml",
MediaType.APPLICATION_XML)).build();
protected HttpResponse describeImagesResponse2 = HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/describe_images_imageextension2.xml",
MediaType.APPLICATION_XML)).build();
private final Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()
.put(describeRegionsRequest, describeRegionsResponse).put(describeImagesRequest0, describeImagesResponse0)
.put(describeImagesRequest1, describeImagesResponse1).put(describeImagesRequest2, describeImagesResponse2)
.build();
public void testReturnsFalseOnQueuedAndSavingAndTrueOnActive() {
Injector injector = requestsSendResponses(requestResponseMap);
PredicateWithResult<String, Image> predicate = injector
.getInstance(GetImageWhenStatusAvailablePredicateWithResult.class);
assertTrue(predicate.apply("us-east-1/ami-0"));
assertFalse(predicate.apply("us-east-1/ami-2"));
}
@Test(groups = "unit", testName = "GetImageWhenStatusAvailablePredicateWithResultExpectTest", expectedExceptions = IllegalStateException.class)
public void testFailsOnOtherStatuses() {
Injector injector = requestsSendResponses(requestResponseMap);
PredicateWithResult<String, Image> predicate = injector
.getInstance(GetImageWhenStatusAvailablePredicateWithResult.class);
predicate.apply("us-east-1/ami-1");
}
@Override
public Injector apply(ComputeServiceContext input) {
return input.utils().injector();
}
}

View File

@ -19,18 +19,18 @@
package org.jclouds.ec2.features.internal; package org.jclouds.ec2.features.internal;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jclouds.ec2.domain.Tag; import org.jclouds.ec2.domain.Tag;
import org.jclouds.ec2.features.TagApi; import org.jclouds.ec2.features.TagApi;
import org.jclouds.ec2.internal.BaseEC2ApiLiveTest; import org.jclouds.ec2.internal.BaseEC2ApiLiveTest;
import org.jclouds.ec2.util.TagFilterBuilder; import org.jclouds.ec2.util.TagFilterBuilder;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.SkipException; import org.testng.SkipException;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -85,9 +85,7 @@ public abstract class BaseTagApiLiveTest extends BaseEC2ApiLiveTest {
@Test(dependsOnMethods = { "testApplyTag", "testApplyTagWithValue" }) @Test(dependsOnMethods = { "testApplyTag", "testApplyTagWithValue" })
protected void testList() { protected void testList() {
assertTrue(new RetryablePredicate<Iterable<Tag>>(new Predicate<Iterable<Tag>>() { assertTrue(retry(new Predicate<Iterable<Tag>>() {
@Override
public boolean apply(Iterable<Tag> input) { public boolean apply(Iterable<Tag> input) {
return api().list().filter(new Predicate<Tag>() { return api().list().filter(new Predicate<Tag>() {
@Override @Override
@ -96,8 +94,7 @@ public abstract class BaseTagApiLiveTest extends BaseEC2ApiLiveTest {
} }
}).toSet().equals(input); }).toSet().equals(input);
} }
}, 600, 200, 200, MILLISECONDS).apply(ImmutableSet.of(tag, tag2)));
}, 600, 200, 200, TimeUnit.MILLISECONDS).apply(ImmutableSet.of(tag, tag2)));
} }
@Test(dependsOnMethods = "testList") @Test(dependsOnMethods = "testList")

View File

@ -22,8 +22,10 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newHashSet;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds; import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds;
import static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.addNewBlockDevice; import static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.addNewBlockDevice;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -31,7 +33,6 @@ import static org.testng.Assert.assertTrue;
import java.util.Iterator; import java.util.Iterator;
import java.util.Properties; import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.compute.RunNodesException; import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
@ -46,11 +47,11 @@ import org.jclouds.ec2.domain.RootDeviceType;
import org.jclouds.ec2.domain.RunningInstance; import org.jclouds.ec2.domain.RunningInstance;
import org.jclouds.ec2.domain.Snapshot; import org.jclouds.ec2.domain.Snapshot;
import org.jclouds.ec2.predicates.InstanceStateRunning; import org.jclouds.ec2.predicates.InstanceStateRunning;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
/** /**
@ -78,7 +79,7 @@ public class AMIClientLiveTest extends BaseComputeServiceContextLiveTest {
protected EC2Client ec2Client; protected EC2Client ec2Client;
protected AMIClient client; protected AMIClient client;
protected RetryablePredicate<RunningInstance> runningTester; protected Predicate<RunningInstance> runningTester;
protected Set<String> imagesToDeregister = newHashSet(); protected Set<String> imagesToDeregister = newHashSet();
protected Set<String> snapshotsToDelete = newHashSet(); protected Set<String> snapshotsToDelete = newHashSet();
@ -92,8 +93,7 @@ public class AMIClientLiveTest extends BaseComputeServiceContextLiveTest {
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
ec2Client = view.unwrap(EC2ApiMetadata.CONTEXT_TOKEN).getApi(); ec2Client = view.unwrap(EC2ApiMetadata.CONTEXT_TOKEN).getApi();
runningTester = new RetryablePredicate<RunningInstance>(new InstanceStateRunning(ec2Client), 600, 5, runningTester = retry(new InstanceStateRunning(ec2Client), 600, 5, SECONDS);
TimeUnit.SECONDS);
client = ec2Client.getAMIServices(); client = ec2Client.getAMIServices();
if (ebsTemplate != null) { if (ebsTemplate != null) {

View File

@ -17,15 +17,15 @@
* under the License. * under the License.
*/ */
package org.jclouds.ec2.services; package org.jclouds.ec2.services;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.snapshotIds; import static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.snapshotIds;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import java.util.Set; import java.util.Set;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.concurrent.TimeUnit;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.ec2.EC2ApiMetadata; import org.jclouds.ec2.EC2ApiMetadata;
@ -35,7 +35,6 @@ import org.jclouds.ec2.domain.Snapshot;
import org.jclouds.ec2.domain.Volume; import org.jclouds.ec2.domain.Volume;
import org.jclouds.ec2.predicates.SnapshotCompleted; import org.jclouds.ec2.predicates.SnapshotCompleted;
import org.jclouds.ec2.predicates.VolumeAvailable; import org.jclouds.ec2.predicates.VolumeAvailable;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -109,8 +108,7 @@ public class ElasticBlockStoreClientLiveTest extends BaseComputeServiceContextLi
@Test(dependsOnMethods = "testCreateVolumeInAvailabilityZone") @Test(dependsOnMethods = "testCreateVolumeInAvailabilityZone")
void testCreateSnapshotInRegion() { void testCreateSnapshotInRegion() {
Snapshot snapshot = client.createSnapshotInRegion(defaultRegion, volumeId); Snapshot snapshot = client.createSnapshotInRegion(defaultRegion, volumeId);
Predicate<Snapshot> snapshotted = new RetryablePredicate<Snapshot>(new SnapshotCompleted(client), 600, 10, Predicate<Snapshot> snapshotted = retry(new SnapshotCompleted(client), 600, 10, SECONDS);
TimeUnit.SECONDS);
assert snapshotted.apply(snapshot); assert snapshotted.apply(snapshot);
Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegion(snapshot.getRegion(), Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegion(snapshot.getRegion(),
@ -125,8 +123,7 @@ public class ElasticBlockStoreClientLiveTest extends BaseComputeServiceContextLi
Volume volume = client.createVolumeFromSnapshotInAvailabilityZone(defaultZone, snapshot.getId()); Volume volume = client.createVolumeFromSnapshotInAvailabilityZone(defaultZone, snapshot.getId());
assertNotNull(volume); assertNotNull(volume);
Predicate<Volume> availabile = new RetryablePredicate<Volume>(new VolumeAvailable(client), 600, 10, Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS);
TimeUnit.SECONDS);
assert availabile.apply(volume); assert availabile.apply(volume);
Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(snapshot.getRegion(), volume.getId())); Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(snapshot.getRegion(), volume.getId()));
@ -143,8 +140,7 @@ public class ElasticBlockStoreClientLiveTest extends BaseComputeServiceContextLi
Volume volume = client.createVolumeFromSnapshotInAvailabilityZone(defaultZone, 2, snapshot.getId()); Volume volume = client.createVolumeFromSnapshotInAvailabilityZone(defaultZone, 2, snapshot.getId());
assertNotNull(volume); assertNotNull(volume);
Predicate<Volume> availabile = new RetryablePredicate<Volume>(new VolumeAvailable(client), 600, 10, Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS);
TimeUnit.SECONDS);
assert availabile.apply(volume); assert availabile.apply(volume);
Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(snapshot.getRegion(), volume.getId())); Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(snapshot.getRegion(), volume.getId()));

View File

@ -18,10 +18,12 @@
*/ */
package org.jclouds.elasticstack.compute.config; package org.jclouds.elasticstack.compute.config;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -32,7 +34,7 @@ import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.elasticstack.ElasticStackClient; import org.jclouds.elasticstack.ElasticStackClient;
import org.jclouds.elasticstack.compute.ElasticStackComputeServiceAdapter; import org.jclouds.elasticstack.compute.ElasticStackComputeServiceAdapter;
@ -49,7 +51,6 @@ import org.jclouds.elasticstack.predicates.DriveClaimed;
import org.jclouds.functions.IdentityFunction; import org.jclouds.functions.IdentityFunction;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.location.Provider; import org.jclouds.location.Provider;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.util.Strings2; import org.jclouds.util.Strings2;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -130,9 +131,7 @@ public class ElasticStackComputeServiceContextModule extends
@Provides @Provides
@Singleton @Singleton
protected Predicate<DriveInfo> supplyDriveUnclaimed(DriveClaimed driveClaimed, protected Predicate<DriveInfo> supplyDriveUnclaimed(DriveClaimed driveClaimed, Timeouts timeouts) {
ComputeServiceConstants.Timeouts timeouts) { return retry(Predicates.not(driveClaimed), timeouts.nodeRunning, 1000, MILLISECONDS);
return new RetryablePredicate<DriveInfo>(Predicates.not(driveClaimed), timeouts.nodeRunning, 1000,
TimeUnit.MILLISECONDS);
} }
} }

View File

@ -17,13 +17,13 @@
* under the License. * under the License.
*/ */
package org.jclouds.elasticstack; package org.jclouds.elasticstack;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.ExecResponse;
@ -44,7 +44,6 @@ import org.jclouds.elasticstack.predicates.DriveClaimed;
import org.jclouds.elasticstack.util.Servers; import org.jclouds.elasticstack.util.Servers;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.sshj.config.SshjSshClientModule;
@ -89,10 +88,8 @@ public class ElasticStackClientLiveTest extends BaseComputeServiceContextLiveTes
imageId = view.getComputeService().templateBuilder().build().getImage().getId(); imageId = view.getComputeService().templateBuilder().build().getImage().getId();
client = view.unwrap(ElasticStackApiMetadata.CONTEXT_TOKEN).getApi(); client = view.unwrap(ElasticStackApiMetadata.CONTEXT_TOKEN).getApi();
driveNotClaimed = new RetryablePredicate<DriveInfo>(Predicates.not(new DriveClaimed(client)), maxDriveImageTime, driveNotClaimed = retry(Predicates.not(new DriveClaimed(client)), maxDriveImageTime, 1, SECONDS);
1, TimeUnit.SECONDS); socketTester = retry(new InetSocketAddressConnect(), maxDriveImageTime, 1, SECONDS);
socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), maxDriveImageTime, 1,
TimeUnit.SECONDS);
} }
@Test @Test

View File

@ -19,14 +19,13 @@
package org.jclouds.openstack.cinder.v1.predicates; package org.jclouds.openstack.cinder.v1.predicates;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.TimeUnit; import static org.jclouds.util.Predicates2.retry;
import org.jclouds.openstack.cinder.v1.domain.Snapshot; import org.jclouds.openstack.cinder.v1.domain.Snapshot;
import org.jclouds.openstack.cinder.v1.domain.Volume; import org.jclouds.openstack.cinder.v1.domain.Volume;
import org.jclouds.openstack.cinder.v1.domain.Volume.Status; import org.jclouds.openstack.cinder.v1.domain.Volume.Status;
import org.jclouds.openstack.cinder.v1.features.SnapshotApi; import org.jclouds.openstack.cinder.v1.features.SnapshotApi;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -38,7 +37,7 @@ import com.google.common.base.Predicate;
* <pre> * <pre>
* {@code * {@code
* Snapshot snapshot = snapshotApi.create(volumeId); * Snapshot snapshot = snapshotApi.create(volumeId);
* RetryablePredicate<String> awaitAvailable = new RetryablePredicate<String>( * RetryablePredicate<String> awaitAvailable = RetryablePredicate.create(
* SnapshotPredicates.available(snapshotApi), 600, 10, 10, TimeUnit.SECONDS); * SnapshotPredicates.available(snapshotApi), 600, 10, 10, TimeUnit.SECONDS);
* *
* if (!awaitAvailable.apply(snapshot.getId())) { * if (!awaitAvailable.apply(snapshot.getId())) {
@ -68,10 +67,9 @@ public class SnapshotPredicates {
* @param snapshotApi The SnapshotApi in the zone where your Snapshot resides. * @param snapshotApi The SnapshotApi in the zone where your Snapshot resides.
* @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 20 minutes. * @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 20 minutes.
*/ */
public static RetryablePredicate<Snapshot> awaitAvailable(SnapshotApi snapshotApi) { public static Predicate<Snapshot> awaitAvailable(SnapshotApi snapshotApi) {
StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(snapshotApi, Volume.Status.AVAILABLE); StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(snapshotApi, Volume.Status.AVAILABLE);
return retry(statusPredicate, 1200, 5, 5, SECONDS);
return new RetryablePredicate<Snapshot>(statusPredicate, 1200, 5, 5, TimeUnit.SECONDS);
} }
/** /**
@ -81,17 +79,15 @@ public class SnapshotPredicates {
* @return RetryablePredicate That will check the whether the Snapshot exists * @return RetryablePredicate That will check the whether the Snapshot exists
* every 5 seconds for a maxiumum of 20 minutes. * every 5 seconds for a maxiumum of 20 minutes.
*/ */
public static RetryablePredicate<Snapshot> awaitDeleted(SnapshotApi snapshotApi) { public static Predicate<Snapshot> awaitDeleted(SnapshotApi snapshotApi) {
DeletedPredicate deletedPredicate = new DeletedPredicate(snapshotApi); DeletedPredicate deletedPredicate = new DeletedPredicate(snapshotApi);
return retry(deletedPredicate, 1200, 5, 5, SECONDS);
return new RetryablePredicate<Snapshot>(deletedPredicate, 1200, 5, 5, TimeUnit.SECONDS);
} }
public static RetryablePredicate<Snapshot> awaitStatus( public static Predicate<Snapshot> awaitStatus(SnapshotApi snapshotApi, Volume.Status status, long maxWaitInSec,
SnapshotApi snapshotApi, Volume.Status status, long maxWaitInSec, long periodInSec) { long periodInSec) {
StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(snapshotApi, status); StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(snapshotApi, status);
return retry(statusPredicate, maxWaitInSec, periodInSec, periodInSec, SECONDS);
return new RetryablePredicate<Snapshot>(statusPredicate, maxWaitInSec, periodInSec, periodInSec, TimeUnit.SECONDS);
} }
private static class StatusUpdatedPredicate implements Predicate<Snapshot> { private static class StatusUpdatedPredicate implements Predicate<Snapshot> {

View File

@ -19,13 +19,12 @@
package org.jclouds.openstack.cinder.v1.predicates; package org.jclouds.openstack.cinder.v1.predicates;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.TimeUnit; import static org.jclouds.util.Predicates2.retry;
import org.jclouds.openstack.cinder.v1.domain.Volume; import org.jclouds.openstack.cinder.v1.domain.Volume;
import org.jclouds.openstack.cinder.v1.domain.Volume.Status; import org.jclouds.openstack.cinder.v1.domain.Volume.Status;
import org.jclouds.openstack.cinder.v1.features.VolumeApi; import org.jclouds.openstack.cinder.v1.features.VolumeApi;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -38,7 +37,7 @@ import com.google.common.base.Predicate;
* {@code * {@code
* Volume volume = volumeApi.create(100); * Volume volume = volumeApi.create(100);
* *
* RetryablePredicate<String> awaitAvailable = new RetryablePredicate<String>( * RetryablePredicate<String> awaitAvailable = RetryablePredicate.create(
* VolumePredicates.available(volumeApi), 600, 10, 10, TimeUnit.SECONDS); * VolumePredicates.available(volumeApi), 600, 10, 10, TimeUnit.SECONDS);
* *
* if (!awaitAvailable.apply(volume.getId())) { * if (!awaitAvailable.apply(volume.getId())) {
@ -68,10 +67,9 @@ public class VolumePredicates {
* @param volumeApi The VolumeApi in the zone where your Volume resides. * @param volumeApi The VolumeApi in the zone where your Volume resides.
* @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 10 minutes. * @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 10 minutes.
*/ */
public static RetryablePredicate<Volume> awaitAvailable(VolumeApi volumeApi) { public static Predicate<Volume> awaitAvailable(VolumeApi volumeApi) {
StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, Volume.Status.AVAILABLE); StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, Volume.Status.AVAILABLE);
return retry(statusPredicate, 600, 5, 5, SECONDS);
return new RetryablePredicate<Volume>(statusPredicate, 600, 5, 5, TimeUnit.SECONDS);
} }
/** /**
@ -80,10 +78,9 @@ public class VolumePredicates {
* @param volumeApi The VolumeApi in the zone where your Volume resides. * @param volumeApi The VolumeApi in the zone where your Volume resides.
* @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 10 minutes. * @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 10 minutes.
*/ */
public static RetryablePredicate<Volume> awaitInUse(VolumeApi volumeApi) { public static Predicate<Volume> awaitInUse(VolumeApi volumeApi) {
StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, Volume.Status.IN_USE); StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, Volume.Status.IN_USE);
return retry(statusPredicate, 600, 5, 5, SECONDS);
return new RetryablePredicate<Volume>(statusPredicate, 600, 5, 5, TimeUnit.SECONDS);
} }
/** /**
@ -93,17 +90,15 @@ public class VolumePredicates {
* @return RetryablePredicate That will check the whether the Volume exists * @return RetryablePredicate That will check the whether the Volume exists
* every 5 seconds for a maxiumum of 10 minutes. * every 5 seconds for a maxiumum of 10 minutes.
*/ */
public static RetryablePredicate<Volume> awaitDeleted(VolumeApi volumeApi) { public static Predicate<Volume> awaitDeleted(VolumeApi volumeApi) {
DeletedPredicate deletedPredicate = new DeletedPredicate(volumeApi); DeletedPredicate deletedPredicate = new DeletedPredicate(volumeApi);
return retry(deletedPredicate, 600, 5, 5, SECONDS);
return new RetryablePredicate<Volume>(deletedPredicate, 600, 5, 5, TimeUnit.SECONDS);
} }
public static RetryablePredicate<Volume> awaitStatus( public static Predicate<Volume> awaitStatus(
VolumeApi volumeApi, Volume.Status status, long maxWaitInSec, long periodInSec) { VolumeApi volumeApi, Volume.Status status, long maxWaitInSec, long periodInSec) {
StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, status); StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, status);
return retry(statusPredicate, maxWaitInSec, periodInSec, periodInSec, SECONDS);
return new RetryablePredicate<Volume>(statusPredicate, maxWaitInSec, periodInSec, periodInSec, TimeUnit.SECONDS);
} }
private static class StatusUpdatedPredicate implements Predicate<Volume> { private static class StatusUpdatedPredicate implements Predicate<Volume> {

View File

@ -18,13 +18,14 @@
*/ */
package org.jclouds.openstack.nova.v2_0.compute.config; package org.jclouds.openstack.nova.v2_0.compute.config;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_ALLOCATE_FLOATING_IPS; import static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_ALLOCATE_FLOATING_IPS;
import static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_GENERATE_KEYPAIRS; import static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_GENERATE_KEYPAIRS;
import static org.jclouds.openstack.nova.v2_0.config.NovaProperties.TIMEOUT_SECURITYGROUP_PRESENT; import static org.jclouds.openstack.nova.v2_0.config.NovaProperties.TIMEOUT_SECURITYGROUP_PRESENT;
import static org.jclouds.util.Predicates2.retry;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Named; import javax.inject.Named;
@ -58,7 +59,6 @@ import org.jclouds.openstack.nova.v2_0.compute.loaders.CreateUniqueKeyPair;
import org.jclouds.openstack.nova.v2_0.compute.loaders.FindSecurityGroupOrCreate; import org.jclouds.openstack.nova.v2_0.compute.loaders.FindSecurityGroupOrCreate;
import org.jclouds.openstack.nova.v2_0.compute.loaders.LoadFloatingIpsForInstance; import org.jclouds.openstack.nova.v2_0.compute.loaders.LoadFloatingIpsForInstance;
import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions; import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
import org.jclouds.openstack.nova.v2_0.compute.predicates.GetImageWhenImageInZoneHasActiveStatusPredicateWithResult;
import org.jclouds.openstack.nova.v2_0.compute.strategy.ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet; import org.jclouds.openstack.nova.v2_0.compute.strategy.ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet;
import org.jclouds.openstack.nova.v2_0.domain.FloatingIP; import org.jclouds.openstack.nova.v2_0.domain.FloatingIP;
import org.jclouds.openstack.nova.v2_0.domain.KeyPair; import org.jclouds.openstack.nova.v2_0.domain.KeyPair;
@ -71,8 +71,6 @@ import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndId;
import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndName; import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndName;
import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneSecurityGroupNameAndPorts; import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneSecurityGroupNameAndPorts;
import org.jclouds.openstack.nova.v2_0.predicates.FindSecurityGroupWithNameAndReturnTrue; import org.jclouds.openstack.nova.v2_0.predicates.FindSecurityGroupWithNameAndReturnTrue;
import org.jclouds.predicates.PredicateWithResult;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -146,9 +144,6 @@ public class NovaComputeServiceContextModule extends
bind(new TypeLiteral<ImageExtension>() { bind(new TypeLiteral<ImageExtension>() {
}).to(NovaImageExtension.class); }).to(NovaImageExtension.class);
bind(new TypeLiteral<PredicateWithResult<ZoneAndId, Image>>() {
}).to(GetImageWhenImageInZoneHasActiveStatusPredicateWithResult.class);
} }
@Override @Override
@ -187,7 +182,7 @@ public class NovaComputeServiceContextModule extends
protected Predicate<AtomicReference<ZoneAndName>> securityGroupEventualConsistencyDelay( protected Predicate<AtomicReference<ZoneAndName>> securityGroupEventualConsistencyDelay(
FindSecurityGroupWithNameAndReturnTrue in, FindSecurityGroupWithNameAndReturnTrue in,
@Named(TIMEOUT_SECURITYGROUP_PRESENT) long msDelay) { @Named(TIMEOUT_SECURITYGROUP_PRESENT) long msDelay) {
return new RetryablePredicate<AtomicReference<ZoneAndName>>(in, msDelay, 100l, TimeUnit.MILLISECONDS); return retry(in, msDelay, 100l, MILLISECONDS);
} }
@Provides @Provides

View File

@ -21,10 +21,14 @@ package org.jclouds.openstack.nova.v2_0.compute.extensions;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.find;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;
import static org.jclouds.location.predicates.LocationPredicates.idEquals;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
@ -32,21 +36,26 @@ import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants; import org.jclouds.Constants;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.CloneImageTemplate; import org.jclouds.compute.domain.CloneImageTemplate;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.ImageTemplate; import org.jclouds.compute.domain.ImageTemplate;
import org.jclouds.compute.domain.ImageTemplateBuilder; import org.jclouds.compute.domain.ImageTemplateBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.extensions.ImageExtension; import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.openstack.nova.v2_0.NovaApi; import org.jclouds.openstack.nova.v2_0.NovaApi;
import org.jclouds.openstack.nova.v2_0.domain.Server; import org.jclouds.openstack.nova.v2_0.domain.Server;
import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndId; import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndId;
import org.jclouds.predicates.PredicateWithResult;
import org.jclouds.predicates.Retryables;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.UncheckedTimeoutException;
/** /**
* Nova implementation of {@link ImageExtension} * Nova implementation of {@link ImageExtension}
@ -63,21 +72,17 @@ public class NovaImageExtension implements ImageExtension {
private final NovaApi novaApi; private final NovaApi novaApi;
private final ListeningExecutorService userExecutor; private final ListeningExecutorService userExecutor;
@com.google.inject.Inject(optional = true) private final Supplier<Set<? extends Location>> locations;
@Named("IMAGE_MAX_WAIT") private final Predicate<AtomicReference<Image>> imageAvailablePredicate;
private long maxWait = 3600;
@com.google.inject.Inject(optional = true)
@Named("IMAGE_WAIT_PERIOD")
private long waitPeriod = 1;
private PredicateWithResult<ZoneAndId, Image> imageReadyPredicate;
@Inject @Inject
public NovaImageExtension(NovaApi novaApi, public NovaImageExtension(NovaApi novaApi, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, @Memoized Supplier<Set<? extends Location>> locations,
PredicateWithResult<ZoneAndId, Image> imageReadyPredicate) { @Named(TIMEOUT_IMAGE_AVAILABLE) Predicate<AtomicReference<Image>> imageAvailablePredicate) {
this.novaApi = checkNotNull(novaApi); this.novaApi = checkNotNull(novaApi, "novaApi");
this.userExecutor = userExecutor; this.userExecutor = checkNotNull(userExecutor, "userExecutor");
this.imageReadyPredicate = imageReadyPredicate; this.locations = checkNotNull(locations, "locations");
this.imageAvailablePredicate = checkNotNull(imageAvailablePredicate, "imageAvailablePredicate");
} }
@Override @Override
@ -103,13 +108,22 @@ public class NovaImageExtension implements ImageExtension {
final ZoneAndId targetImageZoneAndId = ZoneAndId.fromZoneAndId(sourceImageZoneAndId.getZone(), newImageId); final ZoneAndId targetImageZoneAndId = ZoneAndId.fromZoneAndId(sourceImageZoneAndId.getZone(), newImageId);
logger.info(">> Registered new Image %s, waiting for it to become available.", newImageId); logger.info(">> Registered new Image %s, waiting for it to become available.", newImageId);
final AtomicReference<Image> image = new AtomicReference<Image>(new ImageBuilder()
.location(find(locations.get(), idEquals(targetImageZoneAndId.getZone())))
.id(targetImageZoneAndId.slashEncode())
.providerId(targetImageZoneAndId.getId())
.description(cloneTemplate.getName())
.operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build())
.status(Image.Status.PENDING).build());
return userExecutor.submit(new Callable<Image>() { return userExecutor.submit(new Callable<Image>() {
@Override @Override
public Image call() throws Exception { public Image call() throws Exception {
return Retryables.retryGettingResultOrFailing(imageReadyPredicate, targetImageZoneAndId, maxWait, if (imageAvailablePredicate.apply(image))
waitPeriod, TimeUnit.SECONDS, "Image was not created within the time limit, Giving up! [Limit: " return image.get();
+ maxWait + " secs.]"); // TODO: get rid of the expectation that the image will be available, as it is very brittle
throw new UncheckedTimeoutException("Image was not created within the time limit: " + image.get());
} }
}); });
} }

View File

@ -1,100 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.openstack.nova.v2_0.compute.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.openstack.nova.v2_0.NovaApi;
import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ImageInZone;
import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndId;
import org.jclouds.predicates.PredicateWithResult;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
/**
* @author David Alves
*/
public final class GetImageWhenImageInZoneHasActiveStatusPredicateWithResult implements
PredicateWithResult<ZoneAndId, Image> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private org.jclouds.openstack.nova.v2_0.domain.Image result;
private ZoneAndId resultZoneAndId;
private RuntimeException lastFailure;
private Function<ImageInZone, Image> imageInZoneToImage;
private NovaApi api;
@Inject
public GetImageWhenImageInZoneHasActiveStatusPredicateWithResult(Function<ImageInZone, Image> imageInZoneToImage,
NovaApi api) {
this.imageInZoneToImage = imageInZoneToImage;
this.api = api;
}
@Override
public boolean apply(ZoneAndId input) {
result = checkNotNull(findImage(ZoneAndId.fromZoneAndId(input.getZone(), input.getId())));
resultZoneAndId = input;
switch (result.getStatus()) {
case ACTIVE:
logger.info("<< Image %s is available for use. %s", input.getId(), result);
return true;
case UNRECOGNIZED:
case SAVING:
logger.debug("<< Image %s is not available yet. %s", input.getId(), result);
return false;
default:
lastFailure = new IllegalStateException("Image " + input.getId() + " was not created. " + result);
throw lastFailure;
}
}
@Override
public Image getResult() {
return imageInZoneToImage.apply(new ImageInZone(result, resultZoneAndId.getZone()));
}
@Override
public Throwable getLastFailure() {
return lastFailure;
}
public org.jclouds.openstack.nova.v2_0.domain.Image findImage(final ZoneAndId zoneAndId) {
return api.getImageApiForZone(zoneAndId.getZone()).listInDetail().concat().firstMatch(
new Predicate<org.jclouds.openstack.nova.v2_0.domain.Image>() {
@Override
public boolean apply(org.jclouds.openstack.nova.v2_0.domain.Image input) {
return input.getId().equals(zoneAndId.getId());
}
}).orNull();
}
}

View File

@ -0,0 +1,94 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.openstack.nova.v2_0.compute.extensions;
import static org.testng.Assert.assertEquals;
import java.util.Properties;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageTemplate;
import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.nova.v2_0.internal.BaseNovaComputeServiceExpectTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Futures;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "NovaImageExtensionExpectTest")
public class NovaImageExtensionExpectTest extends BaseNovaComputeServiceExpectTest {
@Override
protected Properties setupProperties() {
Properties overrides = super.setupProperties();
overrides.setProperty("jclouds.zones", "az-1.region-a.geo-1");
return overrides;
}
HttpRequest serverDetail = HttpRequest.builder().method("GET")
.endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/71752")
.addHeader("Accept", "application/json")
.addHeader("X-Auth-Token", authToken).build();
HttpResponse serverDetailResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/server_details.json")).build();
HttpRequest createImage = HttpRequest.builder().method("POST")
.endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/71752/action")
.addHeader("Accept", "application/json")
.addHeader("X-Auth-Token", authToken)
.payload(
payloadFromStringWithContentType(
"{\"createImage\":{\"name\":\"test\", \"metadata\": {}}}",
"application/json")).build();
HttpResponse createImageResponse = HttpResponse.builder().statusCode(202)
.addHeader("Location", "https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/52415800-8b69-11e0-9b19-734f5736d2a2")
.build();
HttpRequest getImage = HttpRequest.builder().method("GET")
.endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/52415800-8b69-11e0-9b19-734f5736d2a2")
.addHeader("Accept", "application/json")
.addHeader("X-Auth-Token", authToken).build();
HttpResponse getImageResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/image_active.json")).build();
public void testCreateImage() {
Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();
requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);
requestResponseMap.put(serverDetail, serverDetailResponse).build();
requestResponseMap.put(createImage, createImageResponse).build();
requestResponseMap.put(getImage, getImageResponse).build();
ImageExtension apiThatCreatesImage = requestsSendResponses(requestResponseMap.build()).getImageExtension().get();
ImageTemplate newImageTemplate = apiThatCreatesImage.buildImageTemplateFromNode("test", "az-1.region-a.geo-1/71752");
Image image = Futures.getUnchecked(apiThatCreatesImage.createImage(newImageTemplate));
assertEquals(image.getId(), "az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f5736d2a2");
}
}

View File

@ -1,95 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.openstack.nova.v2_0.compute.predicates;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Map;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Image;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndId;
import org.jclouds.openstack.nova.v2_0.internal.BaseNovaComputeServiceContextExpectTest;
import org.jclouds.predicates.PredicateWithResult;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Injector;
/**
*
* @author David Alves
*
*/
@Test(groups = "unit", testName = "GetImageWhenImageInZoneHasActiveStatusPredicateWithResultExpectTest")
public class GetImageWhenImageInZoneHasActiveStatusPredicateWithResultExpectTest extends
BaseNovaComputeServiceContextExpectTest<Injector> {
private final HttpResponse listDetailImageExtensionResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/image_list_detail_imageextension.json")).build();
private Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()
.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)
.put(listDetail, listDetailImageExtensionResponse).build();
public void testReturnsFalseOnImageStatusSavingAndTrueOnActive() {
Injector injector = requestsSendResponses(requestResponseMap);
PredicateWithResult<ZoneAndId, Image> predicate = injector
.getInstance(GetImageWhenImageInZoneHasActiveStatusPredicateWithResult.class);
ZoneAndId zoneAdnId0 = ZoneAndId.fromZoneAndId("az-1.region-a.geo-1", "13");
ZoneAndId zoneAdnId1 = ZoneAndId.fromZoneAndId("az-1.region-a.geo-1", "12");
ZoneAndId zoneAdnId2 = ZoneAndId.fromZoneAndId("az-1.region-a.geo-1", "15");
assertTrue(predicate.apply(zoneAdnId0)); // ACTIVE
assertFalse(predicate.apply(zoneAdnId1)); // SAVING
assertFalse(predicate.apply(zoneAdnId2)); // UNRECOGNIZED
assertEquals("oneiric-server-cloudimg-amd64", predicate.getResult().getName());
}
public void testFailsOnOtherStatuses() {
Injector injector = requestsSendResponses(requestResponseMap);
PredicateWithResult<ZoneAndId, Image> predicate = injector
.getInstance(GetImageWhenImageInZoneHasActiveStatusPredicateWithResult.class);
ZoneAndId zoneAdnId1 = ZoneAndId.fromZoneAndId("az-1.region-a.geo-1", "14");
ZoneAndId zoneAdnId2 = ZoneAndId.fromZoneAndId("az-1.region-a.geo-1", "11");
ZoneAndId zoneAdnId3 = ZoneAndId.fromZoneAndId("az-1.region-a.geo-1", "10");
assertTrue(illegalStateExceptionThrown(predicate, zoneAdnId1)); // UNKNOWN
assertTrue(illegalStateExceptionThrown(predicate, zoneAdnId2)); // ERROR
assertTrue(illegalStateExceptionThrown(predicate, zoneAdnId3)); // ERROR
}
private boolean illegalStateExceptionThrown(PredicateWithResult<ZoneAndId, Image> predicate, ZoneAndId zoneAndId) {
try {
predicate.apply(zoneAndId);
} catch (IllegalStateException e) {
return true;
}
return false;
}
@Override
public Injector apply(ComputeServiceContext input) {
return input.utils().injector();
}
}

View File

@ -18,6 +18,7 @@
*/ */
package org.jclouds.openstack.nova.v2_0.extensions; package org.jclouds.openstack.nova.v2_0.extensions;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -30,7 +31,6 @@ import org.jclouds.openstack.nova.v2_0.domain.VolumeSnapshot;
import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;
import org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions; import org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions;
import org.jclouds.openstack.nova.v2_0.options.CreateVolumeSnapshotOptions; import org.jclouds.openstack.nova.v2_0.options.CreateVolumeSnapshotOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -69,8 +69,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest {
if (testSnapshot != null) { if (testSnapshot != null) {
final String snapshotId = testSnapshot.getId(); final String snapshotId = testSnapshot.getId();
assertTrue(volumeOption.get().deleteSnapshot(snapshotId)); assertTrue(volumeOption.get().deleteSnapshot(snapshotId));
assertTrue(new RetryablePredicate<VolumeApi>(new Predicate<VolumeApi>() { assertTrue(retry(new Predicate<VolumeApi>() {
@Override
public boolean apply(VolumeApi volumeApi) { public boolean apply(VolumeApi volumeApi) {
return volumeOption.get().getSnapshot(snapshotId) == null; return volumeOption.get().getSnapshot(snapshotId) == null;
} }
@ -79,8 +78,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest {
if (testVolume != null) { if (testVolume != null) {
final String volumeId = testVolume.getId(); final String volumeId = testVolume.getId();
assertTrue(volumeOption.get().delete(volumeId)); assertTrue(volumeOption.get().delete(volumeId));
assertTrue(new RetryablePredicate<VolumeApi>(new Predicate<VolumeApi>() { assertTrue(retry(new Predicate<VolumeApi>() {
@Override
public boolean apply(VolumeApi volumeApi) { public boolean apply(VolumeApi volumeApi) {
return volumeOption.get().get(volumeId) == null; return volumeOption.get().get(volumeId) == null;
} }
@ -93,11 +91,10 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest {
public void testCreateVolume() { public void testCreateVolume() {
if (volumeOption.isPresent()) { if (volumeOption.isPresent()) {
testVolume = volumeOption.get().create( testVolume = volumeOption.get().create(
1, 1,
CreateVolumeOptions.Builder.name("jclouds-test-volume").description("description of test volume") CreateVolumeOptions.Builder.name("jclouds-test-volume").description("description of test volume")
.availabilityZone(zone)); .availabilityZone(zone));
assertTrue(new RetryablePredicate<VolumeApi>(new Predicate<VolumeApi>() { assertTrue(retry(new Predicate<VolumeApi>() {
@Override
public boolean apply(VolumeApi volumeApi) { public boolean apply(VolumeApi volumeApi) {
return volumeOption.get().get(testVolume.getId()).getStatus() == Volume.Status.AVAILABLE; return volumeOption.get().get(testVolume.getId()).getStatus() == Volume.Status.AVAILABLE;
} }
@ -162,8 +159,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest {
assertTrue(testSnapshot.getSize() > -1); assertTrue(testSnapshot.getSize() > -1);
assertNotNull(testSnapshot.getCreated()); assertNotNull(testSnapshot.getCreated());
assertTrue(new RetryablePredicate<VolumeApi>(new Predicate<VolumeApi>() { assertTrue(retry(new Predicate<VolumeApi>() {
@Override
public boolean apply(VolumeApi volumeApi) { public boolean apply(VolumeApi volumeApi) {
return volumeOption.get().getSnapshot(snapshotId).getStatus() == Volume.Status.AVAILABLE; return volumeOption.get().getSnapshot(snapshotId).getStatus() == Volume.Status.AVAILABLE;
} }
@ -234,8 +230,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest {
assertNotNull(testAttachment.getId()); assertNotNull(testAttachment.getId());
assertEquals(testAttachment.getVolumeId(), testVolume.getId()); assertEquals(testAttachment.getVolumeId(), testVolume.getId());
assertTrue(new RetryablePredicate<VolumeApi>(new Predicate<VolumeApi>() { assertTrue(retry(new Predicate<VolumeApi>() {
@Override
public boolean apply(VolumeApi volumeApi) { public boolean apply(VolumeApi volumeApi) {
return volumeOption.get().listAttachmentsOnServer(serverId).size() > before; return volumeOption.get().listAttachmentsOnServer(serverId).size() > before;
} }
@ -265,8 +260,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest {
assertTrue(foundIt, "Failed to find the attachment we created in listAttachments() response"); assertTrue(foundIt, "Failed to find the attachment we created in listAttachments() response");
volumeOption.get().detachVolumeFromServer(testVolume.getId(), serverId); volumeOption.get().detachVolumeFromServer(testVolume.getId(), serverId);
assertTrue(new RetryablePredicate<VolumeApi>(new Predicate<VolumeApi>() { assertTrue(retry(new Predicate<VolumeApi>() {
@Override
public boolean apply(VolumeApi volumeApi) { public boolean apply(VolumeApi volumeApi) {
return volumeOption.get().listAttachmentsOnServer(serverId).size() == before; return volumeOption.get().listAttachmentsOnServer(serverId).size() == before;
} }

View File

@ -18,6 +18,7 @@
*/ */
package org.jclouds.openstack.nova.v2_0.extensions; package org.jclouds.openstack.nova.v2_0.extensions;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -28,7 +29,6 @@ import org.jclouds.openstack.nova.v2_0.domain.Volume;
import org.jclouds.openstack.nova.v2_0.domain.VolumeAttachment; import org.jclouds.openstack.nova.v2_0.domain.VolumeAttachment;
import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;
import org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions; import org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -68,8 +68,7 @@ public class VolumeAttachmentApiLiveTest extends BaseNovaApiLiveTest {
if (testVolume != null) { if (testVolume != null) {
final String volumeId = testVolume.getId(); final String volumeId = testVolume.getId();
assertTrue(volumeApi.get().delete(volumeId)); assertTrue(volumeApi.get().delete(volumeId));
assertTrue(new RetryablePredicate<VolumeApi>(new Predicate<VolumeApi>() { assertTrue(retry(new Predicate<VolumeApi>() {
@Override
public boolean apply(VolumeApi volumeApi) { public boolean apply(VolumeApi volumeApi) {
return volumeApi.get(volumeId) == null; return volumeApi.get(volumeId) == null;
} }
@ -88,8 +87,7 @@ public class VolumeAttachmentApiLiveTest extends BaseNovaApiLiveTest {
.availabilityZone(zone); .availabilityZone(zone);
testVolume = volumeApi.get().create(1, options); testVolume = volumeApi.get().create(1, options);
assertTrue(new RetryablePredicate<VolumeApi>(new Predicate<VolumeApi>() { assertTrue(retry(new Predicate<VolumeApi>() {
@Override
public boolean apply(VolumeApi volumeApi) { public boolean apply(VolumeApi volumeApi) {
return volumeApi.get(testVolume.getId()).getStatus() == Volume.Status.AVAILABLE; return volumeApi.get(testVolume.getId()).getStatus() == Volume.Status.AVAILABLE;
} }
@ -114,8 +112,7 @@ public class VolumeAttachmentApiLiveTest extends BaseNovaApiLiveTest {
assertNotNull(testAttachment.getId()); assertNotNull(testAttachment.getId());
assertEquals(testAttachment.getVolumeId(), testVolume.getId()); assertEquals(testAttachment.getVolumeId(), testVolume.getId());
assertTrue(new RetryablePredicate<VolumeAttachmentApi>(new Predicate<VolumeAttachmentApi>() { assertTrue(retry(new Predicate<VolumeAttachmentApi>() {
@Override
public boolean apply(VolumeAttachmentApi volumeAttachmentApi) { public boolean apply(VolumeAttachmentApi volumeAttachmentApi) {
return volumeAttachmentApi.listAttachmentsOnServer(serverId).size() > before; return volumeAttachmentApi.listAttachmentsOnServer(serverId).size() > before;
} }
@ -145,8 +142,7 @@ public class VolumeAttachmentApiLiveTest extends BaseNovaApiLiveTest {
assertTrue(foundIt, "Failed to find the attachment we created in listAttachments() response"); assertTrue(foundIt, "Failed to find the attachment we created in listAttachments() response");
volumeAttachmentApi.get().detachVolumeFromServer(testVolume.getId(), serverId); volumeAttachmentApi.get().detachVolumeFromServer(testVolume.getId(), serverId);
assertTrue(new RetryablePredicate<VolumeAttachmentApi>(new Predicate<VolumeAttachmentApi>() { assertTrue(retry(new Predicate<VolumeAttachmentApi>() {
@Override
public boolean apply(VolumeAttachmentApi volumeAttachmentApi) { public boolean apply(VolumeAttachmentApi volumeAttachmentApi) {
return volumeAttachmentApi.listAttachmentsOnServer(serverId).size() == before; return volumeAttachmentApi.listAttachmentsOnServer(serverId).size() == before;
} }

View File

@ -18,6 +18,7 @@
*/ */
package org.jclouds.openstack.nova.v2_0.extensions; package org.jclouds.openstack.nova.v2_0.extensions;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
@ -27,7 +28,6 @@ import java.util.Set;
import org.jclouds.openstack.nova.v2_0.domain.VolumeType; import org.jclouds.openstack.nova.v2_0.domain.VolumeType;
import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;
import org.jclouds.openstack.nova.v2_0.options.CreateVolumeTypeOptions; import org.jclouds.openstack.nova.v2_0.options.CreateVolumeTypeOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -67,8 +67,7 @@ public class VolumeTypeApiLiveTest extends BaseNovaApiLiveTest {
if (testVolumeType != null) { if (testVolumeType != null) {
final String id = testVolumeType.getId(); final String id = testVolumeType.getId();
assertTrue(volumeTypeOption.get().delete(id)); assertTrue(volumeTypeOption.get().delete(id));
assertTrue(new RetryablePredicate<VolumeTypeApi>(new Predicate<VolumeTypeApi>() { assertTrue(retry(new Predicate<VolumeTypeApi>() {
@Override
public boolean apply(VolumeTypeApi volumeApi) { public boolean apply(VolumeTypeApi volumeApi) {
return volumeApi.get(id) == null; return volumeApi.get(id) == null;
} }
@ -82,8 +81,7 @@ public class VolumeTypeApiLiveTest extends BaseNovaApiLiveTest {
if (volumeTypeOption.isPresent()) { if (volumeTypeOption.isPresent()) {
testVolumeType = volumeTypeOption.get().create( testVolumeType = volumeTypeOption.get().create(
"jclouds-test-1", CreateVolumeTypeOptions.Builder.specs(ImmutableMap.of("test", "value1"))); "jclouds-test-1", CreateVolumeTypeOptions.Builder.specs(ImmutableMap.of("test", "value1")));
assertTrue(new RetryablePredicate<VolumeTypeApi>(new Predicate<VolumeTypeApi>() { assertTrue(retry(new Predicate<VolumeTypeApi>() {
@Override
public boolean apply(VolumeTypeApi volumeTypeApi) { public boolean apply(VolumeTypeApi volumeTypeApi) {
return volumeTypeApi.get(testVolumeType.getId()) != null; return volumeTypeApi.get(testVolumeType.getId()) != null;
} }

View File

@ -0,0 +1,41 @@
{
"image" : {
"id" : "52415800-8b69-11e0-9b19-734f5736d2a2",
"name" : "My Server Backup",
"updated" : "2010-10-10T12:00:00Z",
"created" : "2010-08-10T12:00:00Z",
"tenant_id" : "12345",
"user_id" : "joe",
"status" : "ACTIVE",
"progress" : 80,
"minDisk" : 5,
"minRam" : 256,
"metadata" : {
"ImageType" : "Gold",
"ImageVersion" : "1.5"
},
"server" : {
"id": "52415800-8b69-11e0-9b19-734f335aa7b3",
"links": [
{
"rel": "self",
"href": "http://servers.api.openstack.org/v1.1/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3"
},
{
"rel": "bookmark",
"href": "http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3"
}
]
},
"links": [
{
"rel" : "self",
"href" : "http://servers.api.openstack.org/v1.1/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2"
},
{
"rel" : "bookmark",
"href" : "http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2"
}
]
}
}

View File

@ -19,10 +19,9 @@
package org.jclouds.rackspace.cloudloadbalancers.predicates; package org.jclouds.rackspace.cloudloadbalancers.predicates;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.util.concurrent.TimeUnit;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rackspace.cloudloadbalancers.domain.LoadBalancer; import org.jclouds.rackspace.cloudloadbalancers.domain.LoadBalancer;
import org.jclouds.rackspace.cloudloadbalancers.features.LoadBalancerApi; import org.jclouds.rackspace.cloudloadbalancers.features.LoadBalancerApi;
@ -37,7 +36,7 @@ import com.google.common.base.Predicate;
* {@code * {@code
* LoadBalancer loadBalancer = loadBalancerApi.create(loadBalancerRequest); * LoadBalancer loadBalancer = loadBalancerApi.create(loadBalancerRequest);
* *
* RetryablePredicate<String> awaitAvailable = new RetryablePredicate<String>( * RetryablePredicate<String> awaitAvailable = RetryablePredicate.create(
* LoadBalancerPredicates.available(loadBalancerApi), 600, 10, 10, TimeUnit.SECONDS); * LoadBalancerPredicates.available(loadBalancerApi), 600, 10, 10, TimeUnit.SECONDS);
* *
* if (!awaitAvailable.apply(loadBalancer)) { * if (!awaitAvailable.apply(loadBalancer)) {
@ -67,10 +66,9 @@ public class LoadBalancerPredicates {
* @param loadBalancerApi The LoadBalancerApi in the zone where your LoadBalancer resides. * @param loadBalancerApi The LoadBalancerApi in the zone where your LoadBalancer resides.
* @return RetryablePredicate That will check the status every 3 seconds for a maxiumum of 5 minutes. * @return RetryablePredicate That will check the status every 3 seconds for a maxiumum of 5 minutes.
*/ */
public static RetryablePredicate<LoadBalancer> awaitAvailable(LoadBalancerApi loadBalancerApi) { public static Predicate<LoadBalancer> awaitAvailable(LoadBalancerApi loadBalancerApi) {
StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(loadBalancerApi, LoadBalancer.Status.ACTIVE); StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(loadBalancerApi, LoadBalancer.Status.ACTIVE);
return retry(statusPredicate, 300, 3, 3, SECONDS);
return new RetryablePredicate<LoadBalancer>(statusPredicate, 300, 3, 3, TimeUnit.SECONDS);
} }
/** /**
@ -80,17 +78,15 @@ public class LoadBalancerPredicates {
* @return RetryablePredicate That will check the whether the LoadBalancer exists * @return RetryablePredicate That will check the whether the LoadBalancer exists
* every 3 seconds for a maxiumum of 5 minutes. * every 3 seconds for a maxiumum of 5 minutes.
*/ */
public static RetryablePredicate<LoadBalancer> awaitDeleted(LoadBalancerApi loadBalancerApi) { public static Predicate<LoadBalancer> awaitDeleted(LoadBalancerApi loadBalancerApi) {
DeletedPredicate deletedPredicate = new DeletedPredicate(loadBalancerApi); DeletedPredicate deletedPredicate = new DeletedPredicate(loadBalancerApi);
return retry(deletedPredicate, 300, 3, 3, SECONDS);
return new RetryablePredicate<LoadBalancer>(deletedPredicate, 300, 3, 3, TimeUnit.SECONDS);
} }
public static RetryablePredicate<LoadBalancer> awaitStatus( public static Predicate<LoadBalancer> awaitStatus(
LoadBalancerApi loadBalancerApi, LoadBalancer.Status status, long maxWaitInSec, long periodInSec) { LoadBalancerApi loadBalancerApi, LoadBalancer.Status status, long maxWaitInSec, long periodInSec) {
StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(loadBalancerApi, status); StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(loadBalancerApi, status);
return retry(statusPredicate, maxWaitInSec, periodInSec, periodInSec, SECONDS);
return new RetryablePredicate<LoadBalancer>(statusPredicate, maxWaitInSec, periodInSec, periodInSec, TimeUnit.SECONDS);
} }
private static class StatusUpdatedPredicate implements Predicate<LoadBalancer> { private static class StatusUpdatedPredicate implements Predicate<LoadBalancer> {

View File

@ -20,6 +20,7 @@ package org.jclouds.s3.blobstore;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.util.Predicates2.retry;
import java.util.Set; import java.util.Set;
@ -43,7 +44,6 @@ import org.jclouds.blobstore.util.BlobUtils;
import org.jclouds.collect.Memoized; import org.jclouds.collect.Memoized;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.s3.S3Client; import org.jclouds.s3.S3Client;
import org.jclouds.s3.blobstore.functions.BlobToObject; import org.jclouds.s3.blobstore.functions.BlobToObject;
import org.jclouds.s3.blobstore.functions.BucketToResourceList; import org.jclouds.s3.blobstore.functions.BucketToResourceList;
@ -154,7 +154,7 @@ public class S3BlobStore extends BaseBlobStore {
*/ */
@Override @Override
protected void deletePathAndEnsureGone(String path) { protected void deletePathAndEnsureGone(String path) {
checkState(new RetryablePredicate<String>(new Predicate<String>() { checkState(retry(new Predicate<String>() {
public boolean apply(String in) { public boolean apply(String in) {
try { try {
clearContainer(in); clearContainer(in);

View File

@ -29,6 +29,7 @@ import static com.google.common.collect.Maps.transformValues;
import static com.google.common.collect.Maps.uniqueIndex; import static com.google.common.collect.Maps.uniqueIndex;
import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import static org.jclouds.rest.config.BinderUtils.bindHttpApi; import static org.jclouds.rest.config.BinderUtils.bindHttpApi;
import static org.jclouds.util.Predicates2.retry;
import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_DEFAULT_FENCEMODE; import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_DEFAULT_FENCEMODE;
import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED; import static org.jclouds.vcloud.reference.VCloudConstants.PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED;
@ -52,7 +53,6 @@ import org.jclouds.http.annotation.ServerError;
import org.jclouds.location.suppliers.ImplicitLocationSupplier; import org.jclouds.location.suppliers.ImplicitLocationSupplier;
import org.jclouds.location.suppliers.LocationsSupplier; import org.jclouds.location.suppliers.LocationsSupplier;
import org.jclouds.ovf.Envelope; import org.jclouds.ovf.Envelope;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.annotations.ApiVersion; import org.jclouds.rest.annotations.ApiVersion;
@ -443,7 +443,7 @@ public class VCloudRestClientModule extends RestClientModule<VCloudClient, VClou
@Singleton @Singleton
protected Predicate<URI> successTester(Injector injector, protected Predicate<URI> successTester(Injector injector,
@Named(PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED) long completed) { @Named(PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED) long completed) {
return new RetryablePredicate<URI>(injector.getInstance(TaskSuccess.class), completed); return retry(injector.getInstance(TaskSuccess.class), completed);
} }
@Provides @Provides

View File

@ -19,13 +19,13 @@
package org.jclouds.vcloud.features; package org.jclouds.vcloud.features;
import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Iterables.getOnlyElement;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.net.URI; import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.vcloud.VCloudMediaType; import org.jclouds.vcloud.VCloudMediaType;
import org.jclouds.vcloud.domain.Catalog; import org.jclouds.vcloud.domain.Catalog;
import org.jclouds.vcloud.domain.CatalogItem; import org.jclouds.vcloud.domain.CatalogItem;
@ -121,8 +121,7 @@ public class VAppTemplateClientLiveTest extends BaseVCloudClientLiveTest {
node = getOnlyElement(client.createNodesInGroup(group, 1)); node = getOnlyElement(client.createNodesInGroup(group, 1));
Predicate<URI> taskTester = new RetryablePredicate<URI>(new TaskSuccess(getVCloudApi()), 600, 5, Predicate<URI> taskTester = retry(new TaskSuccess(getVCloudApi()), 600, 5, SECONDS);
TimeUnit.SECONDS);
// I have to undeploy first // I have to undeploy first
Task task = getVCloudApi().getVAppClient().undeployVApp(URI.create(node.getId())); Task task = getVCloudApi().getVAppClient().undeployVApp(URI.create(node.getId()));

View File

@ -21,6 +21,7 @@ package org.jclouds.blobstore.internal;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive; import static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive;
import static org.jclouds.util.Predicates2.retry;
import java.util.Set; import java.util.Set;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@ -41,7 +42,6 @@ import org.jclouds.blobstore.util.BlobUtils;
import org.jclouds.blobstore.util.internal.BlobUtilsImpl; import org.jclouds.blobstore.util.internal.BlobUtilsImpl;
import org.jclouds.collect.Memoized; import org.jclouds.collect.Memoized;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
@ -268,7 +268,7 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
} }
protected void deletePathAndEnsureGone(String path) { protected void deletePathAndEnsureGone(String path) {
checkState(new RetryablePredicate<String>(new Predicate<String>() { checkState(retry(new Predicate<String>() {
public boolean apply(String in) { public boolean apply(String in) {
try { try {
clearContainer(in, recursive()); clearContainer(in, recursive());

View File

@ -21,6 +21,7 @@ package org.jclouds.blobstore.internal;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive; import static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive;
import static org.jclouds.util.Predicates2.retry;
import java.util.Set; import java.util.Set;
@ -38,7 +39,6 @@ import org.jclouds.blobstore.util.BlobUtils;
import org.jclouds.blobstore.util.internal.BlobUtilsImpl; import org.jclouds.blobstore.util.internal.BlobUtilsImpl;
import org.jclouds.collect.Memoized; import org.jclouds.collect.Memoized;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
@ -197,7 +197,7 @@ public abstract class BaseBlobStore implements BlobStore {
} }
protected void deletePathAndEnsureGone(String path) { protected void deletePathAndEnsureGone(String path) {
checkState(new RetryablePredicate<String>(new Predicate<String>() { checkState(retry(new Predicate<String>() {
public boolean apply(String in) { public boolean apply(String in) {
try { try {
clearContainer(in, recursive()); clearContainer(in, recursive());

View File

@ -28,6 +28,7 @@ import static com.google.common.collect.Maps.uniqueIndex;
import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import static org.jclouds.rest.config.BinderUtils.bindHttpApi; import static org.jclouds.rest.config.BinderUtils.bindHttpApi;
import static org.jclouds.trmk.vcloud_0_8.reference.VCloudConstants.PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED; import static org.jclouds.trmk.vcloud_0_8.reference.VCloudConstants.PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED;
import static org.jclouds.util.Predicates2.retry;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
@ -48,7 +49,6 @@ import org.jclouds.http.annotation.Redirection;
import org.jclouds.http.annotation.ServerError; import org.jclouds.http.annotation.ServerError;
import org.jclouds.location.suppliers.ImplicitLocationSupplier; import org.jclouds.location.suppliers.ImplicitLocationSupplier;
import org.jclouds.location.suppliers.LocationsSupplier; import org.jclouds.location.suppliers.LocationsSupplier;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.annotations.ApiVersion; import org.jclouds.rest.annotations.ApiVersion;
import org.jclouds.rest.config.RestClientModule; import org.jclouds.rest.config.RestClientModule;
@ -366,7 +366,7 @@ public class TerremarkVCloudRestClientModule<S, A> extends RestClientModule<S, A
@Singleton @Singleton
protected Predicate<URI> successTester(Injector injector, protected Predicate<URI> successTester(Injector injector,
@Named(PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED) long completed) { @Named(PROPERTY_VCLOUD_TIMEOUT_TASK_COMPLETED) long completed) {
return new RetryablePredicate<URI>(injector.getInstance(TaskSuccess.class), completed); return retry(injector.getInstance(TaskSuccess.class), completed);
} }
@Provides @Provides

View File

@ -21,6 +21,8 @@ package org.jclouds.trmk.vcloud_0_8;
import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.size; import static com.google.common.collect.Iterables.size;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.jclouds.trmk.vcloud_0_8.domain.VAppConfiguration.Builder.changeNameTo; import static org.jclouds.trmk.vcloud_0_8.domain.VAppConfiguration.Builder.changeNameTo;
import static org.jclouds.trmk.vcloud_0_8.domain.VAppConfiguration.Builder.deleteDiskWithAddressOnParent; import static org.jclouds.trmk.vcloud_0_8.domain.VAppConfiguration.Builder.deleteDiskWithAddressOnParent;
import static org.jclouds.trmk.vcloud_0_8.options.CloneVAppOptions.Builder.deploy; import static org.jclouds.trmk.vcloud_0_8.options.CloneVAppOptions.Builder.deploy;
@ -37,21 +39,19 @@ import java.util.Map.Entry;
import java.util.Properties; import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import org.jclouds.cim.CIMPredicates; import org.jclouds.cim.CIMPredicates;
import org.jclouds.cim.ResourceAllocationSettingData; import org.jclouds.cim.ResourceAllocationSettingData;
import org.jclouds.cim.ResourceAllocationSettingData.ResourceType; import org.jclouds.cim.ResourceAllocationSettingData.ResourceType;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshClient.Factory; import org.jclouds.ssh.SshClient.Factory;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.ssh.SshException; import org.jclouds.ssh.SshException;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.trmk.vcloud_0_8.domain.Catalog; import org.jclouds.trmk.vcloud_0_8.domain.Catalog;
import org.jclouds.trmk.vcloud_0_8.domain.CatalogItem; import org.jclouds.trmk.vcloud_0_8.domain.CatalogItem;
import org.jclouds.trmk.vcloud_0_8.domain.CustomizationParameters; import org.jclouds.trmk.vcloud_0_8.domain.CustomizationParameters;
@ -78,6 +78,7 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
@ -96,8 +97,8 @@ public abstract class TerremarkClientLiveTest<S extends TerremarkVCloudClient, A
protected InternetService is; protected InternetService is;
protected Node node; protected Node node;
protected VApp vApp; protected VApp vApp;
protected RetryablePredicate<HostAndPort> socketTester; protected Predicate<HostAndPort> socketTester;
protected RetryablePredicate<URI> successTester; protected Predicate<URI> successTester;
protected Injector injector; protected Injector injector;
protected VApp clone; protected VApp clone;
@ -488,13 +489,10 @@ public abstract class TerremarkClientLiveTest<S extends TerremarkVCloudClient, A
injector = view.utils().injector(); injector = view.utils().injector();
sshFactory = injector.getInstance(SshClient.Factory.class); sshFactory = injector.getInstance(SshClient.Factory.class);
socketTester = new RetryablePredicate<HostAndPort>(injector.getInstance(SocketOpen.class), 300, 10, TimeUnit.SECONDS);// make
// it // longer than default internet service timeout
// longer socketTester = retry(injector.getInstance(SocketOpen.class), 300, 10, SECONDS);
// then successTester = retry(injector.getInstance(TaskSuccess.class), 650, 10, SECONDS);
// default internet
// service timeout
successTester = new RetryablePredicate<URI>(injector.getInstance(TaskSuccess.class), 650, 10, TimeUnit.SECONDS);
connection = (S) RestContext.class.cast(view.unwrap()).getApi(); connection = (S) RestContext.class.cast(view.unwrap()).getApi();
orgs = listOrgs(); orgs = listOrgs();
} }

View File

@ -18,12 +18,12 @@
*/ */
package org.jclouds.trmk.vcloud_0_8.internal; package org.jclouds.trmk.vcloud_0_8.internal;
import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeService;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.ssh.SshClient.Factory; import org.jclouds.ssh.SshClient.Factory;
import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.sshj.config.SshjSshClientModule;
@ -32,6 +32,7 @@ import org.jclouds.trmk.vcloud_0_8.TerremarkVCloudClient;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.net.HostAndPort; import com.google.common.net.HostAndPort;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Module; import com.google.inject.Module;
@ -51,7 +52,7 @@ public abstract class BaseTerremarkClientLiveTest<S extends TerremarkVCloudClien
provider = "trmk-ecloud"; provider = "trmk-ecloud";
} }
protected RetryablePredicate<HostAndPort> socketTester; protected Predicate<HostAndPort> socketTester;
protected Factory sshFactory; protected Factory sshFactory;
protected S connection; protected S connection;
@ -61,7 +62,7 @@ public abstract class BaseTerremarkClientLiveTest<S extends TerremarkVCloudClien
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
Injector injector = view.utils().injector(); Injector injector = view.utils().injector();
socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), 300, 1, TimeUnit.SECONDS); socketTester = retry(new InetSocketAddressConnect(), 300, 1, SECONDS);
sshFactory = injector.getInstance(Factory.class); sshFactory = injector.getInstance(Factory.class);
connection = (S) RestContext.class.cast(view.unwrap()).getApi(); connection = (S) RestContext.class.cast(view.unwrap()).getApi();
} }

View File

@ -19,8 +19,9 @@
package org.jclouds.compute.callables; package org.jclouds.compute.callables;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.util.Date;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -34,7 +35,6 @@ import org.jclouds.compute.events.StatementOnNodeCompletion;
import org.jclouds.compute.events.StatementOnNodeFailure; import org.jclouds.compute.events.StatementOnNodeFailure;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.scriptbuilder.InitScript; import org.jclouds.scriptbuilder.InitScript;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
@ -80,7 +80,7 @@ public class BlockUntilInitScriptStatusIsZeroThenReturnOutput extends AbstractFu
ComputeServiceConstants.InitStatusProperties properties, @Assisted SudoAwareInitManager commandRunner) { ComputeServiceConstants.InitStatusProperties properties, @Assisted SudoAwareInitManager commandRunner) {
this(userExecutor, eventBus, Predicates.<String> alwaysTrue(), commandRunner); this(userExecutor, eventBus, Predicates.<String> alwaysTrue(), commandRunner);
// this is mutable only until we can determine how to decouple "this" from here // this is mutable only until we can determine how to decouple "this" from here
notRunningAnymore = new LoopUntilTrueOrThrowCancellationException(new ExitStatusOfCommandGreaterThanZero( notRunningAnymore = loopUntilTrueOrThrowCancellationException(new ExitStatusOfCommandGreaterThanZero(
commandRunner), properties.initStatusMaxPeriod, properties.initStatusInitialPeriod, this); commandRunner), properties.initStatusMaxPeriod, properties.initStatusInitialPeriod, this);
} }
@ -108,28 +108,19 @@ public class BlockUntilInitScriptStatusIsZeroThenReturnOutput extends AbstractFu
} }
@VisibleForTesting /**
static class LoopUntilTrueOrThrowCancellationException extends RetryablePredicate<String> { * make sure we stop the retry loop if someone cancelled the future, this keeps threads from
* being consumed on dead tasks
private final AbstractFuture<ExecResponse> futureWhichMightBeCancelled; */
static Predicate<String> loopUntilTrueOrThrowCancellationException(Predicate<String> predicate, long period, long maxPeriod,
public LoopUntilTrueOrThrowCancellationException(Predicate<String> predicate, long period, long maxPeriod, final AbstractFuture<ExecResponse> futureWhichMightBeCancelled) {
AbstractFuture<ExecResponse> futureWhichMightBeCancelled) { return retry(Predicates.<String> and(predicate, new Predicate<String>(){
// arbitrarily high value, but Long.MAX_VALUE doesn't work! public boolean apply(String in) {
super(predicate, TimeUnit.DAYS.toMillis(365), period, maxPeriod, TimeUnit.MILLISECONDS); if (futureWhichMightBeCancelled.isCancelled())
this.futureWhichMightBeCancelled = futureWhichMightBeCancelled; throw new CancellationException(futureWhichMightBeCancelled + " is cancelled");
} return true;
}
/** }), period, maxPeriod, MILLISECONDS);
* make sure we stop the retry loop if someone cancelled the future, this keeps threads from
* being consumed on dead tasks
*/
@Override
protected boolean atOrAfter(Date end) {
if (futureWhichMightBeCancelled.isCancelled())
throw new CancellationException(futureWhichMightBeCancelled + " is cancelled");
return super.atOrAfter(end);
}
} }
/** /**

View File

@ -24,6 +24,7 @@ import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_R
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_SCRIPT_COMPLETE; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_SCRIPT_COMPLETE;
import static org.jclouds.util.Predicates2.retry;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -42,7 +43,6 @@ import org.jclouds.compute.predicates.ScriptStatusReturnsZero;
import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient; import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient;
import org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod; import org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -61,67 +61,55 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
@Named(TIMEOUT_NODE_RUNNING) @Named(TIMEOUT_NODE_RUNNING)
protected Predicate<AtomicReference<NodeMetadata>> nodeRunning( protected Predicate<AtomicReference<NodeMetadata>> nodeRunning(AtomicNodeRunning statusRunning, Timeouts timeouts,
AtomicNodeRunning statusRunning, Timeouts timeouts, PollPeriod period) { PollPeriod period) {
return timeouts.nodeRunning == 0 ? return timeouts.nodeRunning == 0 ? statusRunning : RetryablePredicateGuardingNull.create(statusRunning,
statusRunning : timeouts.nodeRunning, period.pollInitialPeriod, period.pollMaxPeriod);
new RetryablePredicateGuardingNull<NodeMetadata>(
statusRunning, timeouts.nodeRunning, period.pollInitialPeriod, period.pollMaxPeriod);
} }
@Provides @Provides
@Singleton @Singleton
@Named(TIMEOUT_NODE_TERMINATED) @Named(TIMEOUT_NODE_TERMINATED)
protected Predicate<AtomicReference<NodeMetadata>> serverTerminated( protected Predicate<AtomicReference<NodeMetadata>> serverTerminated(AtomicNodeTerminated statusTerminated,
AtomicNodeTerminated statusTerminated, Timeouts timeouts, PollPeriod period) { Timeouts timeouts, PollPeriod period) {
return timeouts.nodeTerminated == 0 ? return timeouts.nodeTerminated == 0 ? statusTerminated : retry(statusTerminated, timeouts.nodeTerminated,
statusTerminated : period.pollInitialPeriod, period.pollMaxPeriod);
new RetryablePredicate<AtomicReference<NodeMetadata>>(
statusTerminated, timeouts.nodeTerminated, period.pollInitialPeriod, period.pollMaxPeriod);
} }
@Provides @Provides
@Singleton @Singleton
@Named(TIMEOUT_NODE_SUSPENDED) @Named(TIMEOUT_NODE_SUSPENDED)
protected Predicate<AtomicReference<NodeMetadata>> serverSuspended( protected Predicate<AtomicReference<NodeMetadata>> serverSuspended(AtomicNodeSuspended statusSuspended,
AtomicNodeSuspended statusSuspended, Timeouts timeouts, PollPeriod period) { Timeouts timeouts, PollPeriod period) {
return timeouts.nodeSuspended == 0 ? return timeouts.nodeSuspended == 0 ? statusSuspended : RetryablePredicateGuardingNull.create(statusSuspended,
statusSuspended : timeouts.nodeSuspended, period.pollInitialPeriod, period.pollMaxPeriod);
new RetryablePredicateGuardingNull<NodeMetadata>(
statusSuspended, timeouts.nodeSuspended, period.pollInitialPeriod, period.pollMaxPeriod);
} }
@Provides @Provides
@Singleton @Singleton
@Named(TIMEOUT_SCRIPT_COMPLETE) @Named(TIMEOUT_SCRIPT_COMPLETE)
protected Predicate<CommandUsingClient> runScriptRunning(ScriptStatusReturnsZero statusRunning, Timeouts timeouts) { protected Predicate<CommandUsingClient> runScriptRunning(ScriptStatusReturnsZero statusRunning, Timeouts timeouts) {
return timeouts.scriptComplete == 0 ? not(statusRunning) : new RetryablePredicate<CommandUsingClient>( return timeouts.scriptComplete == 0 ? not(statusRunning) : retry(not(statusRunning), timeouts.scriptComplete);
not(statusRunning), timeouts.scriptComplete);
} }
@Provides @Provides
@Singleton @Singleton
@Named(TIMEOUT_IMAGE_AVAILABLE) @Named(TIMEOUT_IMAGE_AVAILABLE)
protected Predicate<AtomicReference<Image>> imageAvailable( protected Predicate<AtomicReference<Image>> imageAvailable(AtomicImageAvailable statusAvailable, Timeouts timeouts,
AtomicImageAvailable statusAvailable, Timeouts timeouts, PollPeriod period) { PollPeriod period) {
return timeouts.imageAvailable == 0 ? return timeouts.imageAvailable == 0 ? statusAvailable : retry(statusAvailable, timeouts.imageAvailable,
statusAvailable : period.pollInitialPeriod, period.pollMaxPeriod);
new RetryablePredicateGuardingNull<Image>(
statusAvailable, timeouts.imageAvailable, period.pollInitialPeriod, period.pollMaxPeriod);
} }
@Provides @Provides
@Singleton @Singleton
@Named(TIMEOUT_IMAGE_DELETED) @Named(TIMEOUT_IMAGE_DELETED)
protected Predicate<AtomicReference<Image>> serverDeleted( protected Predicate<AtomicReference<Image>> serverDeleted(AtomicImageDeleted statusDeleted, Timeouts timeouts,
AtomicImageDeleted statusDeleted, Timeouts timeouts, PollPeriod period) { PollPeriod period) {
return timeouts.imageDeleted == 0 ? return timeouts.imageDeleted == 0 ? statusDeleted : retry(statusDeleted, timeouts.imageDeleted,
statusDeleted : period.pollInitialPeriod, period.pollMaxPeriod);
new RetryablePredicate<AtomicReference<Image>>(
statusDeleted, timeouts.imageDeleted, period.pollInitialPeriod, period.pollMaxPeriod);
} }
@Override @Override
protected void configure() { protected void configure() {
bind(new TypeLiteral<Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>>>() { bind(new TypeLiteral<Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>>>() {
@ -136,6 +124,11 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
* @author Aled Sage * @author Aled Sage
*/ */
private static class RetryablePredicateGuardingNull<T> implements Predicate<AtomicReference<T>> { private static class RetryablePredicateGuardingNull<T> implements Predicate<AtomicReference<T>> {
private static <T> RetryablePredicateGuardingNull<T> create(Predicate<AtomicReference<T>> predicate, long maxWait, long period, long maxPeriod) {
return new RetryablePredicateGuardingNull<T>(predicate, maxWait, period, maxPeriod);
}
private class AtomicRefAndOrig { private class AtomicRefAndOrig {
private final T orig; private final T orig;
private final AtomicReference<T> ref; private final AtomicReference<T> ref;
@ -146,9 +139,9 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
} }
} }
private final RetryablePredicate<AtomicRefAndOrig> retryablePredicate; private final Predicate<AtomicRefAndOrig> retryablePredicate;
public RetryablePredicateGuardingNull(final Predicate<AtomicReference<T>> predicate, long maxWait, long period, long maxPeriod) { private RetryablePredicateGuardingNull(final Predicate<AtomicReference<T>> predicate, long maxWait, long period, long maxPeriod) {
Predicate<AtomicRefAndOrig> nonNullThingPredicate = new Predicate<AtomicRefAndOrig>() { Predicate<AtomicRefAndOrig> nonNullThingPredicate = new Predicate<AtomicRefAndOrig>() {
@Override @Override
public boolean apply(AtomicRefAndOrig input) { public boolean apply(AtomicRefAndOrig input) {
@ -160,7 +153,7 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
} }
} }
}; };
retryablePredicate = new RetryablePredicate<AtomicRefAndOrig>(nonNullThingPredicate, maxWait, period, maxPeriod); retryablePredicate = retry(nonNullThingPredicate, maxWait, period, maxPeriod);
} }
@Override @Override

View File

@ -26,6 +26,7 @@ import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Maps.newLinkedHashMap; import static com.google.common.collect.Maps.newLinkedHashMap;
import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.Sets.newLinkedHashSet;
import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.Futures.immediateFuture;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;
@ -34,12 +35,12 @@ import static org.jclouds.compute.predicates.NodePredicates.all;
import static org.jclouds.compute.util.ComputeServiceUtils.formatStatus; import static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;
import static org.jclouds.concurrent.FutureIterables.awaitCompletion; import static org.jclouds.concurrent.FutureIterables.awaitCompletion;
import static org.jclouds.concurrent.FutureIterables.transformParallel; import static org.jclouds.concurrent.FutureIterables.transformParallel;
import static org.jclouds.util.Predicates2.retry;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -87,7 +88,6 @@ import org.jclouds.domain.LoginCredentials;
import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.domain.LoginCredentials.Builder;
import org.jclouds.javax.annotation.Nullable; import org.jclouds.javax.annotation.Nullable;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.scriptbuilder.domain.Statements; import org.jclouds.scriptbuilder.domain.Statements;
import org.jclouds.scriptbuilder.functions.InitAdminAccess; import org.jclouds.scriptbuilder.functions.InitAdminAccess;
@ -289,9 +289,7 @@ public class BaseComputeService implements ComputeService {
checkNotNull(id, "id"); checkNotNull(id, "id");
logger.debug(">> destroying node(%s)", id); logger.debug(">> destroying node(%s)", id);
final AtomicReference<NodeMetadata> node = Atomics.newReference(); final AtomicReference<NodeMetadata> node = Atomics.newReference();
RetryablePredicate<String> tester = new RetryablePredicate<String>(new Predicate<String>() { Predicate<String> tester = retry(new Predicate<String>() {
@Override
public boolean apply(String input) { public boolean apply(String input) {
try { try {
NodeMetadata md = destroyNodeStrategy.destroyNode(id); NodeMetadata md = destroyNodeStrategy.destroyNode(id);
@ -303,8 +301,7 @@ public class BaseComputeService implements ComputeService {
return false; return false;
} }
} }
}, timeouts.nodeTerminated, 1000, MILLISECONDS);
}, timeouts.nodeTerminated, 1000, TimeUnit.MILLISECONDS);
boolean successful = tester.apply(id) && (node.get() == null || nodeTerminated.apply(node)); boolean successful = tester.apply(id) && (node.get() == null || nodeTerminated.apply(node));
if (successful) if (successful)

View File

@ -17,16 +17,15 @@
* under the License. * under the License.
*/ */
package org.jclouds.compute.reference; package org.jclouds.compute.reference;
import static org.jclouds.compute.config.ComputeServiceProperties.BLACKLIST_NODES; import static org.jclouds.compute.config.ComputeServiceProperties.BLACKLIST_NODES;
import static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_AUTHENTICATE_SUDO; import static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_AUTHENTICATE_SUDO;
import static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_ID; import static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_ID;
import static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_LOGIN_USER; import static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_LOGIN_USER;
import static org.jclouds.compute.config.ComputeServiceProperties.INIT_STATUS_INITIAL_PERIOD; import static org.jclouds.compute.config.ComputeServiceProperties.INIT_STATUS_INITIAL_PERIOD;
import static org.jclouds.compute.config.ComputeServiceProperties.INIT_STATUS_MAX_PERIOD; import static org.jclouds.compute.config.ComputeServiceProperties.INIT_STATUS_MAX_PERIOD;
import static org.jclouds.compute.config.ComputeServiceProperties.OS_VERSION_MAP_JSON;
import static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD; import static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD;
import static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD; import static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD;
import static org.jclouds.compute.config.ComputeServiceProperties.OS_VERSION_MAP_JSON;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_DELETED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_DELETED;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;
@ -41,7 +40,8 @@ import java.util.concurrent.TimeUnit;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.compute.config.ComputeServiceProperties;
import org.jclouds.util.Predicates2;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.inject.Inject; import com.google.inject.Inject;
@ -145,11 +145,11 @@ public interface ComputeServiceConstants {
public static class PollPeriod { public static class PollPeriod {
@Inject(optional = true) @Inject(optional = true)
@Named(POLL_INITIAL_PERIOD) @Named(POLL_INITIAL_PERIOD)
public long pollInitialPeriod = RetryablePredicate.DEFAULT_PERIOD; public long pollInitialPeriod = Predicates2.DEFAULT_PERIOD;
@Inject(optional = true) @Inject(optional = true)
@Named(POLL_MAX_PERIOD) @Named(POLL_MAX_PERIOD)
public long pollMaxPeriod = RetryablePredicate.DEFAULT_MAX_PERIOD; public long pollMaxPeriod = Predicates2.DEFAULT_MAX_PERIOD;
} }
@Singleton @Singleton

View File

@ -17,7 +17,6 @@
* under the License. * under the License.
*/ */
package org.jclouds.compute.util; package org.jclouds.compute.util;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.or; import static com.google.common.base.Predicates.or;
@ -29,6 +28,7 @@ import static com.google.common.util.concurrent.MoreExecutors.listeningDecorator
import static java.lang.String.format; import static java.lang.String.format;
import static org.jclouds.Constants.PROPERTY_USER_THREADS; import static org.jclouds.Constants.PROPERTY_USER_THREADS;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;
import static org.jclouds.util.Predicates2.retry;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@ -41,7 +41,6 @@ import javax.inject.Named;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
@ -78,7 +77,7 @@ public class ConcurrentOpenSocketFinder implements OpenSocketFinder {
} }
@Override @Override
public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeoutValue, TimeUnit timeUnits) { public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) {
ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node).transform(new Function<String, HostAndPort>() { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node).transform(new Function<String, HostAndPort>() {
@Override @Override
@ -95,20 +94,25 @@ public class ConcurrentOpenSocketFinder implements OpenSocketFinder {
Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node));
logger.debug(">> blocking on sockets %s for %d %s", sockets, timeoutValue, timeUnits); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits);
boolean passed = retryPredicate(findOrBreak, period, timeoutValue, timeUnits).apply(sockets); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets);
if (passed) { if (passed) {
logger.debug("<< socket %s opened", result); logger.debug("<< socket %s opened", result);
assert result.get() != null; assert result.get() != null;
return result.get(); return result.get();
} else { } else {
logger.warn("<< sockets %s didn't open after %d %s", sockets, timeoutValue, timeUnits); logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits);
throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node));
} }
} }
@VisibleForTesting
protected <T> Predicate<T> retryPredicate(Predicate<T> findOrBreak, long timeout, long period, TimeUnit timeUnits) {
return retry(findOrBreak, timeout, period, timeUnits);
}
/** /**
* Checks if any any of the given HostAndPorts are reachable. It checks them * Checks if any any of the given HostAndPorts are reachable. It checks them
* all concurrently, and sets reference to a {@link HostAndPort} if found or * all concurrently, and sets reference to a {@link HostAndPort} if found or
@ -173,16 +177,6 @@ public class ConcurrentOpenSocketFinder implements OpenSocketFinder {
}; };
} }
/**
* @param findOrBreak
* throws {@link IllegalStateException} in order to break the retry
* loop
*/
@VisibleForTesting
<T> Predicate<T> retryPredicate(Predicate<T> findOrBreak, long period, long timeoutValue, TimeUnit timeUnits) {
return new RetryablePredicate<T>(findOrBreak, timeoutValue, period, timeUnits);
}
private static FluentIterable<String> checkNodeHasIps(NodeMetadata node) { private static FluentIterable<String> checkNodeHasIps(NodeMetadata node) {
FluentIterable<String> ips = FluentIterable.from(concat(node.getPublicAddresses(), node.getPrivateAddresses())); FluentIterable<String> ips = FluentIterable.from(concat(node.getPublicAddresses(), node.getPrivateAddresses()));
checkState(size(ips) > 0, "node does not have IP addresses configured: " + node); checkState(size(ips) > 0, "node does not have IP addresses configured: " + node);

View File

@ -17,12 +17,13 @@
* under the License. * under the License.
*/ */
package org.jclouds.compute; package org.jclouds.compute;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reportMatcher; import static org.easymock.EasyMock.reportMatcher;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.io.IOException; import java.io.IOException;
@ -39,7 +40,6 @@ import org.jclouds.compute.util.OpenSocketFinder;
import org.jclouds.crypto.Pems; import org.jclouds.crypto.Pems;
import org.jclouds.domain.LoginCredentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.scriptbuilder.statements.login.AdminAccess; import org.jclouds.scriptbuilder.statements.login.AdminAccess;
@ -84,7 +84,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
replay(socketOpen); replay(socketOpen);
socketTester = new RetryablePredicate<HostAndPort>(socketOpen, 1, 1, TimeUnit.MILLISECONDS); socketTester = retry(socketOpen, 1, 1, MILLISECONDS);
openSocketFinder = new OpenSocketFinder(){ openSocketFinder = new OpenSocketFinder(){

View File

@ -17,11 +17,11 @@
* under the License. * under the License.
*/ */
package org.jclouds.compute.callables; package org.jclouds.compute.callables;
import static org.easymock.EasyMock.createMockBuilder; import static org.easymock.EasyMock.createMockBuilder;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify; import static org.easymock.EasyMock.verify;
import static org.jclouds.compute.callables.BlockUntilInitScriptStatusIsZeroThenReturnOutput.loopUntilTrueOrThrowCancellationException;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail; import static org.testng.Assert.fail;
@ -30,7 +30,6 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import org.jclouds.compute.callables.BlockUntilInitScriptStatusIsZeroThenReturnOutput.ExitStatusOfCommandGreaterThanZero; import org.jclouds.compute.callables.BlockUntilInitScriptStatusIsZeroThenReturnOutput.ExitStatusOfCommandGreaterThanZero;
import org.jclouds.compute.callables.BlockUntilInitScriptStatusIsZeroThenReturnOutput.LoopUntilTrueOrThrowCancellationException;
import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
@ -50,7 +49,7 @@ import com.google.common.util.concurrent.MoreExecutors;
@Test(groups = "unit", singleThreaded = true, testName = "BlockUntilInitScriptStatusIsZeroThenReturnOutputTest") @Test(groups = "unit", singleThreaded = true, testName = "BlockUntilInitScriptStatusIsZeroThenReturnOutputTest")
public class BlockUntilInitScriptStatusIsZeroThenReturnOutputTest { public class BlockUntilInitScriptStatusIsZeroThenReturnOutputTest {
public void testLoopUntilTrueOrThrowCancellationExceptionReturnsWhenPredicateIsTrue() { public void testloopUntilTrueOrThrowCancellationExceptionReturnsWhenPredicateIsTrue() {
AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() { AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() {
@Override @Override
@ -60,13 +59,13 @@ public class BlockUntilInitScriptStatusIsZeroThenReturnOutputTest {
}; };
LoopUntilTrueOrThrowCancellationException pred = new LoopUntilTrueOrThrowCancellationException(Predicates Predicate<String> pred = loopUntilTrueOrThrowCancellationException(Predicates
.<String> alwaysTrue(), 1, 1, future); .<String> alwaysTrue(), 1, 1, future);
assertEquals(pred.apply("foo"), true); assertEquals(pred.apply("foo"), true);
} }
public void testLoopUntilTrueOrThrowCancellationExceptionReturnsWhenPredicateIsTrueSecondTimeWhileNotCancelled() { public void testloopUntilTrueOrThrowCancellationExceptionReturnsWhenPredicateIsTrueSecondTimeWhileNotCancelled() {
AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() { AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() {
@Override @Override
@ -86,14 +85,13 @@ public class BlockUntilInitScriptStatusIsZeroThenReturnOutputTest {
}; };
LoopUntilTrueOrThrowCancellationException pred = new LoopUntilTrueOrThrowCancellationException(predicate, 1, 1, Predicate<String> pred = loopUntilTrueOrThrowCancellationException(predicate, 1, 1, future);
future);
assertEquals(pred.apply("foo"), true); assertEquals(pred.apply("foo"), true);
} }
// need to break the loop when cancelled. // need to break the loop when cancelled.
public void testLoopUntilTrueOrThrowCancellationExceptionSkipsAndReturnsFalseOnCancelled() { public void testloopUntilTrueOrThrowCancellationExceptionSkipsAndReturnsFalseOnCancelled() {
AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() { AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() {
@Override @Override
@ -102,8 +100,8 @@ public class BlockUntilInitScriptStatusIsZeroThenReturnOutputTest {
} }
}; };
LoopUntilTrueOrThrowCancellationException pred = new LoopUntilTrueOrThrowCancellationException(Predicates Predicate<String> pred = loopUntilTrueOrThrowCancellationException(Predicates.<String> alwaysFalse(), 1, 1,
.<String> alwaysFalse(), 1, 1, future); future);
assertEquals(pred.apply("foo"), false); assertEquals(pred.apply("foo"), false);
} }

View File

@ -19,11 +19,12 @@
package org.jclouds.compute.extensions.internal; package org.jclouds.compute.extensions.internal;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Named; import javax.inject.Named;
@ -38,7 +39,6 @@ import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -46,6 +46,7 @@ import com.google.common.base.Optional;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
/** /**
* Base test for {@link ImageExtension} implementations. * Base test for {@link ImageExtension} implementations.
* *
@ -174,7 +175,7 @@ public abstract class BaseImageExtensionLiveTest extends BaseComputeServiceConte
private void checkReachable(NodeMetadata node) { private void checkReachable(NodeMetadata node) {
SshClient client = view.utils().sshForNode().apply(node); SshClient client = view.utils().sshForNode().apply(node);
assertTrue(new RetryablePredicate<SshClient>(new Predicate<SshClient>() { assertTrue(retry(new Predicate<SshClient>() {
@Override @Override
public boolean apply(SshClient input) { public boolean apply(SshClient input) {
input.connect(); input.connect();
@ -183,6 +184,6 @@ public abstract class BaseImageExtensionLiveTest extends BaseComputeServiceConte
} }
return false; return false;
} }
}, getSpawnNodeMaxWait(), 1l, TimeUnit.SECONDS).apply(client)); }, getSpawnNodeMaxWait(), 1l, SECONDS).apply(client));
} }
} }

View File

@ -17,7 +17,6 @@
* under the License. * under the License.
*/ */
package org.jclouds.compute.internal; package org.jclouds.compute.internal;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not; import static com.google.common.base.Predicates.not;
@ -30,6 +29,7 @@ import static com.google.common.collect.Sets.filter;
import static com.google.common.collect.Sets.newTreeSet; import static com.google.common.collect.Sets.newTreeSet;
import static java.lang.String.format; import static java.lang.String.format;
import static java.lang.System.currentTimeMillis; import static java.lang.System.currentTimeMillis;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.logging.Logger.getAnonymousLogger; import static java.util.logging.Logger.getAnonymousLogger;
import static org.jclouds.compute.options.RunScriptOptions.Builder.nameTask; import static org.jclouds.compute.options.RunScriptOptions.Builder.nameTask;
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;
@ -41,6 +41,7 @@ import static org.jclouds.compute.predicates.NodePredicates.all;
import static org.jclouds.compute.predicates.NodePredicates.inGroup; import static org.jclouds.compute.predicates.NodePredicates.inGroup;
import static org.jclouds.compute.predicates.NodePredicates.runningInGroup; import static org.jclouds.compute.predicates.NodePredicates.runningInGroup;
import static org.jclouds.compute.util.ComputeServiceUtils.getCores; import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail; import static org.testng.Assert.fail;
@ -82,7 +83,6 @@ import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
@ -154,7 +154,7 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte
protected void buildSocketTester() { protected void buildSocketTester() {
SocketOpen socketOpen = view.utils().injector().getInstance(SocketOpen.class); SocketOpen socketOpen = view.utils().injector().getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<HostAndPort>(socketOpen, 60, 1, TimeUnit.SECONDS); socketTester = retry(socketOpen, 60, 1, SECONDS);
// wait a maximum of 60 seconds for port 8080 to open. // wait a maximum of 60 seconds for port 8080 to open.
openSocketFinder = context.utils().injector().getInstance(OpenSocketFinder.class); openSocketFinder = context.utils().injector().getInstance(OpenSocketFinder.class);
} }

View File

@ -134,7 +134,7 @@ public class ConcurrentOpenSocketFinderTest {
OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysClosed, nodeNotRunning, userExecutor) { OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysClosed, nodeNotRunning, userExecutor) {
@Override @Override
protected <T> Predicate<T> retryPredicate(final Predicate<T> findOrBreak, long period, long timeoutValue, protected <T> Predicate<T> retryPredicate(final Predicate<T> findOrBreak, long timeout, long period,
TimeUnit timeUnits) { TimeUnit timeUnits) {
return new Predicate<T>() { return new Predicate<T>() {
@Override @Override

View File

@ -1,66 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.predicates;
import java.util.concurrent.Callable;
import com.google.common.annotations.Beta;
/** Provides a facility to convert an arbitrary Callable to a Predicate, implementing PredicateWithResult,
* for use e.g. with Retryables.retryGetting... methods */
@Beta
public abstract class PredicateCallable<Result> implements PredicateWithResult<Void, Result>, Callable<Result> {
Result lastResult;
Exception lastFailure;
@Override
public boolean apply(Void input) {
try {
lastResult = call();
onCompletion();
return isAcceptable(lastResult);
} catch (Exception e) {
lastFailure = e;
onFailure();
return false;
}
}
protected void onFailure() {
}
protected void onCompletion() {
}
protected boolean isAcceptable(Result result) {
return result!=null;
}
@Override
public Result getResult() {
return lastResult;
}
@Override
public Throwable getLastFailure() {
return lastFailure;
}
}

View File

@ -1,31 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.predicates;
import com.google.common.annotations.Beta;
import com.google.common.base.Predicate;
@Beta
public interface PredicateWithResult<Input,Result> extends Predicate<Input> {
Result getResult();
Throwable getLastFailure();
}

View File

@ -1,112 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.predicates;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.util.Throwables2.getFirstThrowableOfType;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Resource;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
/**
*
* Retries a condition until it is met or the max number of retries have occurred.
* maxAttempts parameter is required.
* Initial retry period and retry maxPeriod are optionally configurable,
* defaulting to 50ms and 1000ms respectively,
* with the retrier increasing the interval by a factor of 1.5 each time within these constraints.
*
* @author Aled Sage
*/
public class RetryableNumTimesPredicate<T> implements Predicate<T> {
private final int maxAttempts;
private final long period;
private final long maxPeriod;
private final Predicate<T> predicate;
@Resource
protected Logger logger = Logger.NULL;
public RetryableNumTimesPredicate(Predicate<T> predicate, int maxAttempts, long period, long maxPeriod, TimeUnit unit) {
this.predicate = checkNotNull(predicate);
this.maxAttempts = maxAttempts;
this.period = unit.toMillis(period);
this.maxPeriod = unit.toMillis(maxPeriod);
checkArgument(maxAttempts >= 0, "maxAttempts must be greater than zero, but was "+maxAttempts);
checkArgument(period >= 0, "period must be greater than zero, but was "+period);
checkArgument(maxPeriod >= 0, "maxPeriod must be greater than zero, but was "+maxPeriod);
checkArgument(maxPeriod >= period, "maxPeriod must be greater than or equal to period, but was "+maxPeriod+" < "+period);
}
public RetryableNumTimesPredicate(Predicate<T> predicate, int maxAttempts, long period, TimeUnit unit) {
this(predicate, maxAttempts, period, period*10, unit);
}
public RetryableNumTimesPredicate(Predicate<T> predicate, int maxAttempts) {
this(predicate, maxAttempts, 50l, 1000l, TimeUnit.MILLISECONDS);
}
@Override
public boolean apply(T input) {
try {
for (int i = 1; i <= maxAttempts; Thread.sleep(nextMaxInterval(i++))) {
if (predicate.apply(input)) {
return true;
}
}
return false;
} catch (InterruptedException e) {
logger.warn(e, "predicate %s on %s interrupted, returning false", input, predicate);
Thread.currentThread().interrupt();
} catch (RuntimeException e) {
if (getFirstThrowableOfType(e, ExecutionException.class) != null) {
logger.warn(e, "predicate %s on %s errored [%s], returning false", input, predicate, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, IllegalStateException.class) != null) {
logger.warn(e, "predicate %s on %s illegal state [%s], returning false", input, predicate, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, CancellationException.class) != null) {
logger.warn(e, "predicate %s on %s cancelled [%s], returning false", input, predicate, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, TimeoutException.class) != null) {
logger.warn(e, "predicate %s on %s timed out [%s], returning false", input, predicate, e.getMessage());
return false;
} else
throw e;
}
return false;
}
protected long nextMaxInterval(long attempt) {
// Interval increases exponentially, at a rate of nextInterval *= 1.5
// Note that attempt starts counting at 1
long interval = (long) (period * Math.pow(1.5, attempt - 1));
return interval > maxPeriod ? maxPeriod : interval;
}
}

View File

@ -1,127 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.predicates;
import static org.jclouds.util.Throwables2.getFirstThrowableOfType;
import java.util.Date;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Resource;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
/**
*
* Retries a condition until it is met or a timeout occurs.
* maxWait parameter is required.
* Initial retry period and retry maxPeriod are optionally configurable,
* defaulting to 50ms and 1000ms respectively,
* with the retrier increasing the interval by a factor of 1.5 each time within these constraints.
* All values taken as millis unless TimeUnit specified.
*
* @author Adrian Cole
*/
public class RetryablePredicate<T> implements Predicate<T> {
public static final long DEFAULT_PERIOD = 50l;
public static final long DEFAULT_MAX_PERIOD = 1000l;
private final long maxWait;
private final long period;
private final long maxPeriod;
private final Predicate<T> predicate;
@Resource
protected Logger logger = Logger.NULL;
public RetryablePredicate(Predicate<T> predicate, long maxWait, long period, long maxPeriod, TimeUnit unit) {
this.predicate = predicate;
this.maxWait = unit.toMillis(maxWait);
this.period = unit.toMillis(period);
this.maxPeriod = unit.toMillis(maxPeriod);
}
public RetryablePredicate(Predicate<T> predicate, long maxWait, long period, TimeUnit unit) {
this(predicate, maxWait, period, period * 10l, unit);
}
public RetryablePredicate(Predicate<T> predicate, long maxWait, long period, long maxPeriod) {
this(predicate, maxWait, period, maxPeriod, TimeUnit.MILLISECONDS);
}
public RetryablePredicate(Predicate<T> predicate, long maxWait) {
this(predicate, maxWait, DEFAULT_PERIOD, DEFAULT_MAX_PERIOD, TimeUnit.MILLISECONDS);
}
@Override
public boolean apply(T input) {
try {
long i = 1l;
for (Date end = new Date(System.currentTimeMillis() + maxWait); before(end); Thread.sleep(nextMaxInterval(i++,
end))) {
if (predicate.apply(input)) {
return true;
} else if (atOrAfter(end)) {
return false;
}
}
} catch (InterruptedException e) {
logger.warn(e, "predicate %s on %s interrupted, returning false", input, predicate);
Thread.currentThread().interrupt();
} catch (RuntimeException e) {
if (getFirstThrowableOfType(e, ExecutionException.class) != null) {
logger.warn(e, "predicate %s on %s errored [%s], returning false", input, predicate, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, IllegalStateException.class) != null) {
logger.warn(e, "predicate %s on %s illegal state [%s], returning false", input, predicate, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, CancellationException.class) != null) {
logger.warn(e, "predicate %s on %s cancelled [%s], returning false", input, predicate, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, TimeoutException.class) != null) {
logger.warn(e, "predicate %s on %s timed out [%s], returning false", input, predicate, e.getMessage());
return false;
} else
throw e;
}
return false;
}
protected long nextMaxInterval(long attempt, Date end) {
// Interval increases exponentially, at a rate of nextInterval *= 1.5
// Note that attempt starts counting at 1
long interval = (long) (period * Math.pow(1.5, attempt - 1));
interval = interval > maxPeriod ? maxPeriod : interval;
long max = end.getTime() - System.currentTimeMillis();
return (interval > max) ? max : interval;
}
protected boolean before(Date end) {
return new Date().compareTo(end) <= 1;
}
protected boolean atOrAfter(Date end) {
return new Date().compareTo(end) >= 0;
}
}

View File

@ -1,69 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.predicates;
import java.util.concurrent.TimeUnit;
import com.google.common.annotations.Beta;
import com.google.common.base.Predicate;
/** convenience methods to retry application of a predicate, and optionally (reducing quite a bit of boilerplate)
* get the final result or throw assertion error
*
* @author alex heneveld
*/
@Beta
public class Retryables {
public static <Input> boolean retry(Predicate<Input> predicate, Input input, long maxWaitMillis) {
return new RetryablePredicate<Input>(predicate, maxWaitMillis).apply(input);
}
public static <Input> boolean retry(Predicate<Input> predicate, Input input, long maxWait, long period, TimeUnit unit) {
return new RetryablePredicate<Input>(predicate, maxWait, period, unit).apply(input);
}
public static <Input> boolean retryNumTimes(Predicate<Input> predicate, Input input, int maxAttempts) {
return new RetryableNumTimesPredicate<Input>(predicate, maxAttempts).apply(input);
}
public static <Input> boolean retryNumTimes(Predicate<Input> predicate, Input input, int maxAttempts, long period, long maxPeriod, TimeUnit unit) {
return new RetryableNumTimesPredicate<Input>(predicate, maxAttempts, period, maxPeriod, unit).apply(input);
}
public static <Input> void assertEventually(Predicate<Input> predicate, Input input,
long maxWaitMillis, String failureMessage) {
if (!new RetryablePredicate<Input>(predicate, maxWaitMillis).apply(input))
throw new AssertionError(failureMessage);
}
public static <Input,Result> Result retryGettingResultOrFailing(PredicateWithResult<Input,Result> predicate,
Input input, long maxWaitMillis, String failureMessage) {
if (!new RetryablePredicate<Input>(predicate, maxWaitMillis).apply(input))
throw (AssertionError)new AssertionError(failureMessage).initCause(predicate.getLastFailure());
return predicate.getResult();
}
public static <Input,Result> Result retryGettingResultOrFailing(PredicateWithResult<Input,Result> predicate,
Input input, long maxWait, long period, TimeUnit unit, String failureMessage) {
if (!new RetryablePredicate<Input>(predicate, maxWait, period, unit).apply(input))
throw (AssertionError)new AssertionError(failureMessage).initCause(predicate.getLastFailure());
return predicate.getResult();
}
}

View File

@ -18,6 +18,19 @@
*/ */
package org.jclouds.util; package org.jclouds.util;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.util.Throwables2.getFirstThrowableOfType;
import java.util.Date;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Resource;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
public class Predicates2 { public class Predicates2 {
@ -35,4 +48,105 @@ public class Predicates2 {
} }
}; };
} }
/**
* Retries a predicate until it is met, a timeout occurs, or an exception occurs.
*/
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod,
TimeUnit unit) {
return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit);
}
/**
* like {@link #retry(Predicate, long, long, long, TimeUnit)} where {@code maxPeriod} is 10x {@code period}
*/
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit) {
return retry(findOrBreak, timeout, period, period * 10l, unit);
}
/**
* like {@link #retry(Predicate, long, long, long, TimeUnit)} where {@code unit} is in milliseconds
*/
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod) {
return retry(findOrBreak, timeout, period, maxPeriod, MILLISECONDS);
}
public static final long DEFAULT_PERIOD = 50l;
public static final long DEFAULT_MAX_PERIOD = 1000l;
/**
* like {@link #retry(Predicate, long, long, long, TimeUnit)} where {@code unit} is in milliseconds, {@code period}
* is 50ms, and {@code maxPeriod} 1s.
*/
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout) {
return retry(findOrBreak, timeout, DEFAULT_PERIOD, DEFAULT_MAX_PERIOD, MILLISECONDS);
}
private static class RetryablePredicate<T> implements Predicate<T> {
private final long timeout;
private final long period;
private final long maxPeriod;
private final Predicate<T> findOrBreak;
@Resource
protected Logger logger = Logger.NULL;
protected RetryablePredicate(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) {
this.findOrBreak = findOrBreak;
this.timeout = unit.toMillis(timeout);
this.period = unit.toMillis(period);
this.maxPeriod = unit.toMillis(maxPeriod);
}
@Override
public boolean apply(T input) {
try {
long i = 1l;
for (Date end = new Date(System.currentTimeMillis() + timeout); before(end); Thread.sleep(nextMaxInterval(i++,
end))) {
if (findOrBreak.apply(input)) {
return true;
} else if (atOrAfter(end)) {
return false;
}
}
} catch (InterruptedException e) {
logger.warn(e, "predicate %s on %s interrupted, returning false", input, findOrBreak);
Thread.currentThread().interrupt();
} catch (RuntimeException e) {
if (getFirstThrowableOfType(e, ExecutionException.class) != null) {
logger.warn(e, "predicate %s on %s errored [%s], returning false", input, findOrBreak, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, IllegalStateException.class) != null) {
logger.warn(e, "predicate %s on %s illegal state [%s], returning false", input, findOrBreak, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, CancellationException.class) != null) {
logger.warn(e, "predicate %s on %s cancelled [%s], returning false", input, findOrBreak, e.getMessage());
return false;
} else if (getFirstThrowableOfType(e, TimeoutException.class) != null) {
logger.warn(e, "predicate %s on %s timed out [%s], returning false", input, findOrBreak, e.getMessage());
return false;
} else
throw e;
}
return false;
}
protected long nextMaxInterval(long attempt, Date end) {
// Interval increases exponentially, at a rate of nextInterval *= 1.5
// Note that attempt starts counting at 1
long interval = (long) (period * Math.pow(1.5, attempt - 1));
interval = interval > maxPeriod ? maxPeriod : interval;
long max = end.getTime() - System.currentTimeMillis();
return (interval > max) ? max : interval;
}
protected boolean before(Date end) {
return new Date().compareTo(end) <= 1;
}
protected boolean atOrAfter(Date end) {
return new Date().compareTo(end) >= 0;
}
}
} }

View File

@ -1,170 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.predicates;
import static org.jclouds.predicates.RetryablePredicateTest.assertCallTimes;
import static org.testng.Assert.fail;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jclouds.predicates.RetryablePredicateTest.RepeatedAttemptsPredicate;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Stopwatch;
import com.google.common.base.Supplier;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", singleThreaded = true)
public class RetryableNumTimesPredicateTest {
// Grace must be reasonably big; Thread.sleep can take a bit longer to wake up sometimes...
public static int SLOW_BUILD_SERVER_GRACE = 250;
// Sometimes returns sooner than timer would predict (e.g. observed 2999ms, when expected 3000ms)
public static int EARLY_RETURN_GRACE = 10;
private Stopwatch stopwatch;
@BeforeMethod
public void setUp() {
stopwatch = new Stopwatch();
}
@Test
void testFalseOnIllegalStateExeception() {
ensureImmediateReturnFor(new IllegalStateException());
}
@SuppressWarnings("serial")
@Test
void testFalseOnExecutionException() {
ensureImmediateReturnFor(new ExecutionException() {
});
}
@SuppressWarnings("serial")
@Test
void testFalseOnTimeoutException() {
ensureImmediateReturnFor(new TimeoutException() {
});
}
@SuppressWarnings("serial")
@Test(expectedExceptions = RuntimeException.class)
void testPropagateOnException() {
ensureImmediateReturnFor(new Exception() {
});
}
private void ensureImmediateReturnFor(final Exception ex) {
RetryableNumTimesPredicate<Supplier<String>> predicate = new RetryableNumTimesPredicate<Supplier<String>>(
new Predicate<Supplier<String>>() {
@Override
public boolean apply(Supplier<String> input) {
return "goo".equals(input.get());
}
}, 3, 1L, TimeUnit.SECONDS);
stopwatch.start();
assert !predicate.apply(new Supplier<String>() {
@Override
public String get() {
throw new RuntimeException(ex);
}
});
long duration = stopwatch.elapsedMillis();
assertOrdered(duration, SLOW_BUILD_SERVER_GRACE);
}
@Test
void testAlwaysTrue() {
// will call once immediately
RetryableNumTimesPredicate<String> predicate = new RetryableNumTimesPredicate<String>(Predicates.<String> alwaysTrue(),
1, 1L, TimeUnit.SECONDS);
stopwatch.start();
predicate.apply("");
long duration = stopwatch.elapsedMillis();
assertOrdered(duration, SLOW_BUILD_SERVER_GRACE);
}
@Test
void testAlwaysFalseMillis() {
// maxAttempts=3; period=1; maxPeriod defaults to 1*10
// will call at 0, 1, 1+(1*1.5) = 2.5secs
RetryableNumTimesPredicate<String> predicate = new RetryableNumTimesPredicate<String>(Predicates.<String> alwaysFalse(),
3, 1L, TimeUnit.SECONDS);
stopwatch.start();
predicate.apply("");
long duration = stopwatch.elapsedMillis();
assertOrdered(2500-EARLY_RETURN_GRACE, duration, 2500+SLOW_BUILD_SERVER_GRACE);
}
@Test
void testThirdTimeTrue() {
// maxAttempts=3; period=1; maxPeriod defaults to 1*10
// will call at 0, 1, 1+(1*1.5)
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(2);
RetryableNumTimesPredicate<String> predicate = new RetryableNumTimesPredicate<String>(rawPredicate,
4, 1, TimeUnit.SECONDS);
stopwatch.start();
predicate.apply("");
long duration = stopwatch.elapsedMillis();
assertOrdered(2500-EARLY_RETURN_GRACE, duration, 2500+SLOW_BUILD_SERVER_GRACE);
assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000+1500);
}
@Test
void testThirdTimeTrueLimitedMaxInterval() {
// maxAttempts=3; period=1; maxPeriod=1
// will call at 0, 1, 1+1
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(2);
RetryableNumTimesPredicate<String> predicate = new RetryableNumTimesPredicate<String>(rawPredicate,
3, 1L, 1L, TimeUnit.SECONDS);
stopwatch.start();
predicate.apply("");
long duration = stopwatch.elapsedMillis();
assertOrdered(2000-EARLY_RETURN_GRACE, duration, 2000+SLOW_BUILD_SERVER_GRACE);
assertCallTimes(rawPredicate.callTimes, 0, 1000, 2000);
}
private static void assertOrdered(long... values) {
long prevVal = values[0];
for (long val : values) {
if (val < prevVal) {
fail(String.format("%s should be ordered", Arrays.toString(values)));
}
}
}
}

View File

@ -1,133 +0,0 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.predicates;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.predicates.Retryables.retry;
import static org.jclouds.predicates.Retryables.retryGettingResultOrFailing;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.annotations.Test;
@Test
public class RetryablesTest {
public static class FindX implements PredicateWithResult<String,Character> {
Character result;
Throwable lastFailure;
int attempts=0;
@Override
public boolean apply(String input) {
try {
result = input.charAt(attempts++);
return (result=='x');
} catch (Exception e) {
lastFailure = e;
return false;
}
}
public Character getResult() {
return result;
}
public Throwable getLastFailure() {
return lastFailure;
}
}
public void testPredicateWithResult() {
FindX findX = new FindX();
assertFalse(findX.apply("hexy"));
assertEquals((char)findX.getResult(), 'h');
assertFalse(findX.apply("hexy"));
assertTrue(findX.apply("hexy"));
assertEquals((char)findX.getResult(), 'x');
assertFalse(findX.apply("hexy"));
assertNull(findX.getLastFailure());
//now we get error
assertFalse(findX.apply("hexy"));
assertNotNull(findX.getLastFailure());
assertEquals((char)findX.getResult(), 'y');
}
public void testRetry() {
FindX findX = new FindX();
assertTrue(retry(findX, "hexy", 1000, 1, MILLISECONDS));
assertEquals(findX.attempts, 3);
assertEquals((char)findX.getResult(), 'x');
assertNull(findX.getLastFailure());
//now we'll be getting errors
assertFalse(retry(findX, "hexy", 100, 1, MILLISECONDS));
assertEquals((char)findX.getResult(), 'y');
assertNotNull(findX.getLastFailure());
}
public void testRetryGetting() {
FindX findX = new FindX();
assertEquals((char)retryGettingResultOrFailing(findX, "hexy", 1000, "shouldn't happen"), 'x');
//now we'll be getting errors
boolean secondRetrySucceeds=false;
try {
retryGettingResultOrFailing(findX, "hexy", 100, "expected");
secondRetrySucceeds = true;
} catch (AssertionError e) {
assertTrue(e.toString().contains("expected"));
}
if (secondRetrySucceeds) fail("should have thrown");
assertNotNull(findX.getLastFailure());
assertFalse(findX.getLastFailure().toString().contains("expected"));
}
//using PredicateCallable we can repeat the above test, with the job expressed more simply
public static class FindXSimpler extends PredicateCallable<Character> {
String input = "hexy";
int attempts=0;
public Character call() {
return input.charAt(attempts++);
}
public boolean isAcceptable(Character result) {
return result=='x';
}
}
public void testSimplerPredicateCallableRetryGetting() {
FindXSimpler findX = new FindXSimpler();
assertEquals((char)retryGettingResultOrFailing(findX, null, 1000, "shouldn't happen"), 'x');
//now we'll be getting errors
boolean secondRetrySucceeds=false;
try {
retryGettingResultOrFailing(findX, null, 100, "expected");
secondRetrySucceeds = true;
} catch (AssertionError e) {
assertTrue(e.toString().contains("expected"));
}
if (secondRetrySucceeds) fail("should have thrown");
assertNotNull(findX.getLastFailure());
assertFalse(findX.getLastFailure().toString().contains("expected"));
}
}

View File

@ -16,14 +16,15 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.jclouds.predicates; package org.jclouds.util;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.fail; import static org.testng.Assert.fail;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import org.testng.Assert; import org.testng.Assert;
@ -41,7 +42,7 @@ import com.google.common.collect.Lists;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", singleThreaded = true) @Test(groups = "unit", singleThreaded = true)
public class RetryablePredicateTest { public class Predicates2Test {
// Grace must be reasonably big; Thread.sleep can take a bit longer to wake up sometimes... // Grace must be reasonably big; Thread.sleep can take a bit longer to wake up sometimes...
public static int SLOW_BUILD_SERVER_GRACE = 250; public static int SLOW_BUILD_SERVER_GRACE = 250;
@ -82,15 +83,12 @@ public class RetryablePredicateTest {
} }
private void ensureImmediateReturnFor(final Exception ex) { private void ensureImmediateReturnFor(final Exception ex) {
RetryablePredicate<Supplier<String>> predicate = new RetryablePredicate<Supplier<String>>( Predicate<Supplier<String>> predicate = retry(
new Predicate<Supplier<String>>() { new Predicate<Supplier<String>>() {
@Override
public boolean apply(Supplier<String> input) { public boolean apply(Supplier<String> input) {
return "goo".equals(input.get()); return "goo".equals(input.get());
} }
}, 3, 1, SECONDS);
}, 3, 1, TimeUnit.SECONDS);
stopwatch.start(); stopwatch.start();
assert !predicate.apply(new Supplier<String>() { assert !predicate.apply(new Supplier<String>() {
@ -108,8 +106,7 @@ public class RetryablePredicateTest {
@Test @Test
void testAlwaysTrue() { void testAlwaysTrue() {
// will call once immediately // will call once immediately
RetryablePredicate<String> predicate = new RetryablePredicate<String>(Predicates.<String> alwaysTrue(), 3, 1, Predicate<String> predicate = retry(Predicates.<String> alwaysTrue(), 3, 1, SECONDS);
TimeUnit.SECONDS);
stopwatch.start(); stopwatch.start();
predicate.apply(""); predicate.apply("");
long duration = stopwatch.elapsedMillis(); long duration = stopwatch.elapsedMillis();
@ -120,8 +117,7 @@ public class RetryablePredicateTest {
void testAlwaysFalseMillis() { void testAlwaysFalseMillis() {
// maxWait=3; period=1; maxPeriod defaults to 1*10 // maxWait=3; period=1; maxPeriod defaults to 1*10
// will call at 0, 1, 1+(1*1.5), 3 // will call at 0, 1, 1+(1*1.5), 3
RetryablePredicate<String> predicate = new RetryablePredicate<String>(Predicates.<String> alwaysFalse(), 3, 1, Predicate<String> predicate = retry(Predicates.<String> alwaysFalse(), 3, 1, SECONDS);
TimeUnit.SECONDS);
stopwatch.start(); stopwatch.start();
predicate.apply(""); predicate.apply("");
long duration = stopwatch.elapsedMillis(); long duration = stopwatch.elapsedMillis();
@ -133,7 +129,7 @@ public class RetryablePredicateTest {
// maxWait=4; period=1; maxPeriod defaults to 1*10 // maxWait=4; period=1; maxPeriod defaults to 1*10
// will call at 0, 1, 1+(1*1.5) // will call at 0, 1, 1+(1*1.5)
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(2); RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(2);
RetryablePredicate<String> predicate = new RetryablePredicate<String>(rawPredicate, 4, 1, TimeUnit.SECONDS); Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS);
stopwatch.start(); stopwatch.start();
predicate.apply(""); predicate.apply("");
@ -148,8 +144,7 @@ public class RetryablePredicateTest {
// maxWait=3; period=1; maxPeriod=1 // maxWait=3; period=1; maxPeriod=1
// will call at 0, 1, 1+1 // will call at 0, 1, 1+1
RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(2); RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(2);
RetryablePredicate<String> predicate = new RetryablePredicate<String>(rawPredicate, 3, 1, 1, Predicate<String> predicate = retry(rawPredicate, 3, 1, 1, SECONDS);
TimeUnit.SECONDS);
stopwatch.start(); stopwatch.start();
predicate.apply(""); predicate.apply("");

View File

@ -20,12 +20,13 @@ package org.jclouds.azure.management.features;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jclouds.azure.management.domain.DetailedHostedServiceProperties; import org.jclouds.azure.management.domain.DetailedHostedServiceProperties;
@ -34,7 +35,6 @@ import org.jclouds.azure.management.domain.HostedService.Status;
import org.jclouds.azure.management.domain.HostedServiceWithDetailedProperties; import org.jclouds.azure.management.domain.HostedServiceWithDetailedProperties;
import org.jclouds.azure.management.domain.Operation; import org.jclouds.azure.management.domain.Operation;
import org.jclouds.azure.management.internal.BaseAzureManagementApiLiveTest; import org.jclouds.azure.management.internal.BaseAzureManagementApiLiveTest;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -52,9 +52,9 @@ public class HostedServiceApiLiveTest extends BaseAzureManagementApiLiveTest {
public static final String HOSTED_SERVICE = (System.getProperty("user.name") + "-jclouds-hostedService") public static final String HOSTED_SERVICE = (System.getProperty("user.name") + "-jclouds-hostedService")
.toLowerCase(); .toLowerCase();
private RetryablePredicate<String> operationSucceeded; private Predicate<String> operationSucceeded;
private RetryablePredicate<HostedServiceWithDetailedProperties> hostedServiceCreated; private Predicate<HostedServiceWithDetailedProperties> hostedServiceCreated;
private RetryablePredicate<HostedService> hostedServiceGone; private Predicate<HostedService> hostedServiceGone;
private String location; private String location;
@ -64,33 +64,21 @@ public class HostedServiceApiLiveTest extends BaseAzureManagementApiLiveTest {
super.setupContext(); super.setupContext();
// TODO: filter locations on those who have compute // TODO: filter locations on those who have compute
location = Iterables.get(context.getApi().getLocationApi().list(), 0).getName(); location = Iterables.get(context.getApi().getLocationApi().list(), 0).getName();
operationSucceeded = new RetryablePredicate<String>(new Predicate<String>() { operationSucceeded = retry(new Predicate<String>() {
@Override
public boolean apply(String input) { public boolean apply(String input) {
return context.getApi().getOperationApi().get(input).getStatus() == Operation.Status.SUCCEEDED; return context.getApi().getOperationApi().get(input).getStatus() == Operation.Status.SUCCEEDED;
} }
}, 600, 5, 5, SECONDS);
}, 600, 5, 5, TimeUnit.SECONDS); hostedServiceCreated = retry(new Predicate<HostedServiceWithDetailedProperties>() {
public boolean apply(HostedServiceWithDetailedProperties input) {
hostedServiceCreated = new RetryablePredicate<HostedServiceWithDetailedProperties>( return api().getDetails(input.getName()).getProperties().getStatus() == Status.CREATED;
new Predicate<HostedServiceWithDetailedProperties>() { }
}, 600, 5, 5, SECONDS);
@Override hostedServiceGone = retry(new Predicate<HostedService>() {
public boolean apply(HostedServiceWithDetailedProperties input) {
return api().getDetails(input.getName()).getProperties().getStatus() == Status.CREATED;
}
}, 600, 5, 5, TimeUnit.SECONDS);
hostedServiceGone = new RetryablePredicate<HostedService>(new Predicate<HostedService>() {
@Override
public boolean apply(HostedService input) { public boolean apply(HostedService input) {
return api().get(input.getName()) == null; return api().get(input.getName()) == null;
} }
}, 600, 5, 5, SECONDS);
}, 600, 5, 5, TimeUnit.SECONDS);
} }
private HostedServiceWithDetailedProperties hostedService; private HostedServiceWithDetailedProperties hostedService;

View File

@ -124,7 +124,7 @@ public class FGCPComputeServiceContextModule
// @Named("SECURITY") // @Named("SECURITY")
// protected Predicate<String> provideServerStopped(ServerStopped // protected Predicate<String> provideServerStopped(ServerStopped
// serverStopped, Timeouts timeouts) { // serverStopped, Timeouts timeouts) {
// return new RetryablePredicate<String>(serverStopped, // return RetryablePredicate.create(serverStopped,
// timeouts.nodeSuspended); // timeouts.nodeSuspended);
// } // }

View File

@ -19,6 +19,7 @@
package org.jclouds.fujitsu.fgcp.compute.strategy; package org.jclouds.fujitsu.fgcp.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.util.Predicates2.retry;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -51,7 +52,6 @@ import org.jclouds.fujitsu.fgcp.domain.VServerWithVNICs;
import org.jclouds.fujitsu.fgcp.domain.VSystem; import org.jclouds.fujitsu.fgcp.domain.VSystem;
import org.jclouds.fujitsu.fgcp.domain.VSystemWithDetails; import org.jclouds.fujitsu.fgcp.domain.VSystemWithDetails;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
@ -90,12 +90,9 @@ public class FGCPComputeServiceAdapter implements
ResourceIdToSystemId toSystemId) { ResourceIdToSystemId toSystemId) {
this.api = checkNotNull(api, "api"); this.api = checkNotNull(api, "api");
this.asyncApi = checkNotNull(asyncApi, "asyncApi"); this.asyncApi = checkNotNull(asyncApi, "asyncApi");
this.serverStopped = new RetryablePredicate<String>( this.serverStopped = retry(checkNotNull(serverStopped), timeouts.nodeSuspended);
checkNotNull(serverStopped), timeouts.nodeSuspended); this.serverCreated = retry(checkNotNull(serverStopped), timeouts.nodeRunning);
this.serverCreated = new RetryablePredicate<String>( this.systemNormal = retry(checkNotNull(systemNormal), timeouts.nodeTerminated);
checkNotNull(serverStopped), timeouts.nodeRunning);
this.systemNormal = new RetryablePredicate<String>(
checkNotNull(systemNormal), timeouts.nodeTerminated);
this.toFirewallId = checkNotNull(toFirewallId, "ResourceIdToFirewallId"); this.toFirewallId = checkNotNull(toFirewallId, "ResourceIdToFirewallId");
this.toSystemId = checkNotNull(toSystemId, "ResourceIdToSystemId"); this.toSystemId = checkNotNull(toSystemId, "ResourceIdToSystemId");
} }

View File

@ -18,10 +18,15 @@
*/ */
package org.jclouds.googlecompute.internal; package org.jclouds.googlecompute.internal;
import com.google.common.base.Predicate; import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.reflect.TypeToken; import static org.jclouds.util.Predicates2.retry;
import com.google.inject.Key; import static org.testng.Assert.assertEquals;
import com.google.inject.TypeLiteral; import static org.testng.AssertJUnit.assertTrue;
import java.net.URI;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import org.jclouds.apis.BaseContextLiveTest; import org.jclouds.apis.BaseContextLiveTest;
import org.jclouds.googlecompute.GoogleComputeApi; import org.jclouds.googlecompute.GoogleComputeApi;
import org.jclouds.googlecompute.GoogleComputeApiMetadata; import org.jclouds.googlecompute.GoogleComputeApiMetadata;
@ -29,16 +34,12 @@ import org.jclouds.googlecompute.GoogleComputeAsyncApi;
import org.jclouds.googlecompute.config.UserProject; import org.jclouds.googlecompute.config.UserProject;
import org.jclouds.googlecompute.domain.Operation; import org.jclouds.googlecompute.domain.Operation;
import org.jclouds.oauth.v2.OAuthTestUtils; import org.jclouds.oauth.v2.OAuthTestUtils;
import org.jclouds.predicates.Retryables;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import java.net.URI; import com.google.common.base.Predicate;
import java.util.Properties; import com.google.common.reflect.TypeToken;
import java.util.concurrent.TimeUnit; import com.google.inject.Key;
import java.util.concurrent.atomic.AtomicReference; import com.google.inject.TypeLiteral;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
/** /**
@ -123,10 +124,8 @@ public class BaseGoogleComputeApiLiveTest extends BaseContextLiveTest<RestContex
protected static Operation waitOperationDone(Predicate<AtomicReference<Operation>> operationDonePredicate, protected static Operation waitOperationDone(Predicate<AtomicReference<Operation>> operationDonePredicate,
Operation operation, long maxWaitSeconds) { Operation operation, long maxWaitSeconds) {
AtomicReference<Operation> operationReference = new AtomicReference<Operation>(operation); AtomicReference<Operation> operationReference = new AtomicReference<Operation>(operation);
Retryables.retry(operationDonePredicate, operationReference, maxWaitSeconds, 1, TimeUnit.SECONDS); retry(operationDonePredicate, maxWaitSeconds, 1, SECONDS).apply(operationReference);
return operationReference.get(); return operationReference.get();
} }
} }

View File

@ -19,12 +19,13 @@
package org.jclouds.joyent.cloudapi.v6_5.features; package org.jclouds.joyent.cloudapi.v6_5.features;
import static com.google.common.base.Predicates.not; import static com.google.common.base.Predicates.not;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.crypto.SshKeys; import org.jclouds.crypto.SshKeys;
@ -35,7 +36,6 @@ import org.jclouds.joyent.cloudapi.v6_5.internal.BaseJoyentCloudApiLiveTest;
import org.jclouds.joyent.cloudapi.v6_5.options.CreateMachineOptions; import org.jclouds.joyent.cloudapi.v6_5.options.CreateMachineOptions;
import org.jclouds.joyent.cloudapi.v6_5.reference.Metadata; import org.jclouds.joyent.cloudapi.v6_5.reference.Metadata;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.util.InetAddresses2; import org.jclouds.util.InetAddresses2;
@ -80,7 +80,7 @@ public class MachineApiLiveTest extends BaseJoyentCloudApiLiveTest {
private Map<String, String> key; private Map<String, String> key;
private String fingerprint; private String fingerprint;
private RetryablePredicate<HostAndPort> socketTester; private Predicate<HostAndPort> socketTester;
private Predicate<Machine> machineRunning; private Predicate<Machine> machineRunning;
private MachineApi api; private MachineApi api;
private Machine machine; private Machine machine;
@ -96,15 +96,12 @@ public class MachineApiLiveTest extends BaseJoyentCloudApiLiveTest {
cloudApiContext.getApi().getKeyApi().create(Key.builder().name(fingerprint).key(key.get("public")).build()); cloudApiContext.getApi().getKeyApi().create(Key.builder().name(fingerprint).key(key.get("public")).build());
api = cloudApiContext.getApi().getMachineApiForDatacenter( api = cloudApiContext.getApi().getMachineApiForDatacenter(
Iterables.get(cloudApiContext.getApi().getConfiguredDatacenters(), 0)); Iterables.get(cloudApiContext.getApi().getConfiguredDatacenters(), 0));
socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), 180, 1, 1, TimeUnit.SECONDS); socketTester = retry(new InetSocketAddressConnect(), 180, 1, 1, SECONDS);
machineRunning = new RetryablePredicate<Machine>(new Predicate<Machine>() { machineRunning = retry(new Predicate<Machine>() {
@Override
public boolean apply(Machine input) { public boolean apply(Machine input) {
return api.get(input.getId()).getState() == Machine.State.RUNNING; return api.get(input.getId()).getState() == Machine.State.RUNNING;
} }
}, 600, 5, 5, SECONDS);
}, 600, 5, 5, TimeUnit.SECONDS);
} }
public void testCreateMachine() { public void testCreateMachine() {

View File

@ -19,16 +19,17 @@
package org.jclouds.rds.features; package org.jclouds.rds.features;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jclouds.collect.IterableWithMarker; import org.jclouds.collect.IterableWithMarker;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rds.domain.Authorization; import org.jclouds.rds.domain.Authorization;
import org.jclouds.rds.domain.Authorization.Status; import org.jclouds.rds.domain.Authorization.Status;
import org.jclouds.rds.domain.Instance; import org.jclouds.rds.domain.Instance;
@ -52,9 +53,9 @@ import com.google.common.net.HostAndPort;
public class InstanceApiLiveTest extends BaseRDSApiLiveTest { public class InstanceApiLiveTest extends BaseRDSApiLiveTest {
public static final String INSTANCE = (System.getProperty("user.name") + "-jclouds-instance").toLowerCase(); public static final String INSTANCE = (System.getProperty("user.name") + "-jclouds-instance").toLowerCase();
private RetryablePredicate<HostAndPort> socketTester; private Predicate<HostAndPort> socketTester;
private RetryablePredicate<Instance> instanceAvailable; private Predicate<Instance> instanceAvailable;
private RetryablePredicate<Instance> instanceGone; private Predicate<Instance> instanceGone;
private SecurityGroup securityGroup; private SecurityGroup securityGroup;
@ -63,44 +64,30 @@ public class InstanceApiLiveTest extends BaseRDSApiLiveTest {
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
securityGroup = createSecurityGroupAndAuthorizeIngressToAll(INSTANCE); securityGroup = createSecurityGroupAndAuthorizeIngressToAll(INSTANCE);
socketTester = retry(new InetSocketAddressConnect(), 180, 1, 1, SECONDS);
socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), 180, 1, 1, TimeUnit.SECONDS); instanceAvailable = retry(new Predicate<Instance>() {
instanceAvailable = new RetryablePredicate<Instance>(new Predicate<Instance>() {
@Override
public boolean apply(Instance input) { public boolean apply(Instance input) {
return api().get(input.getId()).getStatus() == Instance.Status.AVAILABLE; return api().get(input.getId()).getStatus() == Instance.Status.AVAILABLE;
} }
}, 600, 5, 5, SECONDS);
}, 600, 5, 5, TimeUnit.SECONDS); instanceGone = retry(new Predicate<Instance>() {
instanceGone = new RetryablePredicate<Instance>(new Predicate<Instance>() {
@Override
public boolean apply(Instance input) { public boolean apply(Instance input) {
return api().get(input.getId()) == null; return api().get(input.getId()) == null;
} }
}, 600, 5, 5, SECONDS);
}, 600, 5, 5, TimeUnit.SECONDS);
} }
private SecurityGroup createSecurityGroupAndAuthorizeIngressToAll(String name) { private SecurityGroup createSecurityGroupAndAuthorizeIngressToAll(String name) {
RetryablePredicate<SecurityGroup> ipRangesAuthorized = new RetryablePredicate<SecurityGroup>( Predicate<SecurityGroup> ipRangesAuthorized = retry(
new Predicate<SecurityGroup>() { new Predicate<SecurityGroup>() {
@Override
public boolean apply(SecurityGroup input) { public boolean apply(SecurityGroup input) {
return Iterables.all(sgApi().get(input.getName()).getIPRanges(), new Predicate<Authorization>() { return Iterables.all(sgApi().get(input.getName()).getIPRanges(), new Predicate<Authorization>() {
@Override
public boolean apply(Authorization i2) { public boolean apply(Authorization i2) {
return i2.getStatus() == Status.AUTHORIZED; return i2.getStatus() == Status.AUTHORIZED;
} }
}); });
} }
}, 30000, 100, 500, MILLISECONDS);
}, 30000, 100, 500, TimeUnit.MILLISECONDS);
try { try {
SecurityGroup securityGroup = sgApi().createWithNameAndDescription(name, "jclouds"); SecurityGroup securityGroup = sgApi().createWithNameAndDescription(name, "jclouds");

View File

@ -19,14 +19,14 @@
package org.jclouds.rds.features; package org.jclouds.rds.features;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.jclouds.collect.IterableWithMarker; import org.jclouds.collect.IterableWithMarker;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rds.domain.Authorization; import org.jclouds.rds.domain.Authorization;
import org.jclouds.rds.domain.Authorization.Status; import org.jclouds.rds.domain.Authorization.Status;
import org.jclouds.rds.domain.EC2SecurityGroup; import org.jclouds.rds.domain.EC2SecurityGroup;
@ -49,36 +49,27 @@ public class SecurityGroupApiLiveTest extends BaseRDSApiLiveTest {
public static final String SECURITYGROUP = (System.getProperty("user.name") + "-jclouds-securityGroup") public static final String SECURITYGROUP = (System.getProperty("user.name") + "-jclouds-securityGroup")
.toLowerCase(); .toLowerCase();
private RetryablePredicate<SecurityGroup> ipRangesAuthorized; private Predicate<SecurityGroup> ipRangesAuthorized;
private RetryablePredicate<SecurityGroup> ipRangesRevoked; private Predicate<SecurityGroup> ipRangesRevoked;
@BeforeClass(groups = "live") @BeforeClass(groups = "live")
@Override @Override
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
ipRangesAuthorized = new RetryablePredicate<SecurityGroup>(new Predicate<SecurityGroup>() { ipRangesAuthorized = retry(new Predicate<SecurityGroup>() {
@Override
public boolean apply(SecurityGroup input) { public boolean apply(SecurityGroup input) {
return Iterables.all(api().get(input.getName()).getIPRanges(), new Predicate<Authorization>() { return Iterables.all(api().get(input.getName()).getIPRanges(), new Predicate<Authorization>() {
@Override
public boolean apply(Authorization i2) { public boolean apply(Authorization i2) {
return i2.getStatus() == Status.AUTHORIZED; return i2.getStatus() == Status.AUTHORIZED;
} }
}); });
} }
}, 30000, 100, 500, MILLISECONDS);
}, 30000, 100, 500, TimeUnit.MILLISECONDS); ipRangesRevoked = retry(new Predicate<SecurityGroup>() {
ipRangesRevoked = new RetryablePredicate<SecurityGroup>(new Predicate<SecurityGroup>() {
@Override
public boolean apply(SecurityGroup input) { public boolean apply(SecurityGroup input) {
return api().get(input.getName()).getIPRanges().size() == 0; return api().get(input.getName()).getIPRanges().size() == 0;
} }
}, 30000, 100, 500, MILLISECONDS);
}, 30000, 100, 500, TimeUnit.MILLISECONDS);
} }
private SecurityGroup securityGroup; private SecurityGroup securityGroup;

View File

@ -19,20 +19,21 @@
package org.jclouds.savvis.vpdc.compute.strategy; package org.jclouds.savvis.vpdc.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.jclouds.savvis.vpdc.options.GetVMOptions.Builder.withPowerState; import static org.jclouds.savvis.vpdc.options.GetVMOptions.Builder.withPowerState;
import static org.jclouds.savvis.vpdc.reference.VPDCConstants.PROPERTY_VPDC_VDC_EMAIL; import static org.jclouds.savvis.vpdc.reference.VPDCConstants.PROPERTY_VPDC_VDC_EMAIL;
import java.net.URI; import java.net.URI;
import java.util.concurrent.TimeUnit;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.domain.CIMOperatingSystem; import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.savvis.vpdc.VPDCApi; import org.jclouds.savvis.vpdc.VPDCApi;
import org.jclouds.savvis.vpdc.domain.Network; import org.jclouds.savvis.vpdc.domain.Network;
import org.jclouds.savvis.vpdc.domain.Org; import org.jclouds.savvis.vpdc.domain.Org;
@ -46,8 +47,8 @@ import org.jclouds.savvis.vpdc.reference.VCloudMediaType;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.ImmutableSet.Builder; import com.google.common.collect.ImmutableSet.Builder;
import com.google.common.collect.Iterables;
import com.google.inject.Inject; import com.google.inject.Inject;
; ;
@ -60,7 +61,7 @@ import com.google.inject.Inject;
@Singleton @Singleton
public class VPDCComputeServiceAdapter implements ComputeServiceAdapter<VM, VMSpec, CIMOperatingSystem, Network> { public class VPDCComputeServiceAdapter implements ComputeServiceAdapter<VM, VMSpec, CIMOperatingSystem, Network> {
private final VPDCApi api; private final VPDCApi api;
private final RetryablePredicate<String> taskTester; private final Predicate<String> taskTester;
@Inject(optional = true) @Inject(optional = true)
@Named(PROPERTY_VPDC_VDC_EMAIL) @Named(PROPERTY_VPDC_VDC_EMAIL)
String email; String email;
@ -69,8 +70,7 @@ public class VPDCComputeServiceAdapter implements ComputeServiceAdapter<VM, VMSp
public VPDCComputeServiceAdapter(VPDCApi api, TaskSuccess taskSuccess) { public VPDCComputeServiceAdapter(VPDCApi api, TaskSuccess taskSuccess) {
this.api = checkNotNull(api, "api"); this.api = checkNotNull(api, "api");
// TODO: parameterize // TODO: parameterize
this.taskTester = new RetryablePredicate<String>(checkNotNull(taskSuccess, "taskSuccess"), 650, 10, this.taskTester = retry(checkNotNull(taskSuccess, "taskSuccess"), 650, 10, SECONDS);
TimeUnit.SECONDS);
} }
@Override @Override

View File

@ -23,6 +23,7 @@ import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import static org.jclouds.rest.config.BinderUtils.bindHttpApi; import static org.jclouds.rest.config.BinderUtils.bindHttpApi;
import static org.jclouds.savvis.vpdc.reference.VPDCConstants.PROPERTY_VPDC_TIMEOUT_TASK_COMPLETED; import static org.jclouds.savvis.vpdc.reference.VPDCConstants.PROPERTY_VPDC_TIMEOUT_TASK_COMPLETED;
import static org.jclouds.util.Predicates2.retry;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
@ -40,7 +41,6 @@ import org.jclouds.http.annotation.ServerError;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.location.Provider; import org.jclouds.location.Provider;
import org.jclouds.location.suppliers.ImplicitLocationSupplier; import org.jclouds.location.suppliers.ImplicitLocationSupplier;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.annotations.Identity; import org.jclouds.rest.annotations.Identity;
import org.jclouds.rest.config.RestClientModule; import org.jclouds.rest.config.RestClientModule;
@ -138,7 +138,7 @@ public class VPDCRestClientModule extends RestClientModule<VPDCApi, VPDCAsyncApi
@Singleton @Singleton
protected Predicate<String> successTester(Injector injector, protected Predicate<String> successTester(Injector injector,
@Named(PROPERTY_VPDC_TIMEOUT_TASK_COMPLETED) long completed) { @Named(PROPERTY_VPDC_TIMEOUT_TASK_COMPLETED) long completed) {
return new RetryablePredicate<String>(injector.getInstance(TaskSuccess.class), completed); return retry(injector.getInstance(TaskSuccess.class), completed);
} }
public static final Map<Class<?>, Class<?>> DELEGATE_MAP = ImmutableMap.<Class<?>, Class<?>> builder()// public static final Map<Class<?>, Class<?>> DELEGATE_MAP = ImmutableMap.<Class<?>, Class<?>> builder()//

View File

@ -19,20 +19,22 @@
package org.jclouds.savvis.vpdc.features; package org.jclouds.savvis.vpdc.features;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.savvis.vpdc.VPDCAsyncApi;
import org.jclouds.savvis.vpdc.VPDCApi; import org.jclouds.savvis.vpdc.VPDCApi;
import org.jclouds.savvis.vpdc.VPDCAsyncApi;
import org.jclouds.savvis.vpdc.predicates.TaskSuccess; import org.jclouds.savvis.vpdc.predicates.TaskSuccess;
import org.jclouds.savvis.vpdc.reference.VPDCConstants; import org.jclouds.savvis.vpdc.reference.VPDCConstants;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Predicate;
/** /**
* Tests behavior of {@code VPDCApi} * Tests behavior of {@code VPDCApi}
* *
@ -47,7 +49,7 @@ public class BaseVPDCApiLiveTest extends BaseComputeServiceContextLiveTest {
protected RestContext<VPDCApi, VPDCAsyncApi> restContext; protected RestContext<VPDCApi, VPDCAsyncApi> restContext;
protected String email; protected String email;
protected RetryablePredicate<String> taskTester; protected Predicate<String> taskTester;
@Override @Override
protected Properties setupProperties() { protected Properties setupProperties() {
@ -65,7 +67,7 @@ public class BaseVPDCApiLiveTest extends BaseComputeServiceContextLiveTest {
@Override @Override
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
taskTester = new RetryablePredicate<String>(new TaskSuccess(restContext.getApi()), 7200, 10, TimeUnit.SECONDS); taskTester = retry(new TaskSuccess(restContext.getApi()), 7200, 10, SECONDS);
} }
} }

View File

@ -19,17 +19,17 @@
package org.jclouds.savvis.vpdc.features; package org.jclouds.savvis.vpdc.features;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.cim.OSType; import org.jclouds.cim.OSType;
import org.jclouds.compute.domain.CIMOperatingSystem; import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.domain.LoginCredentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.predicates.InetSocketAddressConnect; import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.savvis.vpdc.domain.Network; import org.jclouds.savvis.vpdc.domain.Network;
import org.jclouds.savvis.vpdc.domain.Resource; import org.jclouds.savvis.vpdc.domain.Resource;
import org.jclouds.savvis.vpdc.domain.Task; import org.jclouds.savvis.vpdc.domain.Task;
@ -54,7 +54,7 @@ public class VMApiLiveTest extends BaseVPDCApiLiveTest {
private VMApi api; private VMApi api;
private VM vm; private VM vm;
private RetryablePredicate<HostAndPort> socketTester; private Predicate<HostAndPort> socketTester;
private String username = checkNotNull(System.getProperty("test." + provider + ".loginUser"), "test." + provider private String username = checkNotNull(System.getProperty("test." + provider + ".loginUser"), "test." + provider
+ ".loginUser"); + ".loginUser");
@ -66,7 +66,7 @@ public class VMApiLiveTest extends BaseVPDCApiLiveTest {
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
api = restContext.getApi().getVMApi(); api = restContext.getApi().getVMApi();
socketTester = new RetryablePredicate<HostAndPort>(new InetSocketAddressConnect(), 130, 10, TimeUnit.SECONDS);// make socketTester = retry(new InetSocketAddressConnect(), 130, 10, SECONDS);// make
} }
private String billingSiteId; private String billingSiteId;

View File

@ -25,6 +25,7 @@ import static com.google.common.collect.Iterables.contains;
import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.getFirst; import static com.google.common.collect.Iterables.getFirst;
import static com.google.common.collect.Iterables.tryFind; import static com.google.common.collect.Iterables.tryFind;
import static org.jclouds.util.Predicates2.retry;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.ENTITY_NON_NULL; import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.ENTITY_NON_NULL;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.TASK_COMPLETE_TIMELY; import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.TASK_COMPLETE_TIMELY;
import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.URN_REQ_LIVE; import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.URN_REQ_LIVE;
@ -57,7 +58,6 @@ import org.jclouds.apis.BaseContextLiveTest;
import org.jclouds.date.DateService; import org.jclouds.date.DateService;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.vcloud.director.testng.FormatApiResultsListener; import org.jclouds.vcloud.director.testng.FormatApiResultsListener;
import org.jclouds.vcloud.director.v1_5.VCloudDirectorApiMetadata; import org.jclouds.vcloud.director.v1_5.VCloudDirectorApiMetadata;
@ -179,12 +179,12 @@ public abstract class BaseVCloudDirectorApiLiveTest extends BaseContextLiveTest<
@Inject @Inject
protected void initTaskSuccess(TaskSuccess taskSuccess) { protected void initTaskSuccess(TaskSuccess taskSuccess) {
retryTaskSuccess = new RetryablePredicate<Task>(taskSuccess, TASK_TIMEOUT_SECONDS * 1000L); retryTaskSuccess = retry(taskSuccess, TASK_TIMEOUT_SECONDS * 1000L);
} }
@Inject @Inject
protected void initTaskSuccessLong(TaskSuccess taskSuccess) { protected void initTaskSuccessLong(TaskSuccess taskSuccess) {
retryTaskSuccessLong = new RetryablePredicate<Task>(taskSuccess, LONG_TASK_TIMEOUT_SECONDS * 1000L); retryTaskSuccessLong = retry(taskSuccess, LONG_TASK_TIMEOUT_SECONDS * 1000L);
} }
@BeforeClass(groups = { "integration", "live" }) @BeforeClass(groups = { "integration", "live" })
@ -588,9 +588,7 @@ public abstract class BaseVCloudDirectorApiLiveTest extends BaseContextLiveTest<
protected boolean taskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) { protected boolean taskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) {
TaskApi taskApi = context.getApi().getTaskApi(); TaskApi taskApi = context.getApi().getTaskApi();
TaskStatusEquals predicate = new TaskStatusEquals(taskApi, running, immutableSet); TaskStatusEquals predicate = new TaskStatusEquals(taskApi, running, immutableSet);
RetryablePredicate<Task> retryablePredicate = new RetryablePredicate<Task>(predicate, return retry(predicate, TASK_TIMEOUT_SECONDS * 1000L).apply(task);
TASK_TIMEOUT_SECONDS * 1000L);
return retryablePredicate.apply(task);
} }
protected void assertTaskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) { protected void assertTaskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) {
@ -602,9 +600,7 @@ public abstract class BaseVCloudDirectorApiLiveTest extends BaseContextLiveTest<
TaskApi taskApi = context.getApi().getTaskApi(); TaskApi taskApi = context.getApi().getTaskApi();
TaskStatusEquals predicate = new TaskStatusEquals(taskApi, ImmutableSet.of(Task.Status.ABORTED, TaskStatusEquals predicate = new TaskStatusEquals(taskApi, ImmutableSet.of(Task.Status.ABORTED,
Task.Status.CANCELED, Task.Status.ERROR, Task.Status.SUCCESS), ImmutableSet.<Task.Status> of()); Task.Status.CANCELED, Task.Status.ERROR, Task.Status.SUCCESS), ImmutableSet.<Task.Status> of());
RetryablePredicate<Task> retryablePredicate = new RetryablePredicate<Task>(predicate, return retry(predicate, TASK_TIMEOUT_SECONDS * 1000L).apply(task);
LONG_TASK_TIMEOUT_SECONDS * 1000L);
return retryablePredicate.apply(task);
} }
protected void assertTaskDoneEventually(Task task) { protected void assertTaskDoneEventually(Task task) {

View File

@ -18,11 +18,12 @@
*/ */
package org.jclouds.virtualbox.config; package org.jclouds.virtualbox.config;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.io.File; import java.io.File;
import java.net.URI; import java.net.URI;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -37,7 +38,6 @@ import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.functions.IdentityFunction; import org.jclouds.functions.IdentityFunction;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.virtualbox.compute.VirtualBoxComputeServiceAdapter; import org.jclouds.virtualbox.compute.VirtualBoxComputeServiceAdapter;
import org.jclouds.virtualbox.compute.extensions.VirtualBoxImageExtension; import org.jclouds.virtualbox.compute.extensions.VirtualBoxImageExtension;
@ -167,7 +167,7 @@ public class VirtualBoxComputeServiceContextModule extends
@Provides @Provides
@Singleton @Singleton
protected Predicate<SshClient> sshResponds(SshResponds sshResponds, Timeouts timeouts) { protected Predicate<SshClient> sshResponds(SshResponds sshResponds, Timeouts timeouts) {
return new RetryablePredicate<SshClient>(sshResponds, timeouts.nodeRunning, 500l, TimeUnit.MILLISECONDS); return retry(sshResponds, timeouts.nodeRunning, 500l, MILLISECONDS);
} }
@Override @Override

View File

@ -18,6 +18,8 @@
*/ */
package org.jclouds.virtualbox.predicates; package org.jclouds.virtualbox.predicates;
import static org.jclouds.util.Predicates2.retry;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -27,7 +29,6 @@ import javax.inject.Named;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -88,8 +89,7 @@ public class RetryIfSocketNotYetOpen implements Predicate<HostAndPort> {
logger.debug(">> blocking on socket %s for %d %s", socket, timeoutValue, timeoutUnits); logger.debug(">> blocking on socket %s for %d %s", socket, timeoutValue, timeoutUnits);
// Specify a retry period of 1s, expressed in the same time units. // Specify a retry period of 1s, expressed in the same time units.
long period = timeoutUnits.convert(1, TimeUnit.SECONDS); long period = timeoutUnits.convert(1, TimeUnit.SECONDS);
RetryablePredicate<HostAndPort> tester = new RetryablePredicate<HostAndPort>(socketTester, timeoutValue, period, timeoutUnits); boolean passed = retry(socketTester, timeoutValue, period, timeoutUnits).apply(socket);
boolean passed = tester.apply(socket);
if (passed) if (passed)
logger.debug("<< socket %s opened", socket); logger.debug("<< socket %s opened", socket);
else else

View File

@ -20,9 +20,10 @@ package org.jclouds.virtualbox.util;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Named; import javax.inject.Named;
@ -30,7 +31,6 @@ import javax.inject.Singleton;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryableNumTimesPredicate;
import org.jclouds.virtualbox.domain.ExecutionType; import org.jclouds.virtualbox.domain.ExecutionType;
import org.jclouds.virtualbox.functions.LaunchMachineIfNotAlreadyRunning; import org.jclouds.virtualbox.functions.LaunchMachineIfNotAlreadyRunning;
import org.virtualbox_4_2.AdditionsFacilityStatus; import org.virtualbox_4_2.AdditionsFacilityStatus;
@ -100,8 +100,7 @@ public class MachineController {
new Function<ISession, String>() { new Function<ISession, String>() {
@Override @Override
public String apply(ISession session) { public String apply(ISession session) {
new RetryableNumTimesPredicate<Integer>(new FacilitiesPredicate(session), retry(new FacilitiesPredicate(session), 15, 3, SECONDS).apply(4);
5, 3L, TimeUnit.SECONDS).apply(4);
String guestAdditionsInstalled = session.getConsole().getGuest().getAdditionsVersion(); String guestAdditionsInstalled = session.getConsole().getGuest().getAdditionsVersion();
return guestAdditionsInstalled; return guestAdditionsInstalled;
} }
@ -139,10 +138,10 @@ public class MachineController {
session.getConsole().powerButton(); session.getConsole().powerButton();
return session; return session;
} }
}); });
checkState(new RetryableNumTimesPredicate<MachineState>( checkState(
new MachineStatePredicate(manager.get().getVBox(), vmName), 5, retry(new MachineStatePredicate(manager.get().getVBox(), vmName), 15, 3, SECONDS).apply(
3L, TimeUnit.SECONDS).apply(MachineState.PoweredOff), "vm(%s) is not shutdown correctly", vmName); MachineState.PoweredOff), "vm(%s) is not shutdown correctly", vmName);
return checkNotNull(session, "session"); return checkNotNull(session, "session");
} }
@ -200,10 +199,11 @@ public class MachineController {
@Override @Override
public Void apply(ISession session) { public Void apply(ISession session) {
checkState(new RetryableNumTimesPredicate<AdditionsRunLevelType>(new AdditionsStatusPredicate(session), checkState(
5, 2L, TimeUnit.SECONDS).apply(AdditionsRunLevelType.Userland), "timed out waiting for additionsRunLevelType to be %s", AdditionsRunLevelType.Userland); retry(new AdditionsStatusPredicate(session), 10, 2, SECONDS).apply(AdditionsRunLevelType.Userland),
checkState(new RetryableNumTimesPredicate<Integer>(new FacilitiesPredicate(session), "timed out waiting for additionsRunLevelType to be %s", AdditionsRunLevelType.Userland);
5, 3L, TimeUnit.SECONDS).apply(4), "timed out waiting for 4 running facilities"); checkState(retry(new FacilitiesPredicate(session), 15, 3, SECONDS).apply(4),
"timed out waiting for 4 running facilities");
Optional<IAdditionsFacility> vboxServiceFacility = Optional.absent(); Optional<IAdditionsFacility> vboxServiceFacility = Optional.absent();
while (!vboxServiceFacility.isPresent()) { while (!vboxServiceFacility.isPresent()) {
List<IAdditionsFacility> facilities = session.getConsole().getGuest().getFacilities(); List<IAdditionsFacility> facilities = session.getConsole().getGuest().getFacilities();

View File

@ -20,6 +20,7 @@ package org.jclouds.virtualbox.util;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.util.Predicates2.retry;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -34,7 +35,6 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryableNumTimesPredicate;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.util.Throwables2; import org.jclouds.util.Throwables2;
import org.jclouds.virtualbox.functions.IpAddressesLoadingCache; import org.jclouds.virtualbox.functions.IpAddressesLoadingCache;
@ -60,9 +60,6 @@ import com.google.inject.Inject;
@Singleton @Singleton
public class MachineUtils { public class MachineUtils {
public final String IP_V4_ADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." public final String IP_V4_ADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
@ -270,8 +267,8 @@ public class MachineUtils {
} }
private void checkSessionIsUnlocked(ISession session, int attempts, long period, TimeUnit timeUnit) { private void checkSessionIsUnlocked(ISession session, int attempts, long period, TimeUnit timeUnit) {
checkState(new RetryableNumTimesPredicate<SessionState>(new SessionStatePredicate(session), checkState(
attempts, period, timeUnit).apply(SessionState.Unlocked), retry(new SessionStatePredicate(session), attempts * period, period, timeUnit).apply(SessionState.Unlocked),
"timed out or number of retries(%s) reached waiting for session to be unlocked", attempts); "timed out or number of retries(%s) reached waiting for session to be unlocked", attempts);
} }

View File

@ -21,10 +21,11 @@ package org.jclouds.loadbalancer.internal;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.Sets.newLinkedHashSet;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -44,7 +45,6 @@ import org.jclouds.loadbalancer.strategy.GetLoadBalancerMetadataStrategy;
import org.jclouds.loadbalancer.strategy.ListLoadBalancersStrategy; import org.jclouds.loadbalancer.strategy.ListLoadBalancersStrategy;
import org.jclouds.loadbalancer.strategy.LoadBalanceNodesStrategy; import org.jclouds.loadbalancer.strategy.LoadBalanceNodesStrategy;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
@ -138,9 +138,7 @@ public class BaseLoadBalancerService implements LoadBalancerService {
checkNotNull(id, "id"); checkNotNull(id, "id");
logger.debug(">> destroying load balancer(%s)", id); logger.debug(">> destroying load balancer(%s)", id);
final AtomicReference<LoadBalancerMetadata> loadBalancer = Atomics.newReference(); final AtomicReference<LoadBalancerMetadata> loadBalancer = Atomics.newReference();
RetryablePredicate<String> tester = new RetryablePredicate<String>(new Predicate<String>() { Predicate<String> tester = retry(new Predicate<String>() {
@Override
public boolean apply(String input) { public boolean apply(String input) {
try { try {
LoadBalancerMetadata md = destroyLoadBalancerStrategy.destroyLoadBalancer(id); LoadBalancerMetadata md = destroyLoadBalancerStrategy.destroyLoadBalancer(id);
@ -152,8 +150,7 @@ public class BaseLoadBalancerService implements LoadBalancerService {
return false; return false;
} }
} }
}, 3000, 1000, MILLISECONDS);// TODO make timeouts class like ComputeServiceconstants
}, 3000, 1000, TimeUnit.MILLISECONDS);// TODO make timeouts class like ComputeServiceconstants
boolean successful = tester.apply(id) && loadBalancer.get() == null; // TODO add load boolean successful = tester.apply(id) && loadBalancer.get() == null; // TODO add load
// balancerTerminated // balancerTerminated
// retryable predicate // retryable predicate

View File

@ -19,11 +19,12 @@
package org.jclouds.loadbalancer; package org.jclouds.loadbalancer;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import java.util.Properties; import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.Constants; import org.jclouds.Constants;
import org.jclouds.ContextBuilder; import org.jclouds.ContextBuilder;
@ -37,12 +38,12 @@ import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.domain.LoginCredentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.domain.LoginCredentials.Builder;
import org.jclouds.loadbalancer.domain.LoadBalancerMetadata; import org.jclouds.loadbalancer.domain.LoadBalancerMetadata;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.net.HostAndPort; import com.google.common.net.HostAndPort;
@ -89,7 +90,7 @@ public abstract class BaseLoadBalancerServiceLiveTest extends BaseViewLiveTest<L
protected String group; protected String group;
protected RetryablePredicate<HostAndPort> socketTester; protected Predicate<HostAndPort> socketTester;
protected Set<? extends NodeMetadata> nodes; protected Set<? extends NodeMetadata> nodes;
protected LoadBalancerMetadata loadbalancer; protected LoadBalancerMetadata loadbalancer;
@ -131,7 +132,7 @@ public abstract class BaseLoadBalancerServiceLiveTest extends BaseViewLiveTest<L
protected void buildSocketTester() { protected void buildSocketTester() {
SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class); SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class);
socketTester = new RetryablePredicate<HostAndPort>(socketOpen, 60, 1, TimeUnit.SECONDS); socketTester = retry(socketOpen, 60, 1, SECONDS);
} }
abstract protected Module getSshModule(); abstract protected Module getSshModule();

View File

@ -18,13 +18,14 @@
*/ */
package org.jclouds.aws.ec2.compute.config; package org.jclouds.aws.ec2.compute.config;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_AMI_QUERY; import static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_AMI_QUERY;
import static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_CC_AMI_QUERY; import static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_CC_AMI_QUERY;
import static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS; import static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;
import static org.jclouds.util.Predicates2.retry;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.inject.Named; import javax.inject.Named;
@ -59,11 +60,8 @@ import org.jclouds.ec2.compute.internal.EC2TemplateBuilderImpl;
import org.jclouds.ec2.compute.loaders.CreateSecurityGroupIfNeeded; import org.jclouds.ec2.compute.loaders.CreateSecurityGroupIfNeeded;
import org.jclouds.ec2.compute.loaders.LoadPublicIpForInstanceOrNull; import org.jclouds.ec2.compute.loaders.LoadPublicIpForInstanceOrNull;
import org.jclouds.ec2.compute.loaders.RegionAndIdToImage; import org.jclouds.ec2.compute.loaders.RegionAndIdToImage;
import org.jclouds.ec2.compute.predicates.GetImageWhenStatusAvailablePredicateWithResult;
import org.jclouds.ec2.domain.KeyPair; import org.jclouds.ec2.domain.KeyPair;
import org.jclouds.ec2.domain.RunningInstance; import org.jclouds.ec2.domain.RunningInstance;
import org.jclouds.predicates.PredicateWithResult;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Optional; import com.google.common.base.Optional;
@ -111,8 +109,6 @@ public class AWSEC2ComputeServiceDependenciesModule extends EC2ComputeServiceDep
}).to(EC2ImageParser.class); }).to(EC2ImageParser.class);
bind(new TypeLiteral<ImageExtension>() { bind(new TypeLiteral<ImageExtension>() {
}).to(EC2ImageExtension.class); }).to(EC2ImageExtension.class);
bind(new TypeLiteral<PredicateWithResult<String, Image>>() {
}).to(GetImageWhenStatusAvailablePredicateWithResult.class);
} }
@Provides @Provides
@ -147,14 +143,14 @@ public class AWSEC2ComputeServiceDependenciesModule extends EC2ComputeServiceDep
@Singleton @Singleton
@Named("AVAILABLE") @Named("AVAILABLE")
protected Predicate<PlacementGroup> placementGroupAvailable(PlacementGroupAvailable available) { protected Predicate<PlacementGroup> placementGroupAvailable(PlacementGroupAvailable available) {
return new RetryablePredicate<PlacementGroup>(available, 60, 1, TimeUnit.SECONDS); return retry(available, 60, 1, SECONDS);
} }
@Provides @Provides
@Singleton @Singleton
@Named("DELETED") @Named("DELETED")
protected Predicate<PlacementGroup> placementGroupDeleted(PlacementGroupDeleted deleted) { protected Predicate<PlacementGroup> placementGroupDeleted(PlacementGroupDeleted deleted) {
return new RetryablePredicate<PlacementGroup>(deleted, 60, 1, TimeUnit.SECONDS); return retry(deleted, 60, 1, SECONDS);
} }
@Provides @Provides

View File

@ -21,6 +21,8 @@ package org.jclouds.aws.ec2.services;
import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newTreeSet; import static com.google.common.collect.Sets.newTreeSet;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail; import static org.testng.Assert.fail;
@ -28,7 +30,6 @@ import static org.testng.Assert.fail;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Set; import java.util.Set;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.concurrent.TimeUnit;
import org.jclouds.aws.domain.Region; import org.jclouds.aws.domain.Region;
import org.jclouds.aws.ec2.AWSEC2ApiMetadata; import org.jclouds.aws.ec2.AWSEC2ApiMetadata;
@ -45,7 +46,6 @@ import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.compute.predicates.NodePredicates; import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.ec2.compute.domain.EC2HardwareBuilder; import org.jclouds.ec2.compute.domain.EC2HardwareBuilder;
import org.jclouds.ec2.domain.InstanceType; import org.jclouds.ec2.domain.InstanceType;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.scriptbuilder.domain.Statements; import org.jclouds.scriptbuilder.domain.Statements;
import org.jclouds.scriptbuilder.statements.java.InstallJDK; import org.jclouds.scriptbuilder.statements.java.InstallJDK;
import org.jclouds.scriptbuilder.statements.login.AdminAccess; import org.jclouds.scriptbuilder.statements.login.AdminAccess;
@ -54,6 +54,7 @@ import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.google.inject.Module; import com.google.inject.Module;
@ -71,8 +72,8 @@ public class PlacementGroupClientLiveTest extends BaseComputeServiceContextLiveT
} }
private AWSEC2Client client; private AWSEC2Client client;
private RetryablePredicate<PlacementGroup> availableTester; private Predicate<PlacementGroup> availableTester;
private RetryablePredicate<PlacementGroup> deletedTester; private Predicate<PlacementGroup> deletedTester;
private PlacementGroup group; private PlacementGroup group;
@Override @Override
@ -80,11 +81,8 @@ public class PlacementGroupClientLiveTest extends BaseComputeServiceContextLiveT
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
client = view.unwrap(AWSEC2ApiMetadata.CONTEXT_TOKEN).getApi(); client = view.unwrap(AWSEC2ApiMetadata.CONTEXT_TOKEN).getApi();
availableTester = retry(new PlacementGroupAvailable(client), 60, 1, SECONDS);
availableTester = new RetryablePredicate<PlacementGroup>(new PlacementGroupAvailable(client), 60, 1, deletedTester = retry(new PlacementGroupDeleted(client), 60, 1, SECONDS);
TimeUnit.SECONDS);
deletedTester = new RetryablePredicate<PlacementGroup>(new PlacementGroupDeleted(client), 60, 1, TimeUnit.SECONDS);
} }
@Test @Test

View File

@ -20,8 +20,10 @@ package org.jclouds.aws.ec2.services;
import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.in;
import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Iterables.getOnlyElement;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.from; import static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.from;
import static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.launchGroup; import static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.launchGroup;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
@ -40,11 +42,11 @@ import org.jclouds.aws.ec2.domain.SpotInstanceRequest;
import org.jclouds.aws.ec2.predicates.SpotInstanceRequestActive; import org.jclouds.aws.ec2.predicates.SpotInstanceRequestActive;
import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;
import org.jclouds.ec2.domain.InstanceType; import org.jclouds.ec2.domain.InstanceType;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet;
@ -61,7 +63,7 @@ public class SpotInstanceClientLiveTest extends BaseComputeServiceContextLiveTe
private static final int SPOT_DELAY_SECONDS = 600; private static final int SPOT_DELAY_SECONDS = 600;
private AWSEC2Client client; private AWSEC2Client client;
private RetryablePredicate<SpotInstanceRequest> activeTester; private Predicate<SpotInstanceRequest> activeTester;
private Set<SpotInstanceRequest> requests; private Set<SpotInstanceRequest> requests;
private AWSRunningInstance instance; private AWSRunningInstance instance;
private long start; private long start;
@ -71,8 +73,7 @@ public class SpotInstanceClientLiveTest extends BaseComputeServiceContextLiveTe
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
client = view.unwrap(AWSEC2ApiMetadata.CONTEXT_TOKEN).getApi(); client = view.unwrap(AWSEC2ApiMetadata.CONTEXT_TOKEN).getApi();
activeTester = new RetryablePredicate<SpotInstanceRequest>(new SpotInstanceRequestActive(client), activeTester = retry(new SpotInstanceRequestActive(client), SPOT_DELAY_SECONDS, 1, 1, SECONDS);
SPOT_DELAY_SECONDS, 1, 1, TimeUnit.SECONDS);
} }
@Test @Test

View File

@ -24,6 +24,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.BaseEncoding.base16; import static com.google.common.io.BaseEncoding.base16;
import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue; import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue;
import static org.jclouds.concurrent.FutureIterables.transformParallel; import static org.jclouds.concurrent.FutureIterables.transformParallel;
import static org.jclouds.util.Predicates2.retry;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@ -62,7 +63,6 @@ import org.jclouds.glesys.options.CreateServerOptions;
import org.jclouds.glesys.options.DestroyServerOptions; import org.jclouds.glesys.options.DestroyServerOptions;
import org.jclouds.location.predicates.LocationPredicates; import org.jclouds.location.predicates.LocationPredicates;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
@ -234,9 +234,7 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter<Server
@Override @Override
public void destroyNode(String id) { public void destroyNode(String id) {
new RetryablePredicate<String>(new Predicate<String>() { retry(new Predicate<String>() {
@Override
public boolean apply(String arg0) { public boolean apply(String arg0) {
try { try {
api.getServerApi().destroy(arg0, DestroyServerOptions.Builder.discardIp()); api.getServerApi().destroy(arg0, DestroyServerOptions.Builder.discardIp());
@ -245,7 +243,6 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter<Server
return false; return false;
} }
} }
}, timeouts.nodeTerminated).apply(id); }, timeouts.nodeTerminated).apply(id);
} }

View File

@ -18,16 +18,15 @@
*/ */
package org.jclouds.glesys.features; package org.jclouds.glesys.features;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.jclouds.glesys.domain.Archive; import org.jclouds.glesys.domain.Archive;
import org.jclouds.glesys.domain.ArchiveAllowedArguments; import org.jclouds.glesys.domain.ArchiveAllowedArguments;
import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest; import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -48,12 +47,11 @@ public class ArchiveApiLiveTest extends BaseGleSYSApiLiveTest {
api = gleContext.getApi().getArchiveApi(); api = gleContext.getApi().getArchiveApi();
archiveUser = gleContext.getIdentity().toLowerCase() + "_test9"; archiveUser = gleContext.getIdentity().toLowerCase() + "_test9";
archiveCounter = new RetryablePredicate<Integer>( archiveCounter = retry(new Predicate<Integer>() {
new Predicate<Integer>() { public boolean apply(Integer value) {
public boolean apply(Integer value){ return api.list().size() == value;
return api.list().size() == value; }
} }, 30, 1, SECONDS);
}, 30, 1, TimeUnit.SECONDS);
} }
@AfterClass(groups = { "integration", "live" }) @AfterClass(groups = { "integration", "live" })
@ -67,7 +65,7 @@ public class ArchiveApiLiveTest extends BaseGleSYSApiLiveTest {
private ArchiveApi api; private ArchiveApi api;
private String archiveUser; private String archiveUser;
private RetryablePredicate<Integer> archiveCounter; private Predicate<Integer> archiveCounter;
@Test @Test
public void testAllowedArguments() throws Exception { public void testAllowedArguments() throws Exception {
@ -111,12 +109,11 @@ public class ArchiveApiLiveTest extends BaseGleSYSApiLiveTest {
public void testResizeArchive() throws Exception { public void testResizeArchive() throws Exception {
api.resize(archiveUser, 20); api.resize(archiveUser, 20);
assertTrue(new RetryablePredicate<String>( assertTrue(retry(new Predicate<String>() {
new Predicate<String>() { public boolean apply(String value) {
public boolean apply(String value){ return api.get(archiveUser) != null && value.equals(api.get(archiveUser).getTotalSize());
return api.get(archiveUser) != null && value.equals(api.get(archiveUser).getTotalSize()); }
} }, 30, 1, SECONDS).apply("20 GB"));
}, 30, 1, TimeUnit.SECONDS).apply("20 GB"));
} }
} }

View File

@ -18,19 +18,19 @@
*/ */
package org.jclouds.glesys.features; package org.jclouds.glesys.features;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.glesys.domain.Domain; import org.jclouds.glesys.domain.Domain;
import org.jclouds.glesys.domain.DomainRecord; import org.jclouds.glesys.domain.DomainRecord;
import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest; import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest;
import org.jclouds.glesys.options.DomainOptions; import org.jclouds.glesys.options.DomainOptions;
import org.jclouds.glesys.options.UpdateRecordOptions; import org.jclouds.glesys.options.UpdateRecordOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -51,18 +51,16 @@ public class DomainApiLiveTest extends BaseGleSYSApiLiveTest {
super.setupContext(); super.setupContext();
testDomain = identity.toLowerCase() + "-domain.jclouds.org"; testDomain = identity.toLowerCase() + "-domain.jclouds.org";
api = gleContext.getApi().getDomainApi(); api = gleContext.getApi().getDomainApi();
domainCounter = new RetryablePredicate<Integer>( domainCounter = retry(new Predicate<Integer>() {
new Predicate<Integer>() { public boolean apply(Integer value) {
public boolean apply(Integer value) { return api.list().size() == value;
return api.list().size() == value; }
} }, 30, 1, SECONDS);
}, 30, 1, TimeUnit.SECONDS); recordCounter = retry(new Predicate<Integer>() {
recordCounter = new RetryablePredicate<Integer>( public boolean apply(Integer value) {
new Predicate<Integer>() { return api.listRecords(testDomain).size() == value;
public boolean apply(Integer value) { }
return api.listRecords(testDomain).size() == value; }, 30, 1, SECONDS);
}
}, 30, 1, TimeUnit.SECONDS);
try { try {
api.delete(testDomain); api.delete(testDomain);
@ -82,8 +80,8 @@ public class DomainApiLiveTest extends BaseGleSYSApiLiveTest {
} }
private DomainApi api; private DomainApi api;
private RetryablePredicate<Integer> domainCounter; private Predicate<Integer> domainCounter;
private RetryablePredicate<Integer> recordCounter; private Predicate<Integer> recordCounter;
@Test @Test
public void testGetDomain() throws Exception { public void testGetDomain() throws Exception {

View File

@ -18,13 +18,13 @@
*/ */
package org.jclouds.glesys.features; package org.jclouds.glesys.features;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.jclouds.glesys.domain.EmailAccount; import org.jclouds.glesys.domain.EmailAccount;
import org.jclouds.glesys.domain.EmailAlias; import org.jclouds.glesys.domain.EmailAlias;
import org.jclouds.glesys.domain.EmailOverview; import org.jclouds.glesys.domain.EmailOverview;
@ -32,7 +32,6 @@ import org.jclouds.glesys.domain.EmailOverviewDomain;
import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest; import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest;
import org.jclouds.glesys.options.CreateAccountOptions; import org.jclouds.glesys.options.CreateAccountOptions;
import org.jclouds.glesys.options.UpdateAccountOptions; import org.jclouds.glesys.options.UpdateAccountOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -62,11 +61,11 @@ public class EmailAccountApiLiveTest extends BaseGleSYSApiLiveTest {
createDomain(testDomain); createDomain(testDomain);
emailAccountCounter = new RetryablePredicate<Integer>(new Predicate<Integer>() { emailAccountCounter = retry(new Predicate<Integer>() {
public boolean apply(Integer value) { public boolean apply(Integer value) {
return api.listDomain(testDomain).size() == value; return api.listDomain(testDomain).size() == value;
} }
}, 180, 5, TimeUnit.SECONDS); }, 180, 5, SECONDS);
assertTrue(emailAccountCounter.apply(0)); assertTrue(emailAccountCounter.apply(0));
@ -86,7 +85,7 @@ public class EmailAccountApiLiveTest extends BaseGleSYSApiLiveTest {
private EmailAccountApi api; private EmailAccountApi api;
private String testDomain; private String testDomain;
private RetryablePredicate<Integer> emailAccountCounter; private Predicate<Integer> emailAccountCounter;
@Test @Test
public void testCreateEmail() { public void testCreateEmail() {

View File

@ -18,12 +18,13 @@
*/ */
package org.jclouds.glesys.features; package org.jclouds.glesys.features;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer; import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer;
import org.jclouds.glesys.domain.Console; import org.jclouds.glesys.domain.Console;
@ -31,6 +32,7 @@ import org.jclouds.glesys.domain.OSTemplate;
import org.jclouds.glesys.domain.ResourceStatus; import org.jclouds.glesys.domain.ResourceStatus;
import org.jclouds.glesys.domain.ResourceUsage; import org.jclouds.glesys.domain.ResourceUsage;
import org.jclouds.glesys.domain.Server; import org.jclouds.glesys.domain.Server;
import org.jclouds.glesys.domain.Server.State;
import org.jclouds.glesys.domain.ServerDetails; import org.jclouds.glesys.domain.ServerDetails;
import org.jclouds.glesys.domain.ServerLimit; import org.jclouds.glesys.domain.ServerLimit;
import org.jclouds.glesys.domain.ServerStatus; import org.jclouds.glesys.domain.ServerStatus;
@ -39,7 +41,6 @@ import org.jclouds.glesys.options.CloneServerOptions;
import org.jclouds.glesys.options.DestroyServerOptions; import org.jclouds.glesys.options.DestroyServerOptions;
import org.jclouds.glesys.options.ServerStatusOptions; import org.jclouds.glesys.options.ServerStatusOptions;
import org.jclouds.glesys.options.UpdateServerOptions; import org.jclouds.glesys.options.UpdateServerOptions;
import org.jclouds.predicates.RetryablePredicate;
import org.testng.annotations.AfterClass; import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeMethod;
@ -247,26 +248,22 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest {
testServerId2 = testServer2.getId(); testServerId2 = testServer2.getId();
RetryablePredicate<Server.State> cloneChecker = new ServerStatusChecker(api, testServerId2, 300, 10, TimeUnit.SECONDS); Predicate<State> cloneChecker = statusChecker(api, testServerId2);
assertTrue(cloneChecker.apply(Server.State.STOPPED)); assertTrue(cloneChecker.apply(Server.State.STOPPED));
api.start(testServer2.getId()); api.start(testServer2.getId());
// TODO ServerStatus==STOPPED suggests the previous call to start should have worked // TODO ServerStatus==STOPPED suggests the previous call to start should have worked
cloneChecker = new RetryablePredicate<Server.State>( cloneChecker = retry(new Predicate<Server.State>() {
new Predicate<Server.State>() { public boolean apply(Server.State value) {
ServerStatus status = api.getStatus(testServerId2, ServerStatusOptions.Builder.state());
public boolean apply(Server.State value) { if (status.getState() == value) {
ServerStatus status = api.getStatus(testServerId2, ServerStatusOptions.Builder.state()); return true;
if (status.getState() == value) { }
return true; api.start(testServerId2);
} return false;
}
api.start(testServerId2); }, 600, 30, SECONDS);
return false;
}
}, 600, 30, TimeUnit.SECONDS);
assertTrue(cloneChecker.apply(Server.State.RUNNING)); assertTrue(cloneChecker.apply(Server.State.RUNNING));
} }

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