Skip to content
Closed
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
225 changes: 218 additions & 7 deletions src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,20 @@
import com.redhat.devtools.gateway.devworkspace.DevWorkspaces
import com.redhat.devtools.gateway.download.DevSpacesClientConnectProgress
import com.redhat.devtools.gateway.download.DevSpacesClientMirror
import com.redhat.devtools.gateway.openshift.DevWorkspacePods
import com.redhat.devtools.gateway.openshift.PodPortForwarder
import com.redhat.devtools.gateway.openshift.PortForwardSession
import com.redhat.devtools.gateway.openshift.PortForwarder
import com.redhat.devtools.gateway.server.RemoteIDEServer
import com.redhat.devtools.gateway.server.RemoteIDEServerStatus
import com.redhat.devtools.gateway.util.ProgressCountdown
import com.redhat.devtools.gateway.util.callerFrames
import com.redhat.devtools.gateway.util.isCancellationException
import com.redhat.devtools.gateway.util.isServerContainerNotFound
import com.redhat.devtools.gateway.view.ui.Dialogs
import io.kubernetes.client.openapi.models.V1Pod
import kotlinx.coroutines.*
import java.io.IOException
import java.net.URI
import java.util.concurrent.CancellationException
import java.util.concurrent.atomic.AtomicBoolean
Expand All @@ -55,6 +59,7 @@
* restarts it, and a stop (Dashboard or Gateway) closes the port forward at once so the Guest
* reports the loss without waiting for the pod to terminate.
*/
@Suppress("TooManyFunctions") // the connection lifecycle is one cohesive operation
class DevSpacesConnection internal constructor(
private val devSpacesContext: DevSpacesContext,
private val clientWindowFocus: ClientWindowFocus,
Expand All @@ -68,12 +73,23 @@

companion object {
private const val CONNECT_POLL: Long = 200 // millis
private const val REMOTE_IDE_PORT = 5990
}

/** Ensures [tearDownConnection] runs at most once for this connect attempt. */
private val tearDownStarted = AtomicBoolean(false)

/**
* Watches the Guest's re-dial while the connection is lost. Set once the session is live and
* cleared when recovery ends; [tearDownConnection] reads its state to withhold the workspace
* auto-stop (§7.9) and [startRecovery] starts it from the forwarder's remote-end signal.
*/
@Volatile
private var recoveryWatcher: ThinClientRecoveryWatcher? = null

/** Owns the recovery loop, so cancelling it ends recovery with the client session. */
@Volatile
private var recoveryScope: CoroutineScope? = null

@Throws(Exception::class)
@Suppress("UnstableApiUsage", "LongParameterList") // this is the connection API surface
suspend fun connect(
Expand All @@ -88,6 +104,7 @@
): ThinClientHandle {
val workspace = workspace ?: devSpacesContext.devWorkspace
tearDownStarted.set(false)
stopRecovery()
clientWindowFocus.resetThrottle()
devSpacesContext.addWorkspace(workspace)

Expand All @@ -109,30 +126,40 @@
checkCancelled?.invoke()
progress.waitingForClientStart()

// the forwarder outlives the client handle creation: resolve the handle lazily
// the forwarder outlives the client handle creation: resolve the handle lazily.
// The resolver lets the forward follow a replacement pod: while the DevWorkspace stays
// Running, the workspace - not the pod pinned here - is what keeps serving.
val portForwardSession = portForwarder
.forward(remoteIdeServer.pod, REMOTE_IDE_PORT) {
client?.let(clientWindowFocus::requestFocus)
.forward(
remoteIdeServer.pod,
ThinClientJoinLink.REMOTE_IDE_PORT,
{ findRunningPod(workspace) },
) {
onRemoteEnd(client)
}

forwarder = portForwardSession

val localJoinLink = joinLink.replace(":$REMOTE_IDE_PORT", ":${portForwardSession.localPort}")
val localJoinLink = ThinClientJoinLink.toLocal(URI(joinLink), portForwardSession.localPort)
val connectFailed = AtomicBoolean(false)

checkCancelled?.invoke()
clientMirror = mirrorClient(URI(localJoinLink), progress, checkCancelled)
clientMirror = mirrorClient(localJoinLink, progress, checkCancelled)
client = startClient(
URI(localJoinLink), workspace, onConnected, onConnectionEnded, onDevWorkspaceStopped,
localJoinLink, workspace, onConnected, onConnectionEnded, onDevWorkspaceStopped,
remoteIdeServer, forwarder, connectFailed, connectionLive
)

progress.startingClient()
waitForConnect(client, connectFailed, checkCancelled)

connectionLive.set(true)
portForwardSession.markEstablished()
onConnected()
watchSession(workspace, client, portForwardSession, handleRestarts = registerRestartWatcher)
// the pod the local join link was built against: a different pod serves the same link
// with a new idea-server session token, so recovery must treat the link as stale
prepareRecovery(workspace, client, portForwardSession, localJoinLink, remoteIdeServer.pod)
client
} catch (e: Exception) {
if (e !is ThinClientLaunchException || connectionLive.get()) {
Expand Down Expand Up @@ -206,6 +233,8 @@
workspaces.removeRestartRequest(workspace.namespace, workspace.name)
},
onStopped = {
// the workspace is going down: nothing to recover into
stopRecovery()
// close sockets -> Guest EOF, immediate status loss
// close listener -> pod pinned, re-dial would hit stopped pod
forwarder.close()
Expand All @@ -218,9 +247,187 @@
thinClient.lifetime.onTermination {
sessionWatch.stop()
sessionWatchScope.cancel()
stopRecovery()
}
}

/**
* Builds the recovery watcher of this session. Nothing starts yet: the Guest may be perfectly
* fine. [startRecovery] starts it on the forward's remote-end signal; the client's lifetime and
* the teardown stop it.
*
* Recovery observes the existing Guest only: it resolves the current workspace pod itself and
* prods that Guest to re-dial. It never starts a new client and never closes one.
*
* @param sessionPod the pod [localJoinLink] was built against; when a different pod serves the
* workspace, the link's session token is unknown to it and recovery refreshes the link.
*/
private fun prepareRecovery(
workspace: DevWorkspace,
thinClient: ThinClientHandle,

Check warning on line 267 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'com.jetbrains.gateway.thinClientLink.ThinClientHandle' is marked unstable with @ApiStatus.Experimental

Check warning on line 267 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Inspect code

Unstable API Usage

'com.jetbrains.gateway.thinClientLink.ThinClientHandle' is marked unstable with @ApiStatus.Experimental
session: PortForwardSession,
localJoinLink: URI,
sessionPod: V1Pod
) {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
recoveryScope = scope
recoveryWatcher = ThinClientRecoveryWatcher(
ThinClientRecoveryWatcher.Collaborators(
resolvePod = { findRunningPod(workspace) },
probe = { pod -> portForwarder.probe(pod, ThinClientJoinLink.REMOTE_IDE_PORT) },
cachedLink = localJoinLink,
sessionPod = sessionPod,
refreshLink = refreshJoinLink(workspace, session.localPort),
prod = prodJoinLink(thinClient),
session = session,
isClientPresent = { thinClient.clientPresent },

Check warning on line 283 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'getClientPresent()' is declared in unstable 'com.jetbrains.gateway.thinClientLink.ThinClientHandle' marked with @ApiStatus.Experimental

Check warning on line 283 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Inspect code

Unstable API Usage

'getClientPresent()' is declared in unstable 'com.jetbrains.gateway.thinClientLink.ThinClientHandle' marked with @ApiStatus.Experimental
onRecovered = { reportRecovered(thinClient) },
onRecoveryFailed = { reportRecoveryFailed(thinClient, workspace) }
)
)
thinClient.lifetime.onTermination {

Check warning on line 288 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'getLifetime()' is declared in unstable 'com.jetbrains.gateway.thinClientLink.ThinClientHandle' marked with @ApiStatus.Experimental

Check warning on line 288 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Inspect code

Unstable API Usage

'getLifetime()' is declared in unstable 'com.jetbrains.gateway.thinClientLink.ThinClientHandle' marked with @ApiStatus.Experimental
stopRecovery()
scope.cancel()
}
}

/**
* The forward ended: the Guest lost its connection. Surface the loss and prod the Guest to
* re-dial. Starting is idempotent, so a session that keeps ending does not spawn a second loop.
*/
private fun onRemoteEnd(client: ThinClientHandle?) {

Check warning on line 298 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'com.jetbrains.gateway.thinClientLink.ThinClientHandle' is marked unstable with @ApiStatus.Experimental

Check warning on line 298 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Inspect code

Unstable API Usage

'com.jetbrains.gateway.thinClientLink.ThinClientHandle' is marked unstable with @ApiStatus.Experimental
client?.let(clientWindowFocus::requestFocus)
startRecovery()
}

private fun startRecovery() {
val watcher = recoveryWatcher
val scope = recoveryScope
// teardown already running: a connection that ends now must not start a recovery
if (!tearDownStarted.get() && watcher != null && scope != null) {
watcher.start(scope)
}
}

/**
* Stops recovery and reports whether it was running.
*
* The running state is read *before* the watcher is stopped, so stopping does not erase it; the
* return value carries it to the caller. Teardown uses it to withhold the workspace auto-stop
* (§7.9): a Guest closed during recovery must not stop a workspace that may come back once the
* outage clears. Only the remote `stop()` is withheld — the rest of the teardown is unchanged.
*/
private fun stopRecovery(): Boolean {
val watcher = recoveryWatcher
val wasActive = watcher?.isActive == true
if (watcher != null) {
thisLogger().info(
"Stopping connection recovery (wasActive=$wasActive); " +
"caller=${callerFrames(javaClass.name)}"
)
}
watcher?.stop()
recoveryWatcher = null
recoveryScope?.cancel()
recoveryScope = null
return wasActive
}

/**
* Installs the recovery watcher of this session; [prepareRecovery] wires the production one.
* Internal so a test can emulate a recovery in progress without a cluster.
*/
internal fun installRecoveryWatcher(watcher: ThinClientRecoveryWatcher?) {
recoveryWatcher = watcher
}

/**
* The pod that serves [workspace] right now. Runs on the watcher's IO coroutine; a failure is
* retried on its next poll.
*/
private fun findRunningPod(workspace: DevWorkspace): V1Pod? =
DevWorkspacePods(devSpacesContext.client).findFirstRunning(
workspace.namespace,
"${DevWorkspacePods.WORKSPACE_LABEL_KEY}=${workspace.name}"
)

/**
* Builds a fresh local join link for the *current* pod, or `null` while none can be built yet.
*
* Constructing [RemoteIDEServer] resolves the pod and its container atomically; its
* [IOException] means "no running, ready pod yet", which is not a recovery failure — the watcher
* keeps polling. [RemoteIDEServer.getStatus] execs the IDE server status once, bounded by
* [RemoteIDEServer.STATUS_EXEC_TIMEOUT], and runs off the EDT.
*
* A server that answers but reports no usable link is logged at info: recovery waits instead of
* prodding while that is the case, so "why is it not prodding?" must be answerable from the log.
*/
@Suppress("TooGenericExceptionCaught") // a malformed link or a failed exec only means "poll again"
private fun refreshJoinLink(workspace: DevWorkspace, localPort: Int): suspend () -> URI? = {
try {
val status = RemoteIDEServer(devSpacesContext, workspace).getStatus()
if (status.isReady && status.joinLink != null) {
ThinClientJoinLink.toLocal(URI(status.joinLink), localPort)
} else {
thisLogger().info(
"Workspace '${workspace.name}' reports no join link yet " +
"(ready=${status.isReady}); recovery waits for a fresh link."
)
null
}
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
thisLogger().debug("No running, ready pod to build a join link from; retrying.", e)
null
} catch (e: Exception) {
// a malformed link or a failed exec must not end recovery: the next poll retries
if (e.isCancellationException()) throw e
thisLogger().debug("Could not build a fresh join link; retrying.", e)
null
}
}

/**
* The transparent lever (verified in the Guest): `updateJoinLink(forceReconnect = true)` drops
* the RD link and re-dials the given one, keeping the window open. A throwing handle is caught
* by the watcher, which then checks whether the client is still present.
*/
@Suppress("UnstableApiUsage")
private fun prodJoinLink(thinClient: ThinClientHandle): suspend (URI) -> Unit = { link ->
thinClient.updateJoinLink(link, true)
}

private fun reportRecovered(thinClient: ThinClientHandle) {

Check warning on line 401 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'com.jetbrains.gateway.thinClientLink.ThinClientHandle' is marked unstable with @ApiStatus.Experimental

Check warning on line 401 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Inspect code

Unstable API Usage

'com.jetbrains.gateway.thinClientLink.ThinClientHandle' is marked unstable with @ApiStatus.Experimental
thisLogger().info(
"Recovered the connection to the workspace; the JetBrains Client keeps its window."
)
// the Guest repaints its connection status when its window is brought to the front
clientWindowFocus.requestFocus(thinClient)
}

/**
* Recovery is definitively over. Reported only if the Guest still exists: a Guest that is gone
* was closed by the user or by the platform's own websocket timeout, so there is nobody to tell.
* Nothing is relaunched and no client is closed; the workspace stop decision is no longer ours.
*/
private fun reportRecoveryFailed(thinClient: ThinClientHandle, workspace: DevWorkspace) {

Check warning on line 414 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'com.jetbrains.gateway.thinClientLink.ThinClientHandle' is marked unstable with @ApiStatus.Experimental

Check warning on line 414 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Inspect code

Unstable API Usage

'com.jetbrains.gateway.thinClientLink.ThinClientHandle' is marked unstable with @ApiStatus.Experimental
val workspacePath = "${workspace.namespace}/${workspace.name}"
if (!thinClient.clientPresent) {

Check warning on line 416 in src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'getClientPresent()' is declared in unstable 'com.jetbrains.gateway.thinClientLink.ThinClientHandle' marked with @ApiStatus.Experimental
thisLogger().warn(
"Could not restore the connection to workspace $workspacePath; " +
"the JetBrains Client is gone, not showing a dialog."
)
return
}
thisLogger().warn("Could not restore the connection to workspace $workspacePath.")
Dialogs.error(
"The connection to workspace '${workspace.name}' could not be restored. " +
"Close the client and connect again.",
"Connection Error"
)
}

/**
* Returns the handler for the restart annotation. [DevWorkspaceRestart.execute] only submits a
* background task, so it runs inline on the watch coroutine (already off the EDT): the watch
Expand Down Expand Up @@ -260,6 +467,9 @@
runCatching { onConnectionEnded() }

CoroutineScope(Dispatchers.IO).launch {
// §7.9: the state is read *before* stopping, so the teardown below still knows that a
// recovery was running and withholds only the remote stop()
val recoveryWasActive = stopRecovery()
runCatching { client?.close() }
val workspacePatch = DevWorkspacePatch(
workspace.namespace,
Expand All @@ -272,6 +482,7 @@
try {
val restartInProgress = workspacePatch.hasRestartAnnotation()
if (!restartInProgress
&& !recoveryWasActive
&& true == remoteIdeServer?.waitServerTerminated()) {
// User closed the IDE and asked to stop the workspace.
DevWorkspaces(devSpacesContext.client)
Expand Down
Loading
Loading