Repository navigation
Include SSH logs in workspace diagnostics #372
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| version=0.9.4 | ||
| version=0.9.5 | ||
| group=com.coder.toolbox | ||
| name=coder-toolbox |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
src/main/kotlin/com/coder/toolbox/diagnostics/CoderSshLogCollector.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| package com.coder.toolbox.diagnostics | ||
|
|
||
| import com.coder.toolbox.session.SessionId | ||
| import kotlinx.coroutines.CancellationException | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.ensureActive | ||
| import kotlinx.coroutines.withContext | ||
| import java.nio.channels.FileChannel | ||
| import java.nio.file.Files | ||
| import java.nio.file.LinkOption.NOFOLLOW_LINKS | ||
| import java.nio.file.Path | ||
| import java.nio.file.StandardOpenOption.CREATE | ||
| import java.nio.file.StandardOpenOption.READ | ||
| import java.nio.file.StandardOpenOption.TRUNCATE_EXISTING | ||
| import java.nio.file.StandardOpenOption.WRITE | ||
| import java.nio.file.attribute.BasicFileAttributes | ||
| import java.time.Instant | ||
|
|
||
| // Include current CLI session filenames and older PID-based logs. | ||
| private val SSH_LOG_FILE = Regex("coder-ssh.*\\.log(?:\\.\\d+)?|\\d+\\.log") | ||
| private const val SSH_LOG_MAX_AGE_SECONDS = 3L * 24 * 60 * 60 | ||
| private const val SSH_LOG_MAX_BYTES = 50L * 1024 * 1024 | ||
|
|
||
| internal class CoderSshLogCollector( | ||
| private val logger: CoderLogger, | ||
| private val logDirectory: Path, | ||
| ) { | ||
| suspend fun collect( | ||
| logsRootFolder: Path, | ||
| sessionId: SessionId? = null, | ||
| activeSshPid: Long? = null, | ||
| ) = withContext(Dispatchers.IO) { | ||
| // Older CLIs may not have created any session logs. | ||
| if (Files.notExists(logDirectory)) return@withContext | ||
|
|
||
| val cutoff = Instant.now().minusSeconds(SSH_LOG_MAX_AGE_SECONDS) | ||
| val entries = Files.newDirectoryStream(logDirectory).use { it.toList() } | ||
| // CLI proxy log names end in the parent SSH PID; timestamps distinguish reused PIDs. | ||
| val activeLog = activeSshPid?.let { pid -> | ||
| entries.filter { entry -> | ||
| val name = entry.fileName.toString() | ||
| (name == "$pid.log" || (name.startsWith("coder-ssh") && name.endsWith("-$pid.log"))) && | ||
| Files.isRegularFile(entry, NOFOLLOW_LINKS) | ||
| }.maxByOrNull { it.fileName.toString() } | ||
| } | ||
| for (entry in entries) { | ||
| ensureActive() | ||
| // An active session can remain quiet longer than the collection window. | ||
| collectFile(entry, logsRootFolder.resolve("coder-ssh"), cutoff.takeUnless { entry == activeLog }, sessionId) | ||
| } | ||
| } | ||
|
|
||
| @Suppress("TooGenericExceptionCaught") | ||
| private fun CoroutineScope.collectFile(source: Path, destination: Path, cutoff: Instant?, sessionId: SessionId?) { | ||
| if (!SSH_LOG_FILE.matches(source.fileName.toString())) return | ||
|
fioan89 marked this conversation as resolved.
|
||
| var output: Path? = null | ||
| try { | ||
| val attributes = Files.readAttributes(source, BasicFileAttributes::class.java, NOFOLLOW_LINKS) | ||
| val expired = cutoff != null && attributes.lastModifiedTime().toInstant().isBefore(cutoff) | ||
| if (!attributes.isRegularFile || expired) return | ||
|
|
||
| FileChannel.open(source, READ, NOFOLLOW_LINKS).use { input -> | ||
| val size = input.size() | ||
| if (size > SSH_LOG_MAX_BYTES) { | ||
| logger.warn( | ||
| sessionId, | ||
| "Truncating SSH log $source ($size bytes) to its last $SSH_LOG_MAX_BYTES bytes", | ||
| ) | ||
| } | ||
| Files.createDirectories(destination) | ||
| val targetPath = destination.resolve(source.fileName) | ||
| output = targetPath | ||
| FileChannel.open(targetPath, CREATE, WRITE, TRUNCATE_EXISTING).use { target -> | ||
| copyTail(input, target, size) | ||
| } | ||
| } | ||
| } catch (ex: CancellationException) { | ||
| output?.let { runCatching { Files.deleteIfExists(it) } } | ||
| throw ex | ||
| } catch (ex: Exception) { | ||
| output?.let { runCatching { Files.deleteIfExists(it) } } | ||
| logger.warn(sessionId, ex, "Could not collect SSH log $source") | ||
| } | ||
| } | ||
|
|
||
| private fun CoroutineScope.copyTail(input: FileChannel, target: FileChannel, size: Long) { | ||
| var remaining = minOf(size, SSH_LOG_MAX_BYTES) | ||
| var offset = size - remaining | ||
| while (remaining > 0) { | ||
| ensureActive() | ||
| val copied = input.transferTo(offset, remaining, target) | ||
| if (copied == 0L) break | ||
| offset += copied | ||
| remaining -= copied | ||
| } | ||
| } | ||
| } | ||
31 changes: 25 additions & 6 deletions
31
src/main/kotlin/com/coder/toolbox/diagnostics/CoderSupportBundleCollector.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,39 +1,58 @@ | ||
| package com.coder.toolbox.diagnostics | ||
|
|
||
| import com.coder.toolbox.session.SessionId | ||
| import com.jetbrains.toolbox.api.remoteDev.deploy.DiagnosticInfoCollector | ||
| import kotlinx.coroutines.CancellationException | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.withContext | ||
| import java.nio.file.Files | ||
| import java.nio.file.Path | ||
|
|
||
| /** Collects a Coder support bundle for a workspace and its optional agent. */ | ||
| /** Collects a workspace support bundle and recent local Coder SSH logs. */ | ||
| internal class CoderSupportBundleCollector( | ||
| private val logger: CoderLogger, | ||
| sshLogDirectory: Path, | ||
| private val currentSessionId: () -> SessionId? = { null }, | ||
| private val sshPid: Long? = null, | ||
| private val collectBundle: suspend (Path) -> Unit, | ||
| ) : DiagnosticInfoCollector { | ||
| private val sshLogs = CoderSshLogCollector(logger, sshLogDirectory) | ||
|
|
||
| // Toolbox discards the additional-diagnostics directory if the collector throws. | ||
| @Suppress("TooGenericExceptionCaught") | ||
| override suspend fun collectAdditionalDiagnostics(logsRootFolder: Path) = withContext(Dispatchers.IO) { | ||
| val bundle = logsRootFolder.resolve("coder-support.zip") | ||
| val sessionId = currentSessionId() | ||
| try { | ||
| Files.createDirectories(logsRootFolder) | ||
| collectSupportBundle(logsRootFolder, sessionId) | ||
| sshLogs.collect(logsRootFolder, sessionId, sshPid) | ||
| } catch (ex: CancellationException) { | ||
| throw ex | ||
| } catch (ex: Exception) { | ||
| logger.warn(sessionId, ex, "Could not collect Coder workspace diagnostics") | ||
| } | ||
| } | ||
|
|
||
| // A failed bundle is replaced by an error report so the SSH logs are still collected. | ||
| @Suppress("TooGenericExceptionCaught") | ||
| private suspend fun collectSupportBundle(logsRootFolder: Path, sessionId: SessionId?) { | ||
| val bundle = logsRootFolder.resolve("coder-support.zip") | ||
| try { | ||
| collectBundle(bundle) | ||
| } catch (ex: CancellationException) { | ||
| runCatching { Files.deleteIfExists(bundle) } | ||
| throw ex | ||
| } catch (ex: Exception) { | ||
| logger.warn(ex, "Could not collect the Coder support bundle") | ||
| runCatching { Files.deleteIfExists(bundle) } | ||
| logger.warn(sessionId, ex, "Could not collect the Coder support bundle") | ||
| runCatching { | ||
| Files.deleteIfExists(bundle) | ||
| Files.writeString( | ||
| logsRootFolder.resolve("coder-support-error.txt"), | ||
| "Coder support bundle collection failed (${ex.javaClass.simpleName}). " + | ||
| "Check deployment connectivity, login, and CLI support for 'coder support bundle' " + | ||
| "(Coder 2.10 or newer). Other Toolbox logs are still available.\n", | ||
| ) | ||
| }.onFailure { logger.warn(it, "Could not write the Coder diagnostic failure report") } | ||
| }.onFailure { logger.warn(sessionId, it, "Could not write the Coder diagnostic failure report") } | ||
| } | ||
| Unit | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What if we set
--log-diron the proxy command? That would remove the need to sniff out what dir the cli would use, and it could be nice to keep the Jetbrains connection logs in a separate dir.And while the cli probably will not change the default location, it would protect us against such a change.
And maybe best of all, it would work for older clis that still do not log by default (although this could also be a downside because it would predate the cleanup as well...).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Asher if you are ok with this, I'll explore in a separate PR this approach.