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

Handle Gateway links #289

Merged
merged 14 commits into from
Aug 18, 2023
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ To manually install a local build:

Alternatively, `./gradlew clean runIde` will deploy a Gateway distribution (the one specified in `gradle.properties` - `platformVersion`) with the latest plugin changes deployed.

To simulate opening a workspace from the dashboard pass the Gateway link via `--args`. For example:

```
./gradlew clean runIDE --args="jetbrains-gateway://connect#type=coder&workspace=dev&agent=coder&folder=/home/coder&url=https://dev.coder.com&token=<redacted>&ide_product_code=IU&ide_build_number=223.8836.41&ide_download_link=https://download.jetbrains.com/idea/ideaIU-2022.3.3.tar.gz"
```

Alternatively, if you have separately built the plugin and already installed it
in a Gateway distribution you can launch that distribution with the URL as the
first argument (no `--args` in this case).

### Plugin Structure

```
Expand Down
182 changes: 109 additions & 73 deletions src/main/kotlin/com/coder/gateway/CoderGatewayConnectionProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,93 +2,129 @@

package com.coder.gateway

import com.coder.gateway.sdk.humanizeDuration
import com.coder.gateway.sdk.isCancellation
import com.coder.gateway.sdk.isWorkerTimeout
import com.coder.gateway.sdk.suspendingRetryWithExponentialBackOff
import com.coder.gateway.services.CoderRecentWorkspaceConnectionsService
import com.intellij.openapi.application.ApplicationManager
import com.coder.gateway.models.TokenSource
import com.coder.gateway.sdk.CoderCLIManager
import com.coder.gateway.sdk.CoderRestClient
import com.coder.gateway.sdk.ex.AuthenticationResponseException
import com.coder.gateway.sdk.toURL
import com.coder.gateway.sdk.v2.models.toAgentModels
import com.coder.gateway.sdk.withPath
import com.coder.gateway.services.CoderSettingsState
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.rd.util.launchUnderBackgroundProgress
import com.intellij.openapi.ui.Messages
import com.jetbrains.gateway.api.ConnectionRequestor
import com.jetbrains.gateway.api.GatewayConnectionHandle
import com.jetbrains.gateway.api.GatewayConnectionProvider
import com.jetbrains.gateway.api.GatewayUI
import com.jetbrains.gateway.ssh.SshDeployFlowUtil
import com.jetbrains.gateway.ssh.SshMultistagePanelContext
import com.jetbrains.gateway.ssh.deploy.DeployException
import com.jetbrains.rd.util.lifetime.LifetimeDefinition
import kotlinx.coroutines.launch
import net.schmizz.sshj.common.SSHException
import net.schmizz.sshj.connection.ConnectionException
import java.time.Duration
import java.util.concurrent.TimeoutException
import java.net.URL

// In addition to `type`, these are the keys that we support in our Gateway
// links.
private const val URL = "url"
private const val TOKEN = "token"
private const val WORKSPACE = "workspace"
private const val AGENT = "agent"
private const val FOLDER = "folder"
private const val IDE_DOWNLOAD_LINK = "ide_download_link"
private const val IDE_PRODUCT_CODE = "ide_product_code"
private const val IDE_BUILD_NUMBER = "ide_build_number"
private const val IDE_PATH_ON_HOST = "ide_path_on_host"

// CoderGatewayConnectionProvider handles connecting via a Gateway link such as
// jetbrains-gateway://connect#type=coder.
class CoderGatewayConnectionProvider : GatewayConnectionProvider {
private val recentConnectionsService = service<CoderRecentWorkspaceConnectionsService>()
private val settings: CoderSettingsState = service()

override suspend fun connect(parameters: Map<String, String>, requestor: ConnectionRequestor): GatewayConnectionHandle? {
val clientLifetime = LifetimeDefinition()
// TODO: If this fails determine if it is an auth error and if so prompt
// for a new token, configure the CLI, then try again.
clientLifetime.launchUnderBackgroundProgress(CoderGatewayBundle.message("gateway.connector.coder.connection.provider.title"), canBeCancelled = true, isIndeterminate = true, project = null) {
try {
indicator.text = CoderGatewayBundle.message("gateway.connector.coder.connecting")
val context = suspendingRetryWithExponentialBackOff(
action = { attempt ->
logger.info("Connecting... (attempt $attempt")
if (attempt > 1) {
// indicator.text is the text above the progress bar.
indicator.text = CoderGatewayBundle.message("gateway.connector.coder.connecting.retry", attempt)
}
SshMultistagePanelContext(parameters.toHostDeployInputs())
},
retryIf = {
it is ConnectionException || it is TimeoutException
|| it is SSHException || it is DeployException
},
onException = { attempt, nextMs, e ->
logger.error("Failed to connect (attempt $attempt; will retry in $nextMs ms)")
// indicator.text2 is the text below the progress bar.
indicator.text2 =
if (isWorkerTimeout(e)) "Failed to upload worker binary...it may have timed out"
else e.message ?: CoderGatewayBundle.message("gateway.connector.no-details")
},
onCountdown = { remainingMs ->
indicator.text = CoderGatewayBundle.message("gateway.connector.coder.connecting.failed.retry", humanizeDuration(remainingMs))
},
)
launch {
logger.info("Deploying and starting IDE with $context")
// At this point JetBrains takes over with their own UI.
@Suppress("UnstableApiUsage") SshDeployFlowUtil.fullDeployCycle(
clientLifetime, context, Duration.ofMinutes(10)
)
}
} catch (e: Exception) {
if (isCancellation(e)) {
logger.info("Connection canceled due to ${e.javaClass}")
} else {
logger.info("Failed to connect (will not retry)", e)
// The dialog will close once we return so write the error
// out into a new dialog.
ApplicationManager.getApplication().invokeAndWait {
Messages.showMessageDialog(
e.message ?: CoderGatewayBundle.message("gateway.connector.no-details"),
CoderGatewayBundle.message("gateway.connector.coder.connection.failed"),
Messages.getErrorIcon())
}
}
CoderRemoteConnectionHandle().connect{ indicator ->
logger.debug("Launched Coder connection provider", parameters)

val deploymentURL = parameters[URL]
?: CoderRemoteConnectionHandle.ask("Enter the full URL of your Coder deployment")
if (deploymentURL.isNullOrBlank()) {
throw IllegalArgumentException("Query parameter \"$URL\" is missing")
}
}

recentConnectionsService.addRecentConnection(parameters.toRecentWorkspaceConnection())
GatewayUI.getInstance().reset()
val (client, username) = authenticate(deploymentURL.toURL(), parameters[TOKEN])

// TODO: If these are missing we could launch the wizard.
val name = parameters[WORKSPACE] ?: throw IllegalArgumentException("Query parameter \"$WORKSPACE\" is missing")
val agent = parameters[AGENT] ?: throw IllegalArgumentException("Query parameter \"$AGENT\" is missing")
code-asher marked this conversation as resolved.
Show resolved Hide resolved

val workspaces = client.workspaces()
val agents = workspaces.flatMap { it.toAgentModels() }
val workspace = agents.firstOrNull { it.name == "$name.$agent" }
?: throw IllegalArgumentException("The agent $agent does not exist on the workspace $name or the workspace is off")

// TODO: Turn on the workspace if it is off then wait for the agent
// to be ready. Also, distinguish between whether the
// workspace is off or the agent does not exist in the error
// above instead of showing a combined error.

val cli = CoderCLIManager.ensureCLI(
deploymentURL.toURL(),
client.buildInfo().version,
settings,
indicator,
)

indicator.text = "Authenticating Coder CLI..."
cli.login(client.token)

indicator.text = "Configuring Coder CLI..."
cli.configSsh(agents)

// TODO: Ask for these if missing. Maybe we can reuse the second
// step of the wizard? Could also be nice if we automatically used
// the last IDE.
if (parameters[IDE_PRODUCT_CODE].isNullOrBlank()) {
throw IllegalArgumentException("Query parameter \"$IDE_PRODUCT_CODE\" is missing")
}
if (parameters[IDE_BUILD_NUMBER].isNullOrBlank()) {
throw IllegalArgumentException("Query parameter \"$IDE_BUILD_NUMBER\" is missing")
}
if (parameters[IDE_PATH_ON_HOST].isNullOrBlank() && parameters[IDE_DOWNLOAD_LINK].isNullOrBlank()) {
throw IllegalArgumentException("One of \"$IDE_PATH_ON_HOST\" or \"$IDE_DOWNLOAD_LINK\" is required")
}

// TODO: Ask for the project path if missing and validate the path.
val folder = parameters[FOLDER] ?: throw IllegalArgumentException("Query parameter \"$FOLDER\" is missing")
code-asher marked this conversation as resolved.
Show resolved Hide resolved

parameters
.withWorkspaceHostname(CoderCLIManager.getHostName(deploymentURL.toURL(), workspace))
.withProjectPath(folder)
.withWebTerminalLink(client.url.withPath("/@$username/$workspace.name/terminal").toString())
.withConfigDirectory(cli.coderConfigPath.toString())
.withName(name)
}
return null
}

/**
* Return an authenticated Coder CLI and the user's name, asking for the
* token as long as it continues to result in an authentication failure.
*/
private fun authenticate(deploymentURL: URL, queryToken: String?, lastToken: Pair<String, TokenSource>? = null): Pair<CoderRestClient, String> {
// Use the token from the query, unless we already tried that.
val isRetry = lastToken != null
val token = if (!queryToken.isNullOrBlank() && !isRetry)
Pair(queryToken, TokenSource.QUERY)
else CoderRemoteConnectionHandle.askToken(
deploymentURL,
lastToken,
isRetry,
useExisting = true,
)
if (token == null) { // User aborted.
throw IllegalArgumentException("Unable to connect to $deploymentURL, $TOKEN is missing")
}
val client = CoderRestClient(deploymentURL, token.first)
return try {
Pair(client, client.me().username)
} catch (ex: AuthenticationResponseException) {
authenticate(deploymentURL, queryToken, token)
code-asher marked this conversation as resolved.
Show resolved Hide resolved
}
}

override fun isApplicable(parameters: Map<String, String>): Boolean {
return parameters.areCoderType()
}
Expand Down
Loading
Loading