Skip to content
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

Impl: update ssh config when settings change #51

Merged
merged 2 commits into from
Mar 29, 2025
Merged
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
4 changes: 4 additions & 0 deletions src/main/kotlin/com/coder/toolbox/CoderRemoteEnvironment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -204,4 +204,8 @@ class CoderRemoteEnvironment(
* Companion to equals, for sets.
*/
override fun hashCode(): Int = id.hashCode()

override fun toString(): String {
return "CoderRemoteEnvironment(name='$name')"
}
}
43 changes: 29 additions & 14 deletions src/main/kotlin/com/coder/toolbox/CoderRemoteProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,16 @@ import com.jetbrains.toolbox.api.remoteDev.RemoteProvider
import com.jetbrains.toolbox.api.remoteDev.RemoteProviderEnvironment
import com.jetbrains.toolbox.api.ui.actions.ActionDescription
import com.jetbrains.toolbox.api.ui.components.UiPage
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.onTimeout
import kotlinx.coroutines.selects.select
import okhttp3.OkHttpClient
import java.net.URI
import java.net.URL
Expand All @@ -35,18 +38,20 @@ import kotlin.time.Duration.Companion.seconds
import com.jetbrains.toolbox.api.ui.components.AccountDropdownField as DropDownMenu
import com.jetbrains.toolbox.api.ui.components.AccountDropdownField as dropDownFactory

@OptIn(ExperimentalCoroutinesApi::class)
class CoderRemoteProvider(
private val context: CoderToolboxContext,
private val httpClient: OkHttpClient,
) : RemoteProvider("Coder") {
// Current polling job.
private var pollJob: Job? = null
private var lastEnvironments: Set<CoderRemoteEnvironment>? = null
private val lastEnvironments = mutableSetOf<CoderRemoteEnvironment>()

private val cSettings = context.settingsStore.readOnly()
private val settings = context.settingsStore.readOnly()

// Create our services from the Toolbox ones.
private val settingsPage: CoderSettingsPage = CoderSettingsPage(context)
private val triggerSshConfig = Channel<Boolean>(Channel.CONFLATED)
private val settingsPage: CoderSettingsPage = CoderSettingsPage(context, triggerSshConfig)
private val dialogUi = DialogUi(context)

// The REST client, if we are signed in
Expand Down Expand Up @@ -92,7 +97,7 @@ class CoderRemoteProvider(
}?.map { agent ->
// If we have an environment already, update that.
val env = CoderRemoteEnvironment(context, client, ws, agent)
lastEnvironments?.firstOrNull { it == env }?.let {
lastEnvironments.firstOrNull { it == env }?.let {
it.update(ws, agent)
it
} ?: env
Expand All @@ -107,9 +112,7 @@ class CoderRemoteProvider(

// Reconfigure if a new environment is found.
// TODO@JB: Should we use the add/remove listeners instead?
val newEnvironments = lastEnvironments
?.let { resolvedEnvironments.subtract(it) }
?: resolvedEnvironments
val newEnvironments = resolvedEnvironments.subtract(lastEnvironments)
if (newEnvironments.isNotEmpty()) {
context.logger.info("Found new environment(s), reconfiguring CLI: $newEnvironments")
cli.configSsh(newEnvironments.map { it.name }.toSet())
Expand All @@ -124,8 +127,10 @@ class CoderRemoteProvider(
true
}
}

lastEnvironments = resolvedEnvironments
lastEnvironments.apply {
clear()
addAll(resolvedEnvironments)
}
} catch (_: CancellationException) {
context.logger.debug("${client.url} polling loop canceled")
break
Expand All @@ -136,7 +141,17 @@ class CoderRemoteProvider(
break
}
// TODO: Listening on a web socket might be better?
delay(5.seconds)
select<Unit> {
onTimeout(5.seconds) {
context.logger.trace("workspace poller waked up by the 5 seconds timeout")
}
triggerSshConfig.onReceive { shouldTrigger ->
if (shouldTrigger) {
context.logger.trace("workspace poller waked up because it should reconfigure the ssh configurations")
cli.configSsh(lastEnvironments.map { it.name }.toSet())
}
}
}
}
}

Expand Down Expand Up @@ -178,7 +193,7 @@ class CoderRemoteProvider(
override fun close() {
pollJob?.cancel()
client?.close()
lastEnvironments = null
lastEnvironments.clear()
environments.value = LoadableState.Value(emptyList())
isInitialized.update { false }
}
Expand Down Expand Up @@ -270,7 +285,7 @@ class CoderRemoteProvider(
var autologinEx: Exception? = null
context.secrets.lastToken.let { lastToken ->
context.secrets.lastDeploymentURL.let { lastDeploymentURL ->
if (autologin && lastDeploymentURL.isNotBlank() && (lastToken.isNotBlank() || !cSettings.requireTokenAuth)) {
if (autologin && lastDeploymentURL.isNotBlank() && (lastToken.isNotBlank() || !settings.requireTokenAuth)) {
try {
return createConnectPage(URL(lastDeploymentURL), lastToken)
} catch (ex: Exception) {
Expand Down Expand Up @@ -342,7 +357,7 @@ class CoderRemoteProvider(
if (it.isNotBlank() && context.secrets.lastDeploymentURL == deploymentURL.toString()) {
it to SettingSource.LAST_USED
} else {
cSettings.token(deploymentURL)
settings.token(deploymentURL)
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/main/kotlin/com/coder/toolbox/cli/CoderCLIManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import com.coder.toolbox.cli.ex.ResponseException
import com.coder.toolbox.cli.ex.SSHConfigFormatException
import com.coder.toolbox.sdk.v2.models.Workspace
import com.coder.toolbox.sdk.v2.models.WorkspaceAgent
import com.coder.toolbox.settings.CoderSettings
import com.coder.toolbox.settings.ReadOnlyCoderSettings
import com.coder.toolbox.util.CoderHostnameVerifier
import com.coder.toolbox.util.InvalidVersionException
import com.coder.toolbox.util.OS
Expand Down Expand Up @@ -125,7 +125,7 @@ class CoderCLIManager(
private val deploymentURL: URL,
private val logger: Logger,
// Plugin configuration.
private val settings: CoderSettings,
private val settings: ReadOnlyCoderSettings,
// If the binary directory is not writable, this can be used to force the
// manager to download to the data directory instead.
forceDownloadToData: Boolean = false,
Expand Down Expand Up @@ -267,21 +267,21 @@ class CoderCLIManager(
"--url",
escape(deploymentURL.toString()),
if (!settings.headerCommand.isNullOrBlank()) "--header-command" else null,
if (!settings.headerCommand.isNullOrBlank()) escapeSubcommand(settings.headerCommand) else null,
if (!settings.headerCommand.isNullOrBlank()) escapeSubcommand(settings.headerCommand!!) else null,
"ssh",
"--stdio",
if (settings.disableAutostart && feats.disableAutostart) "--disable-autostart" else null,
)
val proxyArgs = baseArgs + listOfNotNull(
if (!settings.sshLogDirectory.isNullOrBlank()) "--log-dir" else null,
if (!settings.sshLogDirectory.isNullOrBlank()) escape(settings.sshLogDirectory) else null,
if (!settings.sshLogDirectory.isNullOrBlank()) escape(settings.sshLogDirectory!!) else null,
if (feats.reportWorkspaceUsage) "--usage-app=jetbrains" else null,
)
val backgroundProxyArgs =
baseArgs + listOfNotNull(if (feats.reportWorkspaceUsage) "--usage-app=disable" else null)
val extraConfig =
if (!settings.sshConfigOptions.isNullOrBlank()) {
"\n" + settings.sshConfigOptions.prependIndent(" ")
"\n" + settings.sshConfigOptions!!.prependIndent(" ")
} else {
""
}
Expand Down
Loading
Loading