-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathRetryHelper.java
More file actions
252 lines (211 loc) · 8.11 KB
/
RetryHelper.java
File metadata and controls
252 lines (211 loc) · 8.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gcloud;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.StrictMath.max;
import static java.lang.StrictMath.min;
import static java.lang.StrictMath.pow;
import static java.lang.StrictMath.random;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Stopwatch;
import java.io.InterruptedIOException;
import java.nio.channels.ClosedByInterruptException;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utility class for retrying operations. For more details about the parameters, see
* {@link RetryParams}. If the request is never successful, a {@link RetriesExhaustedException} will
* be thrown.
*
* @param <V> return value of the closure that is being run with retries
*/
public class RetryHelper<V> {
private static final Logger log = Logger.getLogger(RetryHelper.class.getName());
private final Stopwatch stopwatch;
private final Callable<V> callable;
private final RetryParams params;
private final ExceptionHandler exceptionHandler;
private int attemptNumber;
private static final ThreadLocal<Context> context = new ThreadLocal<>();
public static class RetryHelperException extends RuntimeException {
private static final long serialVersionUID = -2907061015610448235L;
RetryHelperException() {}
RetryHelperException(String message) {
super(message);
}
RetryHelperException(Throwable cause) {
super(cause);
}
RetryHelperException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Thrown when a RetryHelper failed to complete its work due to interruption. Throwing this
* exception also sets the thread interrupt flag.
*/
public static final class RetryInterruptedException extends RetryHelperException {
private static final long serialVersionUID = 1678966737697204885L;
RetryInterruptedException() {}
/**
* Sets the caller thread interrupt flag and throws {@code RetryInterruptedException}.
*/
public static void propagate() throws RetryInterruptedException {
Thread.currentThread().interrupt();
throw new RetryInterruptedException();
}
}
/**
* Thrown when a RetryHelper has attempted the maximum number of attempts allowed by RetryParams
* and was not successful.
*/
public static final class RetriesExhaustedException extends RetryHelperException {
private static final long serialVersionUID = 780199686075408083L;
RetriesExhaustedException(String message) {
super(message);
}
RetriesExhaustedException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Thrown when RetryHelper callable has indicate it should not be retried.
*/
public static final class NonRetriableException extends RetryHelperException {
private static final long serialVersionUID = -2331878521983499652L;
NonRetriableException(Throwable throwable) {
super(throwable);
}
}
static class Context {
private final RetryHelper<?> helper;
Context(RetryHelper<?> helper) {
this.helper = helper;
}
public RetryParams getRetryParams() {
return helper.params;
}
public int getAttemptNumber() {
return helper.attemptNumber;
}
}
@VisibleForTesting
static void setContext(Context ctx) {
if (ctx == null) {
context.remove();
} else {
context.set(ctx);
}
}
static Context getContext() {
return context.get();
}
@VisibleForTesting
RetryHelper(Callable<V> callable, RetryParams params, ExceptionHandler exceptionHandler,
Stopwatch stopwatch) {
this.callable = checkNotNull(callable);
this.params = checkNotNull(params);
this.stopwatch = checkNotNull(stopwatch);
this.exceptionHandler = checkNotNull(exceptionHandler);
exceptionHandler.verifyCaller(callable);
}
@Override
public String toString() {
ToStringHelper toStringHelper = MoreObjects.toStringHelper(this);
toStringHelper.add("params", params);
toStringHelper.add("stopwatch", stopwatch);
toStringHelper.add("attemptNumber", attemptNumber);
toStringHelper.add("callable", callable);
toStringHelper.add("exceptionHandler", exceptionHandler);
return toStringHelper.toString();
}
private V doRetry() throws RetryHelperException {
stopwatch.start();
while (true) {
attemptNumber++;
Exception exception;
try {
V value = callable.call();
if (attemptNumber > 1 && log.isLoggable(Level.FINE)) {
log.fine(this + ": attempt #" + attemptNumber + " succeeded");
}
return value;
} catch (InterruptedException | InterruptedIOException | ClosedByInterruptException e) {
if (!exceptionHandler.shouldRetry(e)) {
RetryInterruptedException.propagate();
}
exception = e;
} catch (Exception e) {
if (!exceptionHandler.shouldRetry(e)) {
throw new NonRetriableException(e);
}
exception = e;
}
if (attemptNumber >= params.getRetryMaxAttempts()
|| attemptNumber >= params.getRetryMinAttempts()
&& stopwatch.elapsed(MILLISECONDS) >= params.getTotalRetryPeriodMillis()) {
throw new RetriesExhaustedException(this + ": Too many failures, giving up", exception);
}
long sleepDurationMillis = getSleepDuration(params, attemptNumber);
if (log.isLoggable(Level.FINE)) {
log.fine(this + ": Attempt #" + attemptNumber + " failed [" + exception
+ "], sleeping for " + sleepDurationMillis + " ms");
}
try {
Thread.sleep(sleepDurationMillis);
} catch (InterruptedException e) {
// propagate as RetryInterruptedException
RetryInterruptedException.propagate();
}
}
}
@VisibleForTesting
static long getSleepDuration(RetryParams retryParams, int attemptsSoFar) {
long initialDelay = retryParams.getInitialRetryDelayMillis();
double backoffFactor = retryParams.getRetryDelayBackoffFactor();
long maxDelay = retryParams.getMaxRetryDelayMillis();
long retryDelay = getExponentialValue(initialDelay, backoffFactor, maxDelay, attemptsSoFar);
return (long) ((random() / 2.0 + .75) * retryDelay);
}
private static long getExponentialValue(long initialDelay, double backoffFactor, long maxDelay,
int attemptsSoFar) {
return (long) min(maxDelay, pow(backoffFactor, max(1, attemptsSoFar) - 1) * initialDelay);
}
public static <V> V runWithRetries(Callable<V> callable) throws RetryHelperException {
return runWithRetries(callable, RetryParams.getDefaultInstance(),
ExceptionHandler.getDefaultInstance());
}
public static <V> V runWithRetries(Callable<V> callable, RetryParams params,
ExceptionHandler exceptionHandler) throws RetryHelperException {
return runWithRetries(callable, params, exceptionHandler, Stopwatch.createUnstarted());
}
@VisibleForTesting
static <V> V runWithRetries(Callable<V> callable, RetryParams params,
ExceptionHandler exceptionHandler, Stopwatch stopwatch) throws RetryHelperException {
RetryHelper<V> retryHelper = new RetryHelper<>(callable, params, exceptionHandler, stopwatch);
Context previousContext = getContext();
setContext(new Context(retryHelper));
try {
return retryHelper.doRetry();
} finally {
setContext(previousContext);
}
}
}