Skip to content

Commit 63462f1

Browse files
authored
Merge pull request #1 from volcengine/producer_close
Producer close
2 parents bef2ca5 + 18cdff1 commit 63462f1

12 files changed

Lines changed: 425 additions & 112 deletions

File tree

.gitignore

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,8 @@ scripts/build.out
88
*.swp
99
.classpath
1010
.factorypath
11-
.project
11+
.project
12+
13+
# vscode
14+
.vscode
15+
.devcontainer

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<h1 align="center"><img src="https://iam.volccdn.com/obj/volcengine-public/pic/volcengine-icon.png"></h1>
2-
<h1 align="center">火山引擎Android SDK for TLS</h1>
2+
<h1 align="center">火山引擎Android SDK for TLS</h1>
33
欢迎使用火山引擎SDK for Android,本文档为您介绍如何获取及调用SDK。
44

55
## 前置准备
@@ -28,7 +28,7 @@ Key。更多信息可参考[访问密钥帮助文档](https://www.volcengine.com
2828
1. 创建安卓项目。
2929
2. Gradle配置mavenCentral(),并引入SDK。
3030
```xml
31-
implementation 'com.volcengine:volc-tls-android-sdk:1.1.4'
31+
implementation 'com.volcengine:volc-tls-android-sdk:1.1.5'
3232
```
3333
如果有依赖冲突,请使用指定你需要的版本(以okhttp为例子)
3434
```xml

pom.xml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
55
<modelVersion>4.0.0</modelVersion>
66
<groupId>com.volcengine</groupId>
7-
<version>1.1.4</version>
7+
<version>1.1.5</version>
88
<artifactId>volc-tls-android-sdk</artifactId>
99
<name>volc-tls-android-sdk</name>
1010
<url>https://www.volcengine.com/docs/6470/516236</url>
@@ -207,11 +207,11 @@
207207
<distributionManagement>
208208
<snapshotRepository>
209209
<id>sonatype-nexus-staging</id>
210-
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
210+
<url>https://ossrh-staging-api.central.sonatype.com/content/repositories/snapshots</url>
211211
</snapshotRepository>
212212
<repository>
213213
<id>sonatype-nexus-staging</id>
214-
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
214+
<url>https://ossrh-staging-api.central.sonatype.com/service/local/staging/deploy/maven2/</url>
215215
</repository>
216216
</distributionManagement>
217217
</project>

src/main/java/com/volcengine/model/tls/producer/BatchLog.java

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ public class BatchLog implements Delayed {
3030
EvictingQueue<Attempt> reservedAttempts;
3131
int attemptCount;
3232
long createMs;
33+
long nextRetryMs;
34+
long retryBackoffMs;
35+
long maxRetryBackoffMs;
36+
long baseRetryBackoffMs;
37+
long baseIncreaseBackoffMs;
38+
3339
private static final Logger LOG = LoggerFactory.getLogger(BatchLog.class);
3440

3541
private BatchLog() {
@@ -43,6 +49,10 @@ public BatchLog(BatchKey batchKey, ProducerConfig producerConfig) {
4349
this.attemptCount = 0;
4450
this.reservedAttempts = EvictingQueue.create(producerConfig.getMaxReservedAttempts());
4551
this.createMs = System.currentTimeMillis();
52+
this.retryBackoffMs = 0;
53+
this.maxRetryBackoffMs = 10 * 1000;
54+
this.baseRetryBackoffMs = 1000;
55+
this.baseIncreaseBackoffMs = 1000;
4656
}
4757

4858
public boolean tryAdd(PutLogRequest.LogGroup logGroup, int batchSize, CallBack callBack) {
@@ -89,6 +99,17 @@ public synchronized void fireCallbacks() {
8999
fireCallbacks(result);
90100
}
91101

102+
public void handleNextTry() {
103+
if (attemptCount == 1) {
104+
retryBackoffMs += baseRetryBackoffMs;
105+
} else {
106+
double increaseBackoffMs = Math.random() * baseIncreaseBackoffMs;
107+
retryBackoffMs += (long) increaseBackoffMs;
108+
}
109+
retryBackoffMs = Math.min(retryBackoffMs, maxRetryBackoffMs);
110+
nextRetryMs = System.currentTimeMillis() + retryBackoffMs;
111+
}
112+
92113
private void fireCallbacks(Result result) {
93114
for (CallBack callBack : callBackList) {
94115
callBack.onComplete(result);
@@ -97,12 +118,12 @@ private void fireCallbacks(Result result) {
97118

98119
@Override
99120
public int compareTo(Delayed o) {
100-
return 0;
121+
return (int) (nextRetryMs - ((BatchLog) o).getNextRetryMs());
101122
}
102123

103124
@Override
104125
public long getDelay(TimeUnit unit) {
105-
return unit.convert(producerConfig.getLingerMs(), TimeUnit.MILLISECONDS);
126+
return unit.convert(nextRetryMs - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
106127
}
107128

108129
@Data
@@ -169,11 +190,14 @@ public String toString() {
169190
"batchKey=" + batchKey +
170191
", currentBatchSize=" + currentBatchSize +
171192
", currentBatchCount=" + currentBatchCount +
172-
", callBackList=" + callBackList +
173-
", producerConfig=" + producerConfig +
174193
", reservedAttempts=" + reservedAttempts +
175194
", attemptCount=" + attemptCount +
176195
", createMs=" + createMs +
196+
", nextRetryMs=" + nextRetryMs +
197+
", retryBackoffMs=" + retryBackoffMs +
198+
", maxRetryBackoffMs=" + nextRetryMs +
199+
", baseRetryBackoffMs=" + baseRetryBackoffMs +
200+
", baseIncreaseBackoffMs=" + baseIncreaseBackoffMs +
177201
'}';
178202
}
179203
}

src/main/java/com/volcengine/service/tls/BatchHandler.java

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
66

7+
import java.util.ArrayList;
8+
import java.util.List;
79
import java.util.concurrent.BlockingQueue;
810
import java.util.concurrent.Semaphore;
911
import java.util.concurrent.atomic.AtomicInteger;
@@ -23,12 +25,17 @@ public BatchHandler(String name, Semaphore memoryLock, BlockingQueue<BatchLog> b
2325
this.batchQueue = batchQueue;
2426
this.batchCount = batchCount;
2527
this.name = name;
26-
this.closed = false;
2728
}
2829

2930
@Override
3031
public void run() {
3132
handleBatches();
33+
34+
List<BatchLog> batchLogList = new ArrayList<>();
35+
batchQueue.drainTo(batchLogList);
36+
for (BatchLog batchLog : batchLogList) {
37+
handle(batchLog);
38+
}
3239
}
3340

3441
private void handleBatches() {
@@ -43,9 +50,20 @@ private void handleBatches() {
4350
}
4451

4552
private void handle(BatchLog batch) {
46-
batch.fireCallbacks();
47-
batchCount.decrementAndGet();
48-
memoryLock.release(batch.getCurrentBatchSize());
53+
try {
54+
batch.fireCallbacks();
55+
} catch (Throwable t) {
56+
LOG.error("batch fire callbacks failed: ", t);
57+
} finally {
58+
batchCount.decrementAndGet();
59+
memoryLock.release(batch.getCurrentBatchSize());
60+
}
61+
}
62+
63+
@Override
64+
public void start() {
65+
this.closed = false;
66+
super.start();
4967
}
5068

5169
public void close() {

src/main/java/com/volcengine/service/tls/LogDispatcher.java

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,7 @@ public class LogDispatcher {
2525
private final BlockingQueue<BatchLog> successQueue;
2626
private final BlockingQueue<BatchLog> failureQueue;
2727
private static final Logger LOG = LoggerFactory.getLogger(LogDispatcher.class);
28-
private final AtomicInteger addLogLock = new AtomicInteger(0);
29-
private volatile boolean closed = true;
28+
private volatile boolean closed;
3029
private final Semaphore memoryLock;
3130
private final AtomicInteger batchCount;
3231
private final RetryManager retryManager;
@@ -50,7 +49,6 @@ public LogDispatcher(ProducerConfig producerConfig, String producerName, Blockin
5049
this.batchCount = batchCount;
5150
this.retryManager = retryManager;
5251
this.client = ClientBuilder.newClient(producerConfig.getClientConfig());
53-
this.closed = false;
5452
}
5553

5654
public TLSLogClient getClient() {
@@ -62,19 +60,19 @@ public ConcurrentHashMap<BatchLog.BatchKey, BatchLog.BatchManager> getBatches()
6260
}
6361

6462
public void start() {
63+
this.closed = false;
6564
LOG.info(String.format("log dispatcher %s started and client init success", producerName));
6665
}
6766

6867
public ExecutorService getExecutorService() {
6968
return this.executorService;
7069
}
7170

72-
public void close() throws InterruptedException, LogException {
73-
executorService.shutdown();
71+
public void close() {
7472
this.closed = true;
7573
}
7674

77-
public void closeNow() throws InterruptedException, LogException {
75+
public void closeNow() {
7876
executorService.shutdownNow();
7977
this.closed = true;
8078
}
@@ -99,9 +97,7 @@ public void resetAccessKeyToken(String accessKey, String secretKey, String secur
9997

10098
public void addBatch(String hashKey, String topicId, String source, String filename,
10199
PutLogRequest.LogGroup logGroup, CallBack callBack) throws InterruptedException, LogException {
102-
addLogLock.incrementAndGet();
103100
doAdd(hashKey, topicId, source, filename, logGroup, callBack);
104-
addLogLock.decrementAndGet();
105101
}
106102

107103
private void doAdd(String hashKey, String topicId, String source, String filename,
@@ -121,6 +117,8 @@ private void doAdd(String hashKey, String topicId, String source, String filenam
121117
} else {
122118
boolean acquired = memoryLock.tryAcquire(batchSize, maxBlockMs, TimeUnit.MILLISECONDS);
123119
if (!acquired) {
120+
LOG.warn(String.format("Failed to acquire memory within the configured max blocking time %d ms, requiredSizeInBytes=%d, availableSizeInBytes=%d",
121+
producerConfig.getMaxBlockMs(), batchSize, memoryLock.availablePermits()));
124122
throw new LogException("Producer Error", "dispatcher %s try acquire memory lock failed", null);
125123
}
126124
}
@@ -132,9 +130,8 @@ private void doAdd(String hashKey, String topicId, String source, String filenam
132130
addToBatchManager(batchKey, logGroup, callBack, batchSize, batchManager);
133131
}
134132
} catch (Exception e) {
135-
throw new LogException("Producer Error", "dispatcher add batch concurrent error", null);
136-
} finally {
137133
memoryLock.release(batchSize);
134+
throw new LogException("Producer Error", "dispatcher add batch concurrent error", null);
138135
}
139136
}
140137

@@ -146,7 +143,7 @@ private int calculateSize(PutLogRequest.LogGroup logGroup) {
146143
}
147144

148145
private void addToBatchManager(BatchLog.BatchKey batchKey, PutLogRequest.LogGroup logGroup, CallBack callBack,
149-
int batchSize, BatchLog.BatchManager batchManager) {
146+
int batchSize, BatchLog.BatchManager batchManager) throws LogException {
150147
// add to exist batch
151148
BatchLog batchLog = batchManager.getBatchLog();
152149
if (batchLog != null) {
@@ -164,7 +161,12 @@ private void addToBatchManager(BatchLog.BatchKey batchKey, PutLogRequest.LogGrou
164161
// no batch create new and try send
165162
batchLog = new BatchLog(batchKey, producerConfig);
166163
batchManager.setBatchLog(batchLog);
167-
batchLog.tryAdd(logGroup, batchSize, callBack);
164+
boolean success = batchLog.tryAdd(logGroup, batchSize, callBack);
165+
if (!success) {
166+
LOG.error(String.format("tryAdd batchLog failed, batchKey = %s, batchSize = %d, batchCount = %d",
167+
batchKey.toString(), batchSize, logGroup.getLogsCount()));
168+
throw new LogException("Producer Error", "tryAdd batchLog failed", null);
169+
}
168170
if (batchManager.fullAndSendBatchRequest()) {
169171
batchManager.addNow(producerConfig, executorService, client, successQueue, failureQueue, batchCount,
170172
retryManager);

src/main/java/com/volcengine/service/tls/Mover.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ public Mover(String name, ProducerConfig producerConfig, LogDispatcher dispatche
4040
@Override
4141
public void run() {
4242
handlerTimeout();
43+
44+
handleRemainingBatch();
45+
List<BatchLog> remainingRetryBatches = retryManager.handleRemainingBatches();
46+
for (BatchLog log : remainingRetryBatches) {
47+
executorService.submit(new SendBatchTask(log, producerConfig, successQueue, failureQueue, client, retryManager));
48+
}
4349
}
4450

4551
private void handlerTimeout() {
@@ -84,6 +90,24 @@ private long handleTimeoutBatch() {
8490
return remains;
8591
}
8692

93+
private void handleRemainingBatch() {
94+
LOG.debug("mover" + name + "handler remaining batch");
95+
List<BatchLog> batchLogs = new ArrayList<>();
96+
for (Map.Entry<BatchLog.BatchKey, BatchLog.BatchManager> entry : batches.entrySet()) {
97+
BatchLog.BatchManager batchManager = entry.getValue();
98+
synchronized (batchManager) {
99+
BatchLog batchLog = batchManager.getBatchLog();
100+
if (batchLog == null) {
101+
continue;
102+
}
103+
batchManager.removeBatch(batchLogs);
104+
}
105+
}
106+
for (BatchLog log : batchLogs) {
107+
executorService.submit(new SendBatchTask(log, producerConfig, successQueue, failureQueue, client, retryManager));
108+
}
109+
}
110+
87111
public void close() {
88112
this.closed = true;
89113
super.interrupt();

src/main/java/com/volcengine/service/tls/Producer.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,15 @@ void sendLogsV2(String hashKey, String topicId, String source, String filename,
7373
*/
7474
void close() throws InterruptedException, LogException;
7575

76+
/**
77+
* 暂停Producer
78+
*
79+
* @param timeoutMs 超时等待时间
80+
* @throws InterruptedException
81+
* @throws LogException
82+
*/
83+
void close(long timeoutMs) throws InterruptedException, LogException;
84+
7685
/**
7786
* 立刻暂停producer
7887
*
@@ -88,4 +97,4 @@ void sendLogsV2(String hashKey, String topicId, String source, String filename,
8897
* @throws LogException
8998
*/
9099
void config(ProducerConfig producerConfig) throws LogException;
91-
}
100+
}

0 commit comments

Comments
 (0)