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
2 changes: 2 additions & 0 deletions api/src/org/labkey/api/ApiModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@
import org.labkey.api.util.ContextListener;
import org.labkey.api.util.CspCommentScanner;
import org.labkey.api.util.DateUtil;
import org.labkey.api.util.DebugInfoDumper;
import org.labkey.api.util.DomTestCase;
import org.labkey.api.util.ExceptionUtil;
import org.labkey.api.util.ExtUtil;
Expand Down Expand Up @@ -588,6 +589,7 @@ public void registerServlets(ServletContext servletCtx)
DbScope.PoolStatisticsTestCase.class,
DbScope.TransactionTestCase.class,
DbSequenceManager.TestCase.class,
DebugInfoDumper.TestCase.class,
DisplayColumn.TestCase.class,
DomTestCase.class,
DomainTemplateGroup.TestCase.class,
Expand Down
2 changes: 1 addition & 1 deletion api/src/org/labkey/api/data/ExceptionFramework.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public RuntimeException translate(DbScope scope, String task, SQLException e)
SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(scope.getDataSource());
if (SqlDialect.isTransactionException(e))
{
DebugInfoDumper.dumpThreads(1);
DebugInfoDumper.dumpThreadsIfIdle();
}
RuntimeException result = translator.translate(task, null, e);
if (result == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ public abstract class BasePostgreSqlDialect extends SqlDialect
public static final String POSTGRES_LOCKS_TABLE_NAME = "pg_locks";
public static final String POSTGRES_TABLE_SIZES_TABLE_NAME = "pg_tablesizes";

public static final String POSTGRES_STAT_ACTIVITY_SQL = """
SELECT
*,
CAST(pg_blocking_pids(pid) AS VARCHAR) AS blocked_by,
CASE WHEN (state = 'idle' OR state IS NULL) THEN NULL ELSE GREATEST(EXTRACT(EPOCH FROM (NOW() - query_start)) * 1000, 0) END AS running_time_ms
FROM pg_stat_activity""";

private HtmlString _adminWarning = null;

// Default to 9 and let newer versions be refreshed later
Expand Down
2 changes: 1 addition & 1 deletion api/src/org/labkey/api/data/dialect/StatementWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -2905,7 +2905,7 @@ else if (o instanceof String)
// check for deadlock or transaction related error
if (SqlDialect.isTransactionException(x))
{
DebugInfoDumper.dumpThreads(_log);
DebugInfoDumper.dumpThreadsIfIdle(_log);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,6 @@ public DeadlockPreventingException(String message, Throwable cause)

private void dumpThreads()
{
DebugInfoDumper.dumpThreads(1);
DebugInfoDumper.dumpThreadsIfIdle();
}
}
225 changes: 160 additions & 65 deletions api/src/org/labkey/api/util/DebugInfoDumper.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,19 @@
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import org.labkey.api.action.NullSafeBindException;
import org.junit.Assert;
import org.junit.Test;
import org.labkey.api.data.ConnectionWrapper;
import org.labkey.api.data.ContainerManager;
import org.labkey.api.data.DbScope;
import org.labkey.api.data.TSVWriter;
import org.labkey.api.data.RuntimeSQLException;
import org.labkey.api.data.TransactionFilter;
import org.labkey.api.data.dialect.BasePostgreSqlDialect;
import org.labkey.api.files.FileSystemDirectoryListener;
import org.labkey.api.files.FileSystemWatchers;
import org.labkey.api.mbean.LabKeyManagement;
import org.labkey.api.miniprofiler.MiniProfiler;
import org.labkey.api.module.ModuleLoader;
import org.labkey.api.query.QueryForm;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.QueryView;
import org.labkey.api.query.UserSchema;
import org.labkey.api.security.User;
import org.labkey.api.util.logging.LogHelper;
import org.labkey.api.view.ActionURL;
import org.labkey.api.view.HttpView;
import org.labkey.api.view.ViewContext;
import org.labkey.api.websocket.WebSocketTracker;
import org.labkey.api.writer.PrintWriters;
import org.labkey.vfs.FileLike;
Expand All @@ -50,13 +42,16 @@
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
Expand All @@ -66,8 +61,10 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
* Monitors the timestamp of the heapDumpRequest and threadDumpRequest files to see if an admin has requested
Expand Down Expand Up @@ -325,10 +322,54 @@ static boolean justWaiting(StackTraceElement[] stack)
/** Prevent reentrancy when we get SQLException trying to grab locks from Postgres */
private static final ThreadLocal<Boolean> DUMPING_THREADS = ThreadLocal.withInitial(() -> false);

private static final ReentrantLock DUMP_LOCK = new ReentrantLock();
static final String SKIPPED_DUMP_MESSAGE = "Skipping thread dump; another thread is already writing one";

/**
* Writes the thread dump into threads.txt
* Writes the thread dump into threads.txt, waiting for any dump already in progress on another thread
* */
public static synchronized void dumpThreads(LoggerWriter logWriter)
public static void dumpThreads(LoggerWriter logWriter)
{
DUMP_LOCK.lock();
try
{
writeThreadDump(logWriter);
}
finally
{
DUMP_LOCK.unlock();
}
}

/** For automatic dumps on lock timeouts and transaction errors: skips, rather than queues, when another thread is already dumping */
public static void dumpThreadsIfIdle(LoggerWriter logWriter)
{
if (!DUMP_LOCK.tryLock())
{
logWriter.debug(SKIPPED_DUMP_MESSAGE);
return;
}
try
{
writeThreadDump(logWriter);
}
finally
{
DUMP_LOCK.unlock();
}
}

public static void dumpThreadsIfIdle(Logger log)
{
dumpThreadsIfIdle(new SimpleLoggerWriter(log));
}

public static void dumpThreadsIfIdle()
{
dumpThreadsIfIdle(LOG);
}

private static void writeThreadDump(LoggerWriter logWriter)
{
if (DUMPING_THREADS.get() == true)
{
Expand Down Expand Up @@ -428,34 +469,62 @@ public static synchronized void dumpThreads(LoggerWriter logWriter)
}

// GitHub Issue 713: Automatically include PG locks and active queries in thread dumps
UserSchema schema = QueryService.get().getUserSchema(User.getAdminServiceUser(), ContainerManager.getRoot(), BasePostgreSqlDialect.POSTGRES_SCHEMA_NAME);
// Schema won't exist on SQLServer
if (schema != null)
{
try
{
writeTable(logWriter, schema, BasePostgreSqlDialect.POSTGRES_LOCKS_TABLE_NAME, "Postgres locks");
}
catch (RuntimeException e)
{
logWriter.debug("Failed to write Postgres locks table:" + e);
}
try
{
writeTable(logWriter, schema, BasePostgreSqlDialect.POSTGRES_STAT_ACTIVITY_TABLE_NAME, "Postgres activity");
}
catch (RuntimeException e)
{
logWriter.debug("Failed to write Postgres activity table:" + e);
}
}
dumpPostgresState(logWriter);
}
finally
{
DUMPING_THREADS.set(false);
}
}

/**
* GH Issue 1875: the server may be deadlocked, so use plain JDBC on a dedicated unpooled connection with short
* timeouts; borrowing from the pool or going through query/schema caches can wait on the deadlocked threads.
*/
private static void dumpPostgresState(LoggerWriter logWriter)
{
DbScope scope = DbScope.getLabKeyScope();

// pgjdbc waits forever to log in by default
Properties props = new Properties();
props.setProperty("loginTimeout", "5");
props.setProperty("socketTimeout", "10");
try (Connection conn = scope.getUnpooledConnection(props))
{
writeQuery(logWriter, conn, "SELECT * FROM pg_locks", "Postgres locks");
writeQuery(logWriter, conn, BasePostgreSqlDialect.POSTGRES_STAT_ACTIVITY_SQL, "Postgres activity");
}
catch (SQLException | RuntimeException e)
{
logWriter.debug("Failed to write Postgres locks and activity: " + e);
}
}

private static void writeQuery(LoggerWriter logWriter, Connection conn, String sql, String header)
{
StringBuilder tsv;
try (Statement stmt = conn.createStatement())
{
stmt.setQueryTimeout(5);
try (ResultSet rs = stmt.executeQuery(sql))
{
tsv = ResultSetUtil.getData(rs);
}
}
catch (SQLException | RuntimeSQLException e)
{
logWriter.debug("Failed to write " + header + ": " + e);
return;
}

logWriter.debug("Starting dump of " + header);
logWriter.debug("*********************************************");
logWriter.debug(tsv.toString());
logWriter.debug("*********************************************");
logWriter.debug("Completed dump of " + header);
logWriter.debug("*********************************************");
}

/**
* Connection counts per connector, plus the long-lived populations that fill them. A connector that reaches
* maxConnections stops accepting while its threads sit idle, so the stacks below show an untroubled server.
Expand Down Expand Up @@ -532,35 +601,6 @@ private static String getMBeanLimit(MBeanServer mbs, ObjectName name, String att
return value instanceof Number number && number.longValue() < 0 ? "unlimited" : String.valueOf(value);
}

private static void writeTable(LoggerWriter logWriter, UserSchema schema, String tableName, String header)
{
QueryForm form = new QueryForm();
try (var _ = ViewContext.pushMockViewContext(schema.getUser(), schema.getContainer(), new ActionURL()))
{
form.setViewContext(HttpView.currentContext());
form.setSchemaName(schema.getName());
form.setQueryName(tableName);
QueryView view = QueryView.create(form, new NullSafeBindException(new Object(), "form"));
logWriter.debug("Starting dump of " + header);
logWriter.debug("*********************************************");
try (TSVWriter writer = view.getTsvWriter())
{
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
writer.write(printWriter);
printWriter.flush();
logWriter.debug("\n" + stringWriter);
}
catch (IOException e)
{
logWriter.error("Failed to write " + header, e);
}
logWriter.debug("*********************************************");
logWriter.debug("Completed dump of " + header);
logWriter.debug("*********************************************");
}
}

static private final Set<String> skipMethods = Set.of("pushThreadDumpContext", "beginTransaction", "ensureTransaction", "execute", "getTroubleshootingStackTrace");

private static void dumpOneThread(Thread thread, LoggerWriter logWriter, Map<Thread, StackTraceElement[]> stackTraces, HashSetValuedHashMap<Thread, Integer> spidsByThread)
Expand Down Expand Up @@ -635,8 +675,63 @@ public static List<String> getFormattedExtraContext(Thread thread)
/**
* Writes the current set of thread stacks once to the supplied logger.
*/
public static synchronized void dumpThreads(Logger log)
public static void dumpThreads(Logger log)
{
dumpThreads(new SimpleLoggerWriter(log));
}

public static class TestCase extends Assert
{
@Test
public void testLockTimeoutDoesNotQueueBehindDump() throws Exception
{
List<String> lines = Collections.synchronizedList(new ArrayList<>());
LoggerWriter capturing = new SimpleLoggerWriter(LOG)
{
@Override
public void debug(String message)
{
lines.add(message);
}
};

// Holding the lock stands in for a dump in progress; a queued dump would run out runOnNewThread's join timeout
DUMP_LOCK.lock();
try
{
JunitUtil.runOnNewThread("DumpWhileDumping", () -> {
dumpThreadsIfIdle(capturing);
// The constructor is what dumps
//noinspection ThrowableNotThrown
new DeadlockPreventingException("Test lock timeout");
});
}
finally
{
DUMP_LOCK.unlock();
}
assertEquals(List.of(SKIPPED_DUMP_MESSAGE), lines);
}

@Test
public void testPostgresStateDump()
{
List<String> lines = new ArrayList<>();
LoggerWriter capturing = new SimpleLoggerWriter(LOG)
{
@Override
public void debug(String message)
{
lines.add(message);
}
};

dumpPostgresState(capturing);

// dumpPostgresState swallows every failure, so a broken connection or query only shows up as a missing section
assertTrue(lines.toString(), lines.contains("Starting dump of Postgres locks"));
assertTrue(lines.toString(), lines.contains("Starting dump of Postgres activity"));
assertTrue(lines.toString(), lines.stream().noneMatch(line -> line.startsWith("Failed to write")));
}
}
}
3 changes: 2 additions & 1 deletion api/src/org/labkey/api/util/ResultSetUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,8 @@ public static StringBuilder getData(ResultSet rs)
for (int i = 1; i <= columnCount; i++)
{
Object value = rs.getObject(i);
sb.append(null == value ? "-" : value.toString().trim()).append(SEPARATOR);
// Collapse whitespace so multi-line values (e.g. SQL text) keep one line per row
sb.append(null == value ? "-" : value.toString().replaceAll("\\s+", " ").trim()).append(SEPARATOR);
}

sb.append('\n');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,7 @@ public PostgresStatActivityTable(@NotNull PostgresUserSchema userSchema)
public @NotNull SQLFragment getFromSQL()
{
SQLFragment result = new SQLFragment();
result.unsafeAppend("""
SELECT
*,
CAST(pg_blocking_pids(pid) AS VARCHAR) AS blocked_by,
CASE WHEN (state = 'idle' OR state IS NULL) THEN NULL ELSE GREATEST(EXTRACT(MILLISECONDS FROM AGE(NOW(), query_start)), 0) END AS running_time_ms
FROM pg_stat_activity""");
result.unsafeAppend(BasePostgreSqlDialect.POSTGRES_STAT_ACTIVITY_SQL);
return result;
}

Expand Down