Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF 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.apache.doris.nereids;

import com.google.common.base.FinalizablePhantomReference;
import com.google.common.base.FinalizableReferenceQueue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/** Reports abandoned planner locks without retaining the statement's plan graph. */
final class PlannerLockLeakTracker extends FinalizablePhantomReference<StatementContext> {
private static final Logger LOG = LogManager.getLogger(PlannerLockLeakTracker.class);
private static final Set<PlannerLockLeakTracker> PENDING = ConcurrentHashMap.newKeySet();
private static final FinalizableReferenceQueue QUEUE = new FinalizableReferenceQueue();

private final String table;
private final String ownerThread;
private final String queryId;

private PlannerLockLeakTracker(StatementContext owner, String table, String queryId) {
super(owner, QUEUE);
this.table = table;
this.ownerThread = Thread.currentThread().getName();
this.queryId = queryId;
}

static PlannerLockLeakTracker register(StatementContext owner, String table, String queryId) {
PlannerLockLeakTracker reference = new PlannerLockLeakTracker(owner, table, queryId);
// Keep the phantom reference itself alive until the lock scope is released or reported.
PENDING.add(reference);
return reference;
}

void unregister() {
PENDING.remove(this);
clear();
}

@Override
public void finalizeReferent() {
if (PENDING.remove(this)) {
// Table read locks must be released on the owning thread.
LOG.error("Resources leak: planner lock scope abandoned for table {}, thread {}, query {}",
table, ownerThread, queryId);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.apache.doris.common.Id;
import org.apache.doris.common.IdGenerator;
import org.apache.doris.common.Pair;
import org.apache.doris.common.util.DebugUtil;
import org.apache.doris.connector.ConnectorStatementScopeImpl;
import org.apache.doris.connector.spi.ConnectorStatementScope;
import org.apache.doris.connector.spi.handle.ConnectorTransaction;
Expand Down Expand Up @@ -279,6 +280,8 @@ public enum TableFrom {

// table locks
private final Stack<CloseableResource> plannerResources = new Stack<>();
@GuardedBy("this")
private PlannerLockLeakTracker plannerLockLeakTracker;

// Scan nodes that hold something on this frontend for the backend (a remote Doris scan's Flight
// SQL session on the other frontend) and release it in ScanNode.stop(), which the coordinator
Expand Down Expand Up @@ -1610,16 +1613,21 @@ public synchronized void lock() {
close();
throw new RuntimeException("Failed to get read lock on table:" + tableIf.getName());
}
String fullTableName = tableIf.getNameWithFullQualifiers();
String resourceName = "tableReadLock(" + fullTableName + ")";
plannerResources.push(new CloseableResource(
resourceName, Thread.currentThread().getName(),
originStatement == null ? null : originStatement.originStmt, tableIf::readUnlock));
plannerResources.push(new CloseableResource(tableIf::readUnlock));
if (plannerLockLeakTracker == null) {
String queryId = connectContext == null ? "" : DebugUtil.printId(connectContext.queryId());
plannerLockLeakTracker = PlannerLockLeakTracker.register(
this, tableIf.getNameWithFullQualifiers(), queryId);
}
}
}

/** releasePlannerResources */
public synchronized void releasePlannerResources() {
if (plannerLockLeakTracker != null) {
plannerLockLeakTracker.unregister();
plannerLockLeakTracker = null;
}
Throwable throwable = null;
while (!plannerResources.isEmpty()) {
try {
Expand Down Expand Up @@ -1682,17 +1690,6 @@ private void stopScanNodesLeftBehind() {
}
}

// CHECKSTYLE OFF
@Override
protected void finalize() throws Throwable {
if (!plannerResources.isEmpty()) {
String msg = "Resources leak: " + plannerResources;
LOG.error(msg);
throw new IllegalStateException(msg);
}
}
// CHECKSTYLE ON

@Override
public void close() {
releasePlannerResources();
Expand Down Expand Up @@ -2232,18 +2229,11 @@ private boolean containsPlanReadLockTable(Collection<TableIf> tableIfs) {
}

private static class CloseableResource implements Closeable {
public final String resourceName;
public final String threadName;
public final String sql;

private final Closeable resource;

private boolean closed;

public CloseableResource(String resourceName, String threadName, String sql, Closeable resource) {
this.resourceName = resourceName;
this.threadName = threadName;
this.sql = sql;
public CloseableResource(Closeable resource) {
this.resource = resource;
}

Expand All @@ -2259,12 +2249,6 @@ public void close() {
closed = true;
}
}

@Override
public String toString() {
return "\nResource {\n name: " + resourceName + ",\n thread: " + threadName
+ ",\n sql:\n" + sql + "\n}";
}
}

public void addKeySlot(SlotReference slot) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF 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.apache.doris.nereids;

import org.apache.doris.catalog.TableIf;
import org.apache.doris.mysql.authenticate.TestLogAppender;

import org.apache.logging.log4j.Level;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

class StatementContextPlannerLockTest {
@Test
void statementContextDoesNotParticipateInFinalization() {
// Finalization holds the full graph alive even after all table locks have been released.
Assertions.assertThrows(NoSuchMethodException.class,
() -> StatementContext.class.getDeclaredMethod("finalize"));
}

@Test
void releasesLocksInReverseOrderAndCanAcquireThemAgain() {
StatementContext context = new StatementContext(0);
TableIf first = addTable(context, 1, "t1", true);
TableIf second = addTable(context, 2, "t2", true);

for (int cycle = 0; cycle < 2; cycle++) {
context.lock();
context.close();
context.close();
}

InOrder order = Mockito.inOrder(first, second);
for (int cycle = 0; cycle < 2; cycle++) {
order.verify(first).tryReadLock(1, TimeUnit.MINUTES);
order.verify(second).tryReadLock(1, TimeUnit.MINUTES);
order.verify(second).readUnlock();
order.verify(first).readUnlock();
}
Mockito.verify(first, Mockito.times(2)).readUnlock();
Mockito.verify(second, Mockito.times(2)).readUnlock();
}

@Test
void releasesPreviouslyAcquiredLockWhenNextAcquireFails() {
StatementContext context = new StatementContext(0);
TableIf first = addTable(context, 1, "t1", true);
TableIf second = addTable(context, 2, "t2", false);

try {
RuntimeException failure = Assertions.assertThrows(RuntimeException.class, context::lock);
Assertions.assertTrue(failure.getMessage().contains("t2"));
Mockito.verify(first).readUnlock();
Mockito.verify(second, Mockito.never()).readUnlock();
} finally {
context.close();
}
}

@Test
void reportsAbandonedScopeOnlyOnce() throws ReflectiveOperationException {
StatementContext context = new StatementContext(0);
TableIf table = addTable(context, 1, "abandoned", true);
context.lock();
try {
PlannerLockLeakTracker tracker = getTracker(context);
String message = "planner lock scope abandoned for table internal.db.abandoned";
try (TestLogAppender log = TestLogAppender.attach(PlannerLockLeakTracker.class)) {
Assertions.assertTrue(tracker.enqueue());
Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> log.contains(Level.ERROR, message));
}
try (TestLogAppender log = TestLogAppender.attach(PlannerLockLeakTracker.class)) {
tracker.finalizeReferent();
Assertions.assertFalse(log.contains(Level.ERROR, message));
}
Mockito.verify(table, Mockito.never()).readUnlock();
} finally {
context.close();
}
}

@Test
void releasedScopeCannotReportALeak() throws ReflectiveOperationException {
StatementContext context = new StatementContext(0);
addTable(context, 1, "released", true);
context.lock();
PlannerLockLeakTracker tracker = getTracker(context);
context.close();

try (TestLogAppender log = TestLogAppender.attach(PlannerLockLeakTracker.class)) {
tracker.finalizeReferent();
Assertions.assertFalse(log.contains(Level.ERROR,
"planner lock scope abandoned for table internal.db.released"));
}
}

private PlannerLockLeakTracker getTracker(StatementContext context) throws ReflectiveOperationException {
// Control reference-queue delivery without relying on when GC runs.
Field field = StatementContext.class.getDeclaredField("plannerLockLeakTracker");
field.setAccessible(true);
return (PlannerLockLeakTracker) field.get(context);
}

private TableIf addTable(StatementContext context, long tableId, String name, boolean acquired) {
TableIf table = Mockito.mock(TableIf.class);
Mockito.when(table.getId()).thenReturn(tableId);
Mockito.when(table.getName()).thenReturn(name);
Mockito.when(table.getNameWithFullQualifiers()).thenReturn("internal.db." + name);
Mockito.when(table.needReadLockWhenPlan()).thenReturn(true);
Mockito.when(table.tryReadLock(1, TimeUnit.MINUTES)).thenReturn(acquired);
context.getTables().put(Arrays.asList("internal", "db", name), table);
return table;
}
}