-
Notifications
You must be signed in to change notification settings - Fork 467
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Get latest counter before attempting a take to ensure take succeeds #886
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
/* | ||
* Copyright 2020 Amazon.com, Inc. or its affiliates. | ||
* 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 software.amazon.kinesis.common; | ||
|
||
|
||
public class CommonCalculations { | ||
|
||
|
||
/** | ||
* Convenience method for calculating renewer intervals in milliseconds. | ||
* | ||
* @param leaseDurationMillis Duration of a lease | ||
* @param epsilonMillis Allow for some variance when calculating lease expirations | ||
*/ | ||
public static long getRenewerTakerIntervalMillis(long leaseDurationMillis, long epsilonMillis) { | ||
return leaseDurationMillis / 3 - epsilonMillis; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -42,6 +42,8 @@ | |
import software.amazon.kinesis.metrics.MetricsScope; | ||
import software.amazon.kinesis.metrics.MetricsUtil; | ||
|
||
import static software.amazon.kinesis.common.CommonCalculations.getRenewerTakerIntervalMillis; | ||
|
||
/** | ||
* An implementation of {@link LeaseTaker} that uses DynamoDB via {@link LeaseRefresher}. | ||
*/ | ||
|
@@ -50,7 +52,7 @@ | |
public class DynamoDBLeaseTaker implements LeaseTaker { | ||
private static final int TAKE_RETRIES = 3; | ||
private static final int SCAN_RETRIES = 1; | ||
private long veryOldLeaseDurationNanosMultiplier = 3; | ||
private static final double RENEWAL_SLACK_PERCENTAGE = 0.5; | ||
|
||
// See note on TAKE_LEASES_DIMENSION(Callable) for why we have this callable. | ||
private static final Callable<Long> SYSTEM_CLOCK_CALLABLE = System::nanoTime; | ||
|
@@ -60,20 +62,23 @@ public class DynamoDBLeaseTaker implements LeaseTaker { | |
private final LeaseRefresher leaseRefresher; | ||
private final String workerIdentifier; | ||
private final long leaseDurationNanos; | ||
private final long leaseRenewalIntervalMillis; | ||
private final MetricsFactory metricsFactory; | ||
|
||
final Map<String, Lease> allLeases = new HashMap<>(); | ||
// TODO: Remove these defaults and use the defaults in the config | ||
private int maxLeasesForWorker = Integer.MAX_VALUE; | ||
private int maxLeasesToStealAtOneTime = 1; | ||
|
||
private long veryOldLeaseDurationNanosMultiplier = 3; | ||
private long lastScanTimeNanos = 0L; | ||
|
||
final Map<String, Lease> allLeases = new HashMap<>(); | ||
|
||
public DynamoDBLeaseTaker(LeaseRefresher leaseRefresher, String workerIdentifier, long leaseDurationMillis, | ||
final MetricsFactory metricsFactory) { | ||
this.leaseRefresher = leaseRefresher; | ||
this.workerIdentifier = workerIdentifier; | ||
this.leaseRenewalIntervalMillis = getRenewerTakerIntervalMillis(leaseDurationMillis, 0); | ||
this.leaseDurationNanos = TimeUnit.MILLISECONDS.toNanos(leaseDurationMillis); | ||
this.metricsFactory = metricsFactory; | ||
} | ||
|
@@ -139,12 +144,12 @@ public Map<String, Lease> takeLeases() throws DependencyException, InvalidStateE | |
* Internal implementation of TAKE_LEASES_DIMENSION. Takes a callable that can provide the time to enable test cases | ||
* without Thread.sleep. Takes a callable instead of a raw time value because the time needs to be computed as-of | ||
* immediately after the scan. | ||
* | ||
* | ||
* @param timeProvider | ||
* Callable that will supply the time | ||
* | ||
* | ||
* @return map of lease key to taken lease | ||
* | ||
* | ||
* @throws DependencyException | ||
* @throws InvalidStateException | ||
*/ | ||
|
@@ -156,6 +161,7 @@ synchronized Map<String, Lease> takeLeases(Callable<Long> timeProvider) | |
final MetricsScope scope = MetricsUtil.createMetricsWithOperation(metricsFactory, TAKE_LEASES_DIMENSION); | ||
|
||
long startTime = System.currentTimeMillis(); | ||
long updateAllLeasesTotalTimeMillis; | ||
boolean success = false; | ||
|
||
ProvisionedThroughputException lastException = null; | ||
|
@@ -173,19 +179,23 @@ synchronized Map<String, Lease> takeLeases(Callable<Long> timeProvider) | |
} | ||
} | ||
} finally { | ||
updateAllLeasesTotalTimeMillis = System.currentTimeMillis() - startTime; | ||
MetricsUtil.addWorkerIdentifier(scope, workerIdentifier); | ||
MetricsUtil.addSuccessAndLatency(scope, "ListLeases", success, startTime, MetricsLevel.DETAILED); | ||
} | ||
|
||
|
||
if (lastException != null) { | ||
log.error("Worker {} could not scan leases table, aborting TAKE_LEASES_DIMENSION. Exception caught by" | ||
+ " last retry:", workerIdentifier, lastException); | ||
+ " last retry:", workerIdentifier, lastException); | ||
return takenLeases; | ||
} | ||
|
||
List<Lease> expiredLeases = getExpiredLeases(); | ||
|
||
Set<Lease> leasesToTake = computeLeasesToTake(expiredLeases); | ||
leasesToTake = updateStaleLeasesWithLatestState(updateAllLeasesTotalTimeMillis, leasesToTake); | ||
|
||
Set<String> untakenLeaseKeys = new HashSet<>(); | ||
|
||
for (Lease lease : leasesToTake) { | ||
|
@@ -233,6 +243,33 @@ synchronized Map<String, Lease> takeLeases(Callable<Long> timeProvider) | |
return takenLeases; | ||
} | ||
|
||
/** | ||
* If update all leases takes longer than the lease renewal time, | ||
* we fetch the latest lease info for the given leases that are marked for lease steal. | ||
* If nothing is found (or any transient network error occurs), | ||
* we default to the last known state of the lease | ||
* | ||
* @param updateAllLeasesEndTime How long it takes for update all leases to complete | ||
* @return set of leases to take. | ||
*/ | ||
private Set<Lease> updateStaleLeasesWithLatestState(long updateAllLeasesEndTime, | ||
Set<Lease> leasesToTake) { | ||
if (updateAllLeasesEndTime > leaseRenewalIntervalMillis * RENEWAL_SLACK_PERCENTAGE) { | ||
leasesToTake = leasesToTake.stream().map(lease -> { | ||
if (lease.isMarkedForLeaseSteal()) { | ||
try { | ||
return leaseRefresher.getLease(lease.leaseKey()); | ||
} catch (DependencyException | InvalidStateException | ProvisionedThroughputException e) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this needs to be addressed The log line information doesn't really make sense. You can keep the original log line as is, but explain why we would run into getting these exception in the first place There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "Unable to retrieve the current lease while refreshing the stale lease" this means that we know for a fact that the leases being refreshed are stale while in fact they can be just the same as in DDB. This is not accurate. You can explain in comment naming different cases we run into exceptions. "Like while we tried to update the stale leases" <- i am not sure this is the right reason why we would run into such exception. He might have confused it with a conditional update; while this is in fact just a get ddb request. I am guessing his intention is we explain how we would run into dependencyException and invalidStateException There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here we are trying to update the local copy of the leases with latest info in the event of leases going stale. Note that we already fetched the leases from ddb table just a while ago, but now we want to get their latest state in order to successfully steal the leases. Having a message like "Failed to fetch latest state of the lease that needs to be stolen" would help. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can you add leasekey to the msg There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
log.warn("Failed to fetch latest state of the lease {} that needs to be stolen, " | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. added |
||
+ "defaulting to existing lease", lease.leaseKey(), e); | ||
} | ||
} | ||
return lease; | ||
}).collect(Collectors.toSet()); | ||
} | ||
return leasesToTake; | ||
} | ||
|
||
/** Package access for testing purposes. | ||
* | ||
* @param strings | ||
|
@@ -249,17 +286,17 @@ static String stringJoin(Collection<String> strings, String delimiter) { | |
builder.append(string); | ||
needDelimiter = true; | ||
} | ||
|
||
return builder.toString(); | ||
} | ||
|
||
/** | ||
* Scan all leases and update lastRenewalTime. Add new leases and delete old leases. | ||
* | ||
* | ||
* @param timeProvider callable that supplies the current time | ||
* | ||
* | ||
* @return list of expired leases, possibly empty, never null. | ||
* | ||
* | ||
* @throws ProvisionedThroughputException if listLeases fails due to lack of provisioned throughput | ||
* @throws InvalidStateException if the lease table does not exist | ||
* @throws DependencyException if listLeases fails in an unexpected way | ||
|
@@ -336,7 +373,7 @@ private List<Lease> getExpiredLeases() { | |
|
||
/** | ||
* Compute the number of leases I should try to take based on the state of the system. | ||
* | ||
* | ||
* @param expiredLeases list of leases we determined to be expired | ||
* @return set of leases to take. | ||
*/ | ||
|
@@ -461,11 +498,11 @@ private Set<Lease> computeLeasesToTake(List<Lease> expiredLeases) { | |
/** | ||
* Choose leases to steal by randomly selecting one or more (up to max) from the most loaded worker. | ||
* Stealing rules: | ||
* | ||
* | ||
* Steal up to maxLeasesToStealAtOneTime leases from the most loaded worker if | ||
* a) he has > target leases and I need >= 1 leases : steal min(leases needed, maxLeasesToStealAtOneTime) | ||
* b) he has == target leases and I need > 1 leases : steal 1 | ||
* | ||
* | ||
* @param leaseCounts map of workerIdentifier to lease count | ||
* @param needed # of leases needed to reach the target leases for the worker | ||
* @param target target # of leases per worker | ||
|
@@ -530,15 +567,16 @@ private List<Lease> chooseLeasesToSteal(Map<String, Integer> leaseCounts, int ne | |
// Return random ones | ||
Collections.shuffle(candidates); | ||
int toIndex = Math.min(candidates.size(), numLeasesToSteal); | ||
leasesToSteal.addAll(candidates.subList(0, toIndex)); | ||
|
||
leasesToSteal.addAll(candidates.subList(0, toIndex).stream() | ||
.map(lease -> lease.isMarkedForLeaseSteal(true)) | ||
.collect(Collectors.toList())); | ||
return leasesToSteal; | ||
} | ||
|
||
/** | ||
* Count leases by host. Always includes myself, but otherwise only includes hosts that are currently holding | ||
* leases. | ||
* | ||
* | ||
* @param expiredLeases list of leases that are currently expired | ||
* @return map of workerIdentifier to lease count | ||
*/ | ||
|
@@ -563,11 +601,7 @@ Map<String, Integer> computeLeaseCounts(List<Lease> expiredLeases) { | |
} | ||
|
||
// If I have no leases, I wasn't represented in leaseCounts. Let's fix that. | ||
Integer myCount = leaseCounts.get(workerIdentifier); | ||
if (myCount == null) { | ||
myCount = 0; | ||
leaseCounts.put(workerIdentifier, myCount); | ||
} | ||
leaseCounts.putIfAbsent(workerIdentifier, 0); | ||
|
||
return leaseCounts; | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is this essentially veryOldLeaseDurationNanosMultiplier?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yep, being extracted into a static function
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you use veryOldLeaseDurationNanosMultiplier instead?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
it's not from my commit, do you have strong preference about it?