|
| 1 | +package com.coder.toolbox.diagnostics |
| 2 | + |
| 3 | +import com.coder.toolbox.session.SessionId |
| 4 | +import kotlinx.coroutines.CancellationException |
| 5 | +import kotlinx.coroutines.CoroutineScope |
| 6 | +import kotlinx.coroutines.Dispatchers |
| 7 | +import kotlinx.coroutines.ensureActive |
| 8 | +import kotlinx.coroutines.withContext |
| 9 | +import java.nio.channels.FileChannel |
| 10 | +import java.nio.file.Files |
| 11 | +import java.nio.file.LinkOption.NOFOLLOW_LINKS |
| 12 | +import java.nio.file.Path |
| 13 | +import java.nio.file.StandardOpenOption.CREATE |
| 14 | +import java.nio.file.StandardOpenOption.READ |
| 15 | +import java.nio.file.StandardOpenOption.TRUNCATE_EXISTING |
| 16 | +import java.nio.file.StandardOpenOption.WRITE |
| 17 | +import java.nio.file.attribute.BasicFileAttributes |
| 18 | +import java.time.Instant |
| 19 | + |
| 20 | +// Include current CLI session filenames and older PID-based logs. |
| 21 | +private val SSH_LOG_FILE = Regex("coder-ssh.*\\.log(?:\\.\\d+)?|\\d+\\.log") |
| 22 | +private const val SSH_LOG_MAX_AGE_SECONDS = 3L * 24 * 60 * 60 |
| 23 | +private const val SSH_LOG_MAX_BYTES = 50L * 1024 * 1024 |
| 24 | + |
| 25 | +internal class CoderSshLogCollector( |
| 26 | + private val logger: CoderLogger, |
| 27 | + private val logDirectory: Path, |
| 28 | +) { |
| 29 | + suspend fun collect( |
| 30 | + logsRootFolder: Path, |
| 31 | + sessionId: SessionId? = null, |
| 32 | + activeSshPid: Long? = null, |
| 33 | + ) = withContext(Dispatchers.IO) { |
| 34 | + // Older CLIs may not have created any session logs. |
| 35 | + if (Files.notExists(logDirectory)) return@withContext |
| 36 | + |
| 37 | + val cutoff = Instant.now().minusSeconds(SSH_LOG_MAX_AGE_SECONDS) |
| 38 | + val entries = Files.newDirectoryStream(logDirectory).use { it.toList() } |
| 39 | + // CLI proxy log names end in the parent SSH PID; timestamps distinguish reused PIDs. |
| 40 | + val activeLog = activeSshPid?.let { pid -> |
| 41 | + entries.filter { entry -> |
| 42 | + val name = entry.fileName.toString() |
| 43 | + (name == "$pid.log" || (name.startsWith("coder-ssh") && name.endsWith("-$pid.log"))) && |
| 44 | + Files.isRegularFile(entry, NOFOLLOW_LINKS) |
| 45 | + }.maxByOrNull { it.fileName.toString() } |
| 46 | + } |
| 47 | + for (entry in entries) { |
| 48 | + ensureActive() |
| 49 | + // An active session can remain quiet longer than the collection window. |
| 50 | + collectFile(entry, logsRootFolder.resolve("coder-ssh"), cutoff.takeUnless { entry == activeLog }, sessionId) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + @Suppress("TooGenericExceptionCaught") |
| 55 | + private fun CoroutineScope.collectFile(source: Path, destination: Path, cutoff: Instant?, sessionId: SessionId?) { |
| 56 | + if (!SSH_LOG_FILE.matches(source.fileName.toString())) return |
| 57 | + var output: Path? = null |
| 58 | + try { |
| 59 | + val attributes = Files.readAttributes(source, BasicFileAttributes::class.java, NOFOLLOW_LINKS) |
| 60 | + val expired = cutoff != null && attributes.lastModifiedTime().toInstant().isBefore(cutoff) |
| 61 | + if (!attributes.isRegularFile || expired) return |
| 62 | + |
| 63 | + FileChannel.open(source, READ, NOFOLLOW_LINKS).use { input -> |
| 64 | + val size = input.size() |
| 65 | + if (size > SSH_LOG_MAX_BYTES) { |
| 66 | + logger.warn( |
| 67 | + sessionId, |
| 68 | + "Truncating SSH log $source ($size bytes) to its last $SSH_LOG_MAX_BYTES bytes", |
| 69 | + ) |
| 70 | + } |
| 71 | + Files.createDirectories(destination) |
| 72 | + val targetPath = destination.resolve(source.fileName) |
| 73 | + output = targetPath |
| 74 | + FileChannel.open(targetPath, CREATE, WRITE, TRUNCATE_EXISTING).use { target -> |
| 75 | + copyTail(input, target, size) |
| 76 | + } |
| 77 | + } |
| 78 | + } catch (ex: CancellationException) { |
| 79 | + output?.let { runCatching { Files.deleteIfExists(it) } } |
| 80 | + throw ex |
| 81 | + } catch (ex: Exception) { |
| 82 | + output?.let { runCatching { Files.deleteIfExists(it) } } |
| 83 | + logger.warn(sessionId, ex, "Could not collect SSH log $source") |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + private fun CoroutineScope.copyTail(input: FileChannel, target: FileChannel, size: Long) { |
| 88 | + var remaining = minOf(size, SSH_LOG_MAX_BYTES) |
| 89 | + var offset = size - remaining |
| 90 | + while (remaining > 0) { |
| 91 | + ensureActive() |
| 92 | + val copied = input.transferTo(offset, remaining, target) |
| 93 | + if (copied == 0L) break |
| 94 | + offset += copied |
| 95 | + remaining -= copied |
| 96 | + } |
| 97 | + } |
| 98 | +} |
0 commit comments