Skip to content

Commit e01c7b7

Browse files
committed
improve: remove asserts from code
Signed-off-by: ZhangJian He <[email protected]>
1 parent df823a2 commit e01c7b7

File tree

14 files changed

+128
-93
lines changed

14 files changed

+128
-93
lines changed

bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/EntryMemTable.java

+12-3
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ public EntryKeyValue put(EntryKey k, EntryKeyValue v) {
7575

7676
@Override
7777
public EntryKeyValue putIfAbsent(EntryKey k, EntryKeyValue v) {
78+
if (!k.equals(v)) {
79+
throw new IllegalArgumentException("Key and value should be same");
80+
}
7881
assert k.equals(v);
7982
return super.putIfAbsent(v, v);
8083
}
@@ -275,11 +278,15 @@ long flushSnapshot(final SkipListFlusher flusher, Checkpoint checkpoint) throws
275278
*/
276279
void clearSnapshot(final EntrySkipList keyValues) {
277280
// Caller makes sure that keyValues not empty
278-
assert !keyValues.isEmpty();
281+
if (keyValues.isEmpty()) {
282+
throw new IllegalStateException("Snapshot is empty");
283+
}
279284
this.lock.writeLock().lock();
280285
try {
286+
if (this.snapshot != keyValues) {
287+
throw new IllegalStateException("Snapshot mismatch");
288+
}
281289
// create a new snapshot and let the old one go.
282-
assert this.snapshot == keyValues;
283290
this.snapshot = EntrySkipList.EMPTY_VALUE;
284291
} finally {
285292
this.lock.writeLock().unlock();
@@ -371,7 +378,9 @@ private EntryKeyValue cloneWithAllocator(long ledgerId, long entryId, final Byte
371378
return newEntry(ledgerId, entryId, entry);
372379
}
373380

374-
assert alloc.getData() != null;
381+
if (alloc.getData() == null) {
382+
throw new IllegalStateException("MemorySlice.getData() should not be null");
383+
}
375384
entry.get(alloc.getData(), alloc.getOffset(), len);
376385
return new EntryKeyValue(ledgerId, entryId, alloc.getData(), alloc.getOffset(), len);
377386
}

bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/IndexInMemPageMgr.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -571,7 +571,9 @@ void putEntryOffset(long ledger, long entry, long offset) throws IOException {
571571
LedgerEntryPage lep = null;
572572
try {
573573
lep = getLedgerEntryPage(ledger, pageEntry);
574-
assert lep != null;
574+
if (lep == null) {
575+
throw new Bookie.NoLedgerException(ledger);
576+
}
575577
lep.setOffset(offset, offsetInPage * LedgerEntryPage.getIndexEntrySize());
576578
} catch (FileInfo.FileInfoDeletedException e) {
577579
throw new Bookie.NoLedgerException(ledger);

bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/SkipListArena.java

+16-9
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
* </p>
4646
*/
4747
public class SkipListArena {
48-
private AtomicReference<Chunk> curChunk = new AtomicReference<Chunk>();
48+
private final AtomicReference<Chunk> curChunk = new AtomicReference<Chunk>();
4949

5050
final int chunkSize;
5151

@@ -54,7 +54,9 @@ public class SkipListArena {
5454
public SkipListArena(ServerConfiguration cfg) {
5555
chunkSize = cfg.getSkipListArenaChunkSize();
5656
maxAlloc = cfg.getSkipListArenaMaxAllocSize();
57-
assert maxAlloc <= chunkSize;
57+
if (maxAlloc > chunkSize) {
58+
throw new IllegalArgumentException("maxAlloc should be less than or equal to chunkSize");
59+
}
5860
}
5961

6062
/**
@@ -64,7 +66,9 @@ public SkipListArena(ServerConfiguration cfg) {
6466
* </p>
6567
*/
6668
public MemorySlice allocateBytes(int size) {
67-
assert size >= 0;
69+
if (size < 0) {
70+
throw new IllegalArgumentException("Invalid size: " + size);
71+
}
6872

6973
// Callers should satisfy large allocations directly from JVM since they
7074
// don't cause fragmentation as badly.
@@ -135,10 +139,10 @@ private static class Chunk {
135139
* Offset for the next allocation, or the sentinel value -1
136140
* which implies that the chunk is still uninitialized.
137141
*/
138-
private AtomicInteger nextFreeOffset = new AtomicInteger(UNINITIALIZED);
142+
private final AtomicInteger nextFreeOffset = new AtomicInteger(UNINITIALIZED);
139143

140144
/** Total number of allocations satisfied from this buffer. */
141-
private AtomicInteger allocCount = new AtomicInteger();
145+
private final AtomicInteger allocCount = new AtomicInteger();
142146

143147
/** Size of chunk in bytes. */
144148
private final int size;
@@ -158,17 +162,20 @@ private Chunk(int size) {
158162
* threads calling alloc(), who will block until the allocation is complete.
159163
*/
160164
public void init() {
161-
assert nextFreeOffset.get() == UNINITIALIZED;
165+
if (nextFreeOffset.get() != UNINITIALIZED) {
166+
throw new IllegalStateException("Double-init");
167+
}
162168
try {
163169
data = new byte[size];
164170
} catch (OutOfMemoryError e) {
165-
boolean failInit = nextFreeOffset.compareAndSet(UNINITIALIZED, OOM);
166-
assert failInit; // should be true.
171+
nextFreeOffset.compareAndSet(UNINITIALIZED, OOM);
167172
throw e;
168173
}
169174
// Mark that it's ready for use
170175
boolean okInit = nextFreeOffset.compareAndSet(UNINITIALIZED, 0);
171-
assert okInit; // single-threaded call
176+
if (!okInit) {
177+
throw new IllegalStateException("Double-init");
178+
}
172179
}
173180

174181
/**

bookkeeper-server/src/main/java/org/apache/bookkeeper/client/BookieWatcherImpl.java

-2
Original file line numberDiff line numberDiff line change
@@ -226,8 +226,6 @@ public void initialBlockingBookieRead() throws BKException {
226226
CompletableFuture<?> readonly;
227227
synchronized (this) {
228228
if (initialReadonlyBookiesFuture == null) {
229-
assert initialWritableBookiesFuture == null;
230-
231229
writable = this.registrationClient.watchWritableBookies(
232230
bookies -> processWritableBookiesChanged(bookies.getValue()));
233231

bookkeeper-server/src/main/java/org/apache/bookkeeper/client/LedgerFragmentReplicator.java

+9-6
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,11 @@ private void replicateFragmentInternal(final LedgerHandle lh,
158158
* INVALID_ENTRY_ID and viceversa.
159159
*/
160160
if (startEntryId == INVALID_ENTRY_ID ^ endEntryId == INVALID_ENTRY_ID) {
161-
LOG.error("For LedgerFragment: {}, seeing inconsistent firstStoredEntryId: {} and lastStoredEntryId: {}",
161+
String msg = String.format("For LedgerFragment: %s, seeing inconsistent firstStoredEntryId: %s" +
162+
" and lastStoredEntryId: %s",
162163
lf, startEntryId, endEntryId);
163-
assert false;
164+
LOG.error(msg);
165+
throw new IllegalStateException(msg);
164166
}
165167

166168
if (startEntryId > endEntryId || endEntryId <= INVALID_ENTRY_ID) {
@@ -231,8 +233,7 @@ private void replicateFragmentInternal(final LedgerHandle lh,
231233
void replicate(final LedgerHandle lh, final LedgerFragment lf,
232234
final AsyncCallback.VoidCallback ledgerFragmentMcb,
233235
final Set<BookieId> targetBookieAddresses,
234-
final BiConsumer<Long, Long> onReadEntryFailureCallback)
235-
throws InterruptedException {
236+
final BiConsumer<Long, Long> onReadEntryFailureCallback) {
236237
Set<LedgerFragment> partitionedFragments = splitIntoSubFragments(lh, lf,
237238
bkc.getConf().getRereplicationEntryBatchSize());
238239
LOG.info("Replicating fragment {} in {} sub fragments.",
@@ -300,9 +301,11 @@ static Set<LedgerFragment> splitIntoSubFragments(LedgerHandle lh,
300301
* INVALID_ENTRY_ID and viceversa.
301302
*/
302303
if (firstEntryId == INVALID_ENTRY_ID ^ lastEntryId == INVALID_ENTRY_ID) {
303-
LOG.error("For LedgerFragment: {}, seeing inconsistent firstStoredEntryId: {} and lastStoredEntryId: {}",
304+
String msg = String.format("For LedgerFragment: %s, seeing inconsistent firstStoredEntryId: %s" +
305+
" and lastStoredEntryId: %s",
304306
ledgerFragment, firstEntryId, lastEntryId);
305-
assert false;
307+
LOG.error(msg);
308+
throw new IllegalStateException(msg);
306309
}
307310

308311
long numberOfEntriesToReplicate = firstEntryId == INVALID_ENTRY_ID ? 0 : (lastEntryId - firstEntryId) + 1;

bookkeeper-server/src/main/java/org/apache/bookkeeper/meta/ZkLedgerUnderreplicationManager.java

+6-4
Original file line numberDiff line numberDiff line change
@@ -470,11 +470,11 @@ public void remove() {
470470

471471
@Override
472472
public boolean hasNext() {
473-
if (curBatch.size() > 0) {
473+
if (!curBatch.isEmpty()) {
474474
return true;
475475
}
476476

477-
while (queue.size() > 0 && curBatch.size() == 0) {
477+
while (!queue.isEmpty() && curBatch.isEmpty()) {
478478
String parent = queue.remove();
479479
try {
480480
for (String c : zkc.getChildren(parent, false)) {
@@ -501,12 +501,14 @@ public boolean hasNext() {
501501
throw new RuntimeException("Error reading list", e);
502502
}
503503
}
504-
return curBatch.size() > 0;
504+
return !curBatch.isEmpty();
505505
}
506506

507507
@Override
508508
public UnderreplicatedLedger next() {
509-
assert curBatch.size() > 0;
509+
if (curBatch.isEmpty()) {
510+
throw new IllegalStateException("No more elements");
511+
}
510512
return curBatch.remove();
511513
}
512514
};

bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/AuthHandler.java

+33-32
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
8989
super.channelRead(ctx, msg);
9090
} else if (msg instanceof BookieProtocol.AuthRequest) { // pre-PB-client
9191
BookieProtocol.AuthRequest req = (BookieProtocol.AuthRequest) msg;
92-
assert (req.getOpCode() == BookieProtocol.AUTH);
92+
if (BookieProtocol.AUTH != req.getOpCode()) {
93+
throw new IllegalStateException("Received message other than auth message");
94+
}
9395
if (checkAuthPlugin(req.getAuthMessage(), ctx.channel())) {
9496
byte[] payload = req
9597
.getAuthMessage()
@@ -270,45 +272,44 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
270272

271273
@Override
272274
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
273-
assert (authProvider != null);
275+
if (authProvider == null) {
276+
throw new IllegalStateException("Auth provider is not initialized");
277+
}
274278

275279
if (authenticated) {
276280
super.channelRead(ctx, msg);
277281
} else if (msg instanceof BookkeeperProtocol.Response) {
278282
BookkeeperProtocol.Response resp = (BookkeeperProtocol.Response) msg;
279-
if (null == resp.getHeader().getOperation()) {
280-
LOG.info("dropping received malformed message {} from bookie {}", msg, ctx.channel());
281-
// drop the message without header
282-
} else {
283-
switch (resp.getHeader().getOperation()) {
284-
case START_TLS:
285-
super.channelRead(ctx, msg);
286-
break;
287-
case AUTH:
288-
if (resp.getStatus() != BookkeeperProtocol.StatusCode.EOK) {
289-
authenticationError(ctx, resp.getStatus().getNumber());
290-
} else {
291-
assert (resp.hasAuthResponse());
292-
BookkeeperProtocol.AuthMessage am = resp.getAuthResponse();
293-
if (AUTHENTICATION_DISABLED_PLUGIN_NAME.equals(am.getAuthPluginName())){
294-
SocketAddress remote = ctx.channel().remoteAddress();
295-
LOG.info("Authentication is not enabled."
283+
switch (resp.getHeader().getOperation()) {
284+
case START_TLS:
285+
super.channelRead(ctx, msg);
286+
break;
287+
case AUTH:
288+
if (resp.getStatus() != BookkeeperProtocol.StatusCode.EOK) {
289+
authenticationError(ctx, resp.getStatus().getNumber());
290+
} else {
291+
if (!resp.hasAuthResponse()) {
292+
throw new IllegalStateException("Auth response is missing in the message");
293+
}
294+
AuthMessage am = resp.getAuthResponse();
295+
if (AUTHENTICATION_DISABLED_PLUGIN_NAME.equals(am.getAuthPluginName())) {
296+
SocketAddress remote = ctx.channel().remoteAddress();
297+
LOG.info("Authentication is not enabled."
296298
+ "Considering this client {} authenticated", remote);
297-
AuthHandshakeCompleteCallback cb = new AuthHandshakeCompleteCallback(ctx);
298-
cb.operationComplete(BKException.Code.OK, null);
299-
return;
300-
}
301-
byte[] payload = am.getPayload().toByteArray();
302-
authProvider.process(AuthToken.wrap(payload), new AuthRequestCallback(ctx,
303-
authProviderFactory.getPluginName()));
299+
AuthHandshakeCompleteCallback cb = new AuthHandshakeCompleteCallback(ctx);
300+
cb.operationComplete(BKException.Code.OK, null);
301+
return;
304302
}
305-
break;
306-
default:
307-
LOG.warn("dropping received message {} from bookie {}", msg, ctx.channel());
308-
// else just drop the message,
309-
// we're not authenticated so nothing should be coming through
310-
break;
303+
byte[] payload = am.getPayload().toByteArray();
304+
authProvider.process(AuthToken.wrap(payload), new AuthRequestCallback(ctx,
305+
authProviderFactory.getPluginName()));
311306
}
307+
break;
308+
default:
309+
LOG.warn("dropping received message {} from bookie {}", msg, ctx.channel());
310+
// else just drop the message,
311+
// we're not authenticated so nothing should be coming through
312+
break;
312313
}
313314
} else if (msg instanceof BookieProtocol.Response) {
314315
BookieProtocol.Response resp = (BookieProtocol.Response) msg;

bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieProtocol.java

-1
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,6 @@ boolean hasMasterKey() {
237237
}
238238

239239
byte[] getMasterKey() {
240-
assert hasMasterKey();
241240
return masterKey;
242241
}
243242

bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PerChannelBookieClient.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -2425,9 +2425,7 @@ abstract class CompletionKey {
24252425
public void release() {}
24262426
}
24272427

2428-
/**
2429-
* Note : Helper functions follow
2430-
*/
2428+
// Note : Helper functions follow
24312429

24322430
/**
24332431
* @param status
@@ -2701,7 +2699,9 @@ private void logBookieUnavailable(Runnable logger) {
27012699

27022700
private void initiateTLS() {
27032701
LOG.info("Initializing TLS to {}", channel);
2704-
assert state == ConnectionState.CONNECTING;
2702+
if (ConnectionState.CONNECTING != state) {
2703+
throw new IllegalStateException("Invalid state to initiate TLS: " + state);
2704+
}
27052705
final long txnId = getTxnId();
27062706
final CompletionKey completionKey = new TxnCompletionKey(txnId, OperationType.START_TLS);
27072707
completionObjects.put(completionKey,

bookkeeper-server/src/main/java/org/apache/bookkeeper/util/PageCacheUtil.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,17 @@ public final class PageCacheUtil {
5151
}
5252

5353
private static Field getFieldByReflection(Class cls, String fieldName) {
54-
Field field = null;
54+
Field field;
5555

5656
try {
5757
field = cls.getDeclaredField(fieldName);
5858
field.setAccessible(true);
5959
} catch (Exception e) {
6060
// We don't really expect this so throw an assertion to
6161
// catch this during development
62-
log.warn("Unable to read {} field from {}", fieldName, cls.getName());
63-
assert false;
62+
String msg = "Unable to read " + fieldName + " field from " + cls.getName();
63+
log.warn(msg);
64+
throw new IllegalStateException(msg, e);
6465
}
6566

6667
return field;

bookkeeper-server/src/main/java/org/apache/bookkeeper/verifier/BookkeeperVerifier.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,9 @@ void onLastOpComplete(
345345
void onLastWriteComplete(
346346
Consumer<Integer> cb,
347347
Consumer<Consumer<Integer>> newOnLastWrite) {
348-
assert (onLastWrite == null);
348+
if (onLastWrite != null) {
349+
throw new IllegalStateException("onLastWrite already set");
350+
}
349351
onLastWrite = newOnLastWrite;
350352
checkWriteComplete(cb);
351353
}

stream/distributedlog/core/src/main/java/org/apache/distributedlog/LocalDLMEmulator.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -162,15 +162,16 @@ public void run() {
162162

163163
public void start() throws Exception {
164164
bkStartupThread.start();
165-
if (!LocalBookKeeper.waitForServerUp(zkEnsemble, zkTimeoutSec * 1000)) {
165+
if (!LocalBookKeeper.waitForServerUp(zkEnsemble, zkTimeoutSec * 1000L)) {
166166
throw new Exception("Error starting zookeeper/bookkeeper");
167167
}
168168
int bookiesUp = checkBookiesUp(numBookies, zkTimeoutSec);
169169
if (numBookies != bookiesUp) {
170-
LOG.info("Only {} bookies are up, expected {} bookies to be there.",
170+
String msg = String.format("Only %d bookies are up, expected %d bookies to be there.",
171171
bookiesUp, numBookies);
172+
LOG.info(msg);
173+
throw new IllegalStateException(msg);
172174
}
173-
assert (numBookies == bookiesUp);
174175
// Provision "/messaging/distributedlog" namespace
175176
DLMetadata.create(new BKDLConfig(zkEnsemble, "/ledgers")).create(uri);
176177
}

0 commit comments

Comments
 (0)