diff --git a/src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt b/src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt index e4b41bb2..5457a684 100644 --- a/src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt +++ b/src/main/kotlin/com/redhat/devtools/gateway/DevSpacesConnection.kt @@ -23,16 +23,20 @@ import com.redhat.devtools.gateway.devworkspace.DevWorkspaceSessionWatch 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 @@ -55,6 +59,7 @@ import java.util.concurrent.atomic.AtomicBoolean * 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, @@ -68,12 +73,23 @@ class DevSpacesConnection internal constructor( 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( @@ -88,6 +104,7 @@ class DevSpacesConnection internal constructor( ): ThinClientHandle { val workspace = workspace ?: devSpacesContext.devWorkspace tearDownStarted.set(false) + stopRecovery() clientWindowFocus.resetThrottle() devSpacesContext.addWorkspace(workspace) @@ -109,21 +126,27 @@ class DevSpacesConnection internal constructor( 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 ) @@ -131,8 +154,12 @@ class DevSpacesConnection internal constructor( 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()) { @@ -206,6 +233,8 @@ class DevSpacesConnection internal constructor( 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() @@ -218,9 +247,187 @@ class DevSpacesConnection internal constructor( 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, + 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 }, + onRecovered = { reportRecovered(thinClient) }, + onRecoveryFailed = { reportRecoveryFailed(thinClient, workspace) } + ) + ) + thinClient.lifetime.onTermination { + 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?) { + 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) { + 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) { + val workspacePath = "${workspace.namespace}/${workspace.name}" + if (!thinClient.clientPresent) { + 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 @@ -260,6 +467,9 @@ class DevSpacesConnection internal constructor( 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, @@ -272,6 +482,7 @@ class DevSpacesConnection internal constructor( try { val restartInProgress = workspacePatch.hasRestartAnnotation() if (!restartInProgress + && !recoveryWasActive && true == remoteIdeServer?.waitServerTerminated()) { // User closed the IDE and asked to stop the workspace. DevWorkspaces(devSpacesContext.client) diff --git a/src/main/kotlin/com/redhat/devtools/gateway/ThinClientJoinLink.kt b/src/main/kotlin/com/redhat/devtools/gateway/ThinClientJoinLink.kt new file mode 100644 index 00000000..e932b7e9 --- /dev/null +++ b/src/main/kotlin/com/redhat/devtools/gateway/ThinClientJoinLink.kt @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2024-2026 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package com.redhat.devtools.gateway + +import java.net.URI + +/** + * Rewrites the join link the IDE server reports so the Guest dials a local port-forward instead of + * the pod, and lets that link be varied for reconnection. + * + * The Guest's same-link no-op guard ignores an `UpdateLink` message whose link equals the previous + * one while a project window is open. It compares the link text, so [withReconnectNonce] makes two + * prods distinct by adding a fragment parameter. Fragment parameters survive the Guest's + * `patchConnectionLink`, which merges the new link's fragment parameters onto its gateway URI. + * + * Stateless pure transformations: no dependencies, no lifecycle, so an object (one instance) over a + * class the caller would have to instantiate. + */ +internal object ThinClientJoinLink { + + /** The port the IDE server listens on inside the DevWorkspace pod. */ + const val REMOTE_IDE_PORT: Int = 5990 + + /** Fragment parameter carrying the reconnect nonce. */ + const val RECONNECT_PARAMETER: String = "gatewayReconnect" + + private const val MIN_PORT = 1 + private const val MAX_PORT = 65_535 + private const val PARAMETER_SEPARATOR = '&' + private const val NAME_VALUE_SEPARATOR = '=' + + /** + * Replaces the IDE server port in [joinLink] with [localPort], preserving scheme, host, path, + * query, and fragment. Fails fast when the link does not address [REMOTE_IDE_PORT]: a malformed + * link must surface as an error instead of silently pointing the Guest at the wrong port. + */ + fun toLocal(joinLink: URI, localPort: Int): URI { + require(localPort in MIN_PORT..MAX_PORT) { + "Local port must be a valid TCP port, was $localPort" + } + val authority = requireNotNull(joinLink.rawAuthority) { + "Join link has no authority, cannot locate the IDE server port: $joinLink" + } + val remotePortSuffix = ":$REMOTE_IDE_PORT" + require(joinLink.port == REMOTE_IDE_PORT && authority.endsWith(remotePortSuffix)) { + "Join link does not address the IDE server port $REMOTE_IDE_PORT: $joinLink" + } + val localAuthority = authority.dropLast(remotePortSuffix.length) + ":$localPort" + return URI( + joinLink.scheme, + localAuthority, + joinLink.rawPath, + joinLink.rawQuery, + joinLink.rawFragment + ) + } + + /** + * Adds or replaces the [RECONNECT_PARAMETER] fragment parameter with [nonce], so two links built + * from the same join link are never byte-identical while all other fragment parameters survive. + */ + fun withReconnectNonce(link: URI, nonce: Long): URI { + val fragment = withFragmentParameter( + link.rawFragment, + RECONNECT_PARAMETER, + nonce.toString() + ) + return URI(link.scheme, link.rawAuthority, link.rawPath, link.rawQuery, fragment) + } + + /** Replaces [name] in place when present, appends it otherwise; keeps every other parameter. */ + private fun withFragmentParameter(fragment: String?, name: String, value: String): String { + val parameters = fragment.orEmpty() + .split(PARAMETER_SEPARATOR) + .filter { it.isNotEmpty() } + var isPresent = false + val updated = parameters.map { parameter -> + if (parameter.substringBefore(NAME_VALUE_SEPARATOR) == name) { + isPresent = true + "$name$NAME_VALUE_SEPARATOR$value" + } else { + parameter + } + } + val withNonce = if (isPresent) updated else updated + "$name$NAME_VALUE_SEPARATOR$value" + return withNonce.joinToString(PARAMETER_SEPARATOR.toString()) + } +} diff --git a/src/main/kotlin/com/redhat/devtools/gateway/ThinClientRecoveryWatcher.kt b/src/main/kotlin/com/redhat/devtools/gateway/ThinClientRecoveryWatcher.kt new file mode 100644 index 00000000..58759a7a --- /dev/null +++ b/src/main/kotlin/com/redhat/devtools/gateway/ThinClientRecoveryWatcher.kt @@ -0,0 +1,737 @@ +/* + * Copyright (c) 2026 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package com.redhat.devtools.gateway + +import com.intellij.openapi.diagnostic.thisLogger +import com.redhat.devtools.gateway.openshift.DIAL_CONFIRMATION_MS +import com.redhat.devtools.gateway.openshift.ForwardDials +import com.redhat.devtools.gateway.openshift.describePod +import com.redhat.devtools.gateway.openshift.isSamePod +import com.redhat.devtools.gateway.util.callerFrames +import io.kubernetes.client.openapi.models.V1Pod +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import java.net.URI +import java.util.concurrent.CancellationException +import java.util.concurrent.atomic.AtomicBoolean + +/** + * Brings an open JetBrains Client back to its workspace **transparently**: the window is never + * closed and never relaunched, the existing Guest is prodded to re-dial the plugin's port forward. + * + * The watcher covers the outage the plugin's own layers cannot heal: the forwarder keeps retrying + * while the Guest keeps re-dialing, but once the Guest has given up, only a prod from the Gateway + * side can make it try again. Recovery is read from the forward, never from the platform: a + * successful prod only proves a message was queued, so the watcher waits for a dial outcome on the + * session ([ForwardDials]). + * + * **What counts as recovery.** Only a dial that outlived [DIAL_CONFIRMATION_MS] does. An open TCP + * copy or a long-lived dial proves nothing on its own: CRW-13910 live testing measured stale-link + * dials copied for 6.5–6.9 s before the Guest's own transport-creation timeout dropped them (6 s), + * and those dials never carried an RD session. + * + * **A replaced pod makes the cached link stale by definition.** A new pod is a new idea-server + * process with a new session token, so the `jt`/`fp` the Guest dials are unknown to it and every + * dial with the cached link is doomed however long it is copied. The watcher detects the roll by pod + * identity ([Collaborators.sessionPod] vs. the pod that serves the workspace now), not by guessing + * from dial lifetimes. + * + * **A prod is a project restart, so it is the last resort.** `updateJoinLink(forceReconnect = + * true)` makes the Guest dispose the project and re-open it: state survives server-side, but the + * window is replaced by a new frame. The Guest's own seamless loop preserves the frame, so the + * watcher lets it finish a dial in flight and only prods once that loop is proven unable to recover. + * + * **A link known stale is never prodded.** Such a prod cannot succeed - the session token is + * unknown to the new idea-server - and each one makes the Guest re-open its project against a dead + * session, burning its project-open retries: CRW-13910 live testing saw the Guest close itself + * (exitCode 178) after two prods carrying a stale link. Without a rebuilt link the watcher waits. + * + * **It resolves the pod workspace-scoped, not from the session.** The pod the forward was pinned to + * is exactly the pod that may be gone after a roll, and nothing refreshes it: the forwarder's own + * re-resolution needs an accepted connection, and in this outage the Guest has stopped dialing, so + * no connection ever arrives. Probing the pinned pod would poll a corpse for the whole budget, so + * every poll asks [Collaborators.resolvePod] for the pod that serves the workspace *now*. + * + * Lifecycle mirrors [com.redhat.devtools.gateway.devworkspace.DevWorkspaceSessionWatch]: an explicit + * [start]/[stop] pair and an idempotent start, so the repeated `onRemoteEnd` signals of a flapping + * session never spawn a second loop. + * + * The loop, per iteration (plan §4.2): + * 1. the client is gone -> stop quietly; the Guest window no longer exists, nothing to recover + * 2. a connection older than the confirmation threshold -> recovered, the session is established + * 3. no running+ready pod, or the probe fails -> poll again (cheap list, no prod) + * 4. the workspace pod was replaced -> the cached link is stale: refresh it and prod at once + * 5. the Guest's own seamless reconnection loop is observed first: a dial in flight is awaited (a + * run of failed dials outranks it - overlapping doomed dials never leave a gap), a confirmed one + * is recovery (the frame is preserved); a run of failed dials or a silent redial window means + * that loop cannot recover, and only then is the Guest prodded - a prod restarts the project, + * which the user sees as the window being replaced + * 6. the prod starts an observation window: + * a confirmed dial -> recovered + * a run of failed dials -> the link looks stale, the next attempt refreshes it + * anything else -> next attempt prods again + * + * @param collaborators everything the loop touches, injected so it runs without a cluster. + * @param timing intervals, the budget, and the clock/sleep seams. + */ +@Suppress("TooManyFunctions") // one recovery loop: each step is small and separately testable +internal class ThinClientRecoveryWatcher( + private val collaborators: Collaborators, + private val timing: Timing = Timing() +) { + + /** + * The injected dependencies of the watcher. + * + * @param resolvePod the pod that currently serves the workspace + * ([com.redhat.devtools.gateway.openshift.DevWorkspacePods.findFirstRunning]). + * @param probe opens and closes a real port forward to the IDE port: proves the whole path. + * @param cachedLink the local join link the Guest originally dialed. + * @param sessionPod the pod that link was built against: a different pod means the link is stale. + * @param refreshLink a freshly built local join link, or `null` while none can be built yet. + * @param prod prods the Guest to re-dial [cachedLink]: `updateJoinLink(link, forceReconnect)`. + * @param session the dial outcomes of this session's forward. + * @param isClientPresent whether the Guest window still exists. + * @param onRecovered called once per confirmed recovery; the Guest repaints its status. + * @param onRecoveryFailed called once when the budget is exhausted; never relaunches anything. + */ + @Suppress("LongParameterList") // the watcher's seams: one object instead of a wide constructor + internal class Collaborators( + val resolvePod: () -> V1Pod?, + val probe: suspend (V1Pod) -> Boolean, + val cachedLink: URI, + val sessionPod: V1Pod?, + val refreshLink: suspend () -> URI?, + val prod: suspend (URI) -> Unit, + val session: ForwardDials, + val isClientPresent: () -> Boolean, + val onRecovered: () -> Unit, + val onRecoveryFailed: () -> Unit + ) + + /** + * Intervals, the recovery budget, and the clock/sleep seams. + * + * The seams exist so tests can shrink every interval and drive the clock instead of waiting out + * a ten-minute budget; production uses the defaults. + */ + @Suppress("LongParameterList") // one value per seam, kept together so the loop takes two objects + internal class Timing( + val pollIntervalMs: Long = 5_000, + val longPollIntervalMs: Long = 15_000, + val longPollAfterMs: Long = 120_000, + val redialWaitMs: Long = 10_000, + val budgetMs: Long = 600_000, + val nowNanos: () -> Long = System::nanoTime, + val sleep: suspend (Long) -> Unit = { delay(it) } + ) + + private companion object { + /** Resampling of the in-memory dial outcomes while waiting for the Guest to re-dial. */ + const val OUTCOME_POLL_INTERVAL_MS: Long = 250 + + /** A lone failed dial is not evidence of a stale link; a run of them is. */ + const val FAILED_DIALS_FOR_STALE: Long = 2 + + /** Every nth observation sample is logged (~5 s at the 250 ms poll). */ + const val OBSERVATION_LOG_EVERY_SAMPLES: Int = 20 + + const val MIN_SLEEP_MS: Long = 1 + const val NANOS_PER_MILLI: Long = 1_000_000 + const val MILLIS_PER_SECOND: Long = 1_000 + } + + private val active = AtomicBoolean(false) + private var job: Job? = null + + /** + * Evidence of the session last reported as recovered: the handshake of the connection that + * confirmed it, or the end of the long-lived dial that did. + * + * `onRemoteEnd` fires per connection, so while the Guest's dial churn settles several episodes + * can observe the same established session. Each would otherwise pull the window to the front + * and log again; one recovery per session is enough. + */ + @Volatile + private var lastReportedEvidence: Long? = null + + /** + * Whether the recovery loop is running. Teardown reads it *before* [stop] so a Guest closed + * during recovery withholds the workspace auto-stop (§7.9). + */ + val isActive: Boolean + get() = active.get() + + /** + * Starts the recovery loop, unless one is already running: `onRemoteEnd` fires once per lost + * connection and may fire repeatedly while the session flaps. + */ + fun start(scope: CoroutineScope): Job? { + if (!active.compareAndSet(false, true)) { + return job + } + return scope.launch { recoverUntilStopped() } + .also { job = it } + } + + /** Stops the loop promptly: its next suspension throws, so no further prod is sent. */ + fun stop() { + // who cancelled the loop is not visible from the loop's own death log alone + thisLogger().info("Stopping connection recovery; caller=${callerFrames(javaClass.name)}") + active.set(false) + job?.cancel() + job = null + } + + private suspend fun recoverUntilStopped() { + val episode = Episode(timing.nowNanos()) + try { + while (active.get() && !episode.isFinished && !isBudgetExhausted(episode)) { + if (!collaborators.isClientPresent()) { + stopQuietly(episode, "the JetBrains Client is gone") + break + } + step(episode) + } + if (active.get() && !episode.isFinished) { + reportFailure() + } + } finally { + thisLogger().info( + "Connection recovery loop ended: active=${active.get()}, " + + "finished=${episode.isFinished}, attempts=${episode.attempt}, " + + "budgetExhausted=${isBudgetExhausted(episode)}" + ) + finish() + } + } + + /** + * One loop iteration. Every failure inside it is logged and treated as a failed iteration: the + * watcher keeps polling instead of giving up. Cancellation propagates, so [stop] is prompt. + */ + @Suppress("TooGenericExceptionCaught") // an iteration failure means "retry on the next poll" + private suspend fun step(episode: Episode) { + try { + iterate(episode) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + thisLogger().warn("Connection recovery iteration failed; retrying on the next poll.", e) + waitForNextPoll(episode) + } + } + + @Suppress("ReturnCount") // guard clauses: each early return is one terminal iteration outcome + private suspend fun iterate(episode: Episode) { + if (reportIfConnectionConfirmed(episode)) { + return + } + val pod = collaborators.resolvePod() + if (pod != null) { + detectPodRoll(episode, pod) + } + if (pod == null || !collaborators.probe(pod)) { + waitForNextPoll(episode) + return + } + // Give the Guest's own seamless reconnection loop its chance before prodding: a prod is a + // project-level restart that swaps the window, so it is only worth paying when that loop + // cannot succeed. A dial carrying a stale link is not worth waiting for. + if (!skipsObservation(episode) && observeGuestRecovery(episode) != Observation.PROD) { + return + } + // the attempt and the dial count are committed only once a prod is actually delivered: a + // slow link build (a stale link's status exec can outlast the whole redial window) must not + // consume an attempt number or start the observation window early + val delivery = deliverProd(episode) + if (delivery == null) { + waitForNextPoll(episode) + return + } + when (awaitOutcome(delivery)) { + DialOutcome.RECOVERED -> + reportRecovered(episode, recoveryEvidence(), "a dial confirmed the session") + DialOutcome.STALE -> staleLink(episode) + DialOutcome.NOTHING -> thisLogger().debug( + "No re-dial observed after prodding the Guest; prodding again." + ) + } + } + + /** + * Reports recovery when the Guest holds a connection that outlived [DIAL_CONFIRMATION_MS]. + * + * An open connection alone is not evidence - a stale-link dial is copied for the Guest's own + * transport timeout and then dropped - so only its age confirms a session. + * + * @return whether recovery was reported, ending the episode. + */ + private fun reportIfConnectionConfirmed(episode: Episode): Boolean { + val handshakeNanos = collaborators.session.oldestActiveHandshakeNanos + ?.takeIf { timing.nowNanos() - it >= millisToNanos(DIAL_CONFIRMATION_MS) } + ?: return false + thisLogger().info( + "The Guest's connection on port ${collaborators.cachedLink.port} outlived a stale " + + "dial; the session is established." + ) + reportRecovered(episode, handshakeNanos, "a connection outlived a stale dial") + return true + } + + /** + * Declares the cached link stale when the workspace's pod is no longer the one it was built + * against: a replacement pod is a new idea-server with a new session token, so the link the + * Guest keeps dialing cannot work, however long the Guest's dials are copied. + */ + private fun detectPodRoll(episode: Episode, resolvedPod: V1Pod) { + val sessionPod = collaborators.sessionPod ?: return + if (episode.podRolled || isSamePod(sessionPod, resolvedPod)) { + return + } + episode.podRolled = true + episode.mustRefreshLink = true + thisLogger().info( + "The workspace pod was replaced (session pod ${describePod(sessionPod)}, serving " + + "${describePod(resolvedPod)}); the cached join link is stale and will be refreshed." + ) + } + + /** + * Whether waiting for the Guest's open connection is pointless. + * + * After a pod roll the Guest's current dial still carries the cached link, which the new + * idea-server cannot accept: it can never confirm, so waiting would only delay the fix. Once a + * prod has delivered a refreshed link, the Guest's dials are legitimate again and worth waiting + * for. + */ + /** + * Whether observing the Guest's own reconnection loop is pointless. + * + * After a pod roll the Guest's dials carry the cached link, whose session token the new + * idea-server does not know: they can never confirm, and the frame swap of a prod is inherent + * because the backend session is new. Once a prod has delivered a refreshed link the dials are + * legitimate again and worth observing. + */ + private fun skipsObservation(episode: Episode): Boolean = + episode.podRolled && !episode.sentRefreshedLink + + /** + * Gives the Guest's own seamless reconnection loop the chance to recover before prodding. + * + * A prod is `updateJoinLink(forceReconnect = true)`: the Guest disposes the project and re-opens + * it, which the user sees as the window closing and a new frame opening. Its own loop preserves + * the frame, so it must be allowed to succeed whenever the link is still valid. CRW-13910 live + * testing caught exactly the opposite: a doomed dial ended while a newer seamless dial was + * connecting, the watcher prodded, and the prod cancelled the dial that was about to work. + * + * The observation therefore follows the *dial cycle*, not one dial: + * - a dial in flight (accepted socket or unconfirmed handshake) -> wait for it; + * - it survives the confirmation threshold -> recovered, no prod, frame preserved; + * - it ends before confirming -> count the failed dial and keep observing; + * - a run of failed dials -> the loop runs but cannot succeed (stale link): prod, refreshing + * the link. This outranks a dial in flight: the Guest re-dials before the previous doomed dial + * ends, so waiting for a dial to end would never release while the Guest keeps overlapping + * its dials - only the episode budget would end the wait; + * - no dial activity at all for a redial window -> the Guest gave up: prod the cached link. + * + * It always terminates: the failed-dial run bounds the churn case, the idle window bounds the + * silent case, and the episode budget bounds both. + */ + private suspend fun observeGuestRecovery(episode: Episode): Observation { + val observationStartNanos = timing.nowNanos() + val failedDialsAtStart = collaborators.session.failedDials + var lastActivityNanos = observationStartNanos + var previous = dialSnapshot() + var outcome: Observation? = null + var samples = 0 + + while (outcome == null && active.get()) { + when { + !collaborators.isClientPresent() -> { + stopQuietly(episode, "the JetBrains Client is gone") + outcome = Observation.STOPPED + } + + reportIfConnectionConfirmed(episode) -> outcome = Observation.RECOVERED + + else -> { + val snapshot = dialSnapshot() + if (snapshot != previous) { + previous = snapshot + lastActivityNanos = timing.nowNanos() + } + if (++samples % OBSERVATION_LOG_EVERY_SAMPLES == 0) { + logObservationSample(snapshot, failedDialsAtStart, lastActivityNanos) + } + outcome = decideObservation(episode, snapshot, failedDialsAtStart, lastActivityNanos) + if (outcome == null) { + timing.sleep(OUTCOME_POLL_INTERVAL_MS) + } + } + } + } + return outcome ?: Observation.STOPPED + } + + /** + * States what the silent observation phase currently sees: whether a dial is in flight, what + * the session reports, and how long nothing has changed. Debug only. + */ + private fun logObservationSample( + snapshot: DialSnapshot, + failedDialsAtStart: Long, + lastActivityNanos: Long + ) { + thisLogger().debug( + "Recovery observation: inFlight=${snapshot.isInFlight}, " + + "isClientDialed=${snapshot.isClientDialed}, " + + "oldestActiveHandshake=${snapshot.oldestActiveHandshakeNanos != null}, " + + "failedDials=${snapshot.failedDials} " + + "(delta ${snapshot.failedDials - failedDialsAtStart}), " + + "lastActivityAgeMs=${(timing.nowNanos() - lastActivityNanos) / NANOS_PER_MILLI}" + ) + } + + /** + * The observation's verdict for the current dial state, or `null` to keep observing. + * + * A run of failed dials outranks a dial in flight, because overlapping doomed dials never leave + * a gap: CRW-13910 live measurement saw the Guest's seamless loop re-dial every ~5 s while each + * doomed dial lived ~6.5 s (the Guest's own 6 s transport timeout), so a dial was always in + * flight and waiting for one to end would wait forever. + * + * That is safe because a failed dial is only counted when its forward handshake was delivered + * and the Guest still dropped it within the confirmation threshold + * ([DIAL_CONFIRMATION_MS]); a dial that never handshook - a network cut - is not counted. With a + * working link the RD session establishes and the connection lives for minutes, so two failed + * dials prove every dial carrying the cached link is doomed, including the one in flight. + * Prodding it costs nothing (it dies at its transport timeout anyway) and its end would change + * nothing. + * + * A network cut keeps its protection: its dials never handshake, so `failedDials` stays flat and + * the in-flight guard below holds the prod while the Guest is still trying. Once no dial is in + * flight, plain silence for a redial window means the Guest gave up. + */ + private fun decideObservation( + episode: Episode, + snapshot: DialSnapshot, + failedDialsAtStart: Long, + lastActivityNanos: Long + ): Observation? = when { + snapshot.failedDials - failedDialsAtStart >= FAILED_DIALS_FOR_STALE -> { + staleLink(episode) + Observation.PROD + } + + snapshot.isInFlight -> null + + timing.nowNanos() - lastActivityNanos >= millisToNanos(timing.redialWaitMs) -> + Observation.PROD + + else -> null + } + + /** The dial state the observation samples: a dial is in flight from its socket to its end. */ + private fun dialSnapshot(): DialSnapshot = DialSnapshot( + isClientDialed = collaborators.session.isClientDialed, + oldestActiveHandshakeNanos = collaborators.session.oldestActiveHandshakeNanos, + failedDials = collaborators.session.failedDials + ) + + /** + * Builds the link and sends one prod. + * + * The attempt number counts *delivered* prods only, so the reconnect nonce never skips: a failed + * delivery is retried as the same attempt. + * + * @return when the prod was delivered, the point the observation window starts at: the send + * timestamp and the failed-dial count at that same moment; `null` when nothing was sent. + */ + @Suppress("TooGenericExceptionCaught") // the seams throw whatever the platform throws + private suspend fun deliverProd(episode: Episode): ProdDelivery? { + // null link = nothing may be prodded yet; the cached link is never used as a substitute + val link = prodLinkOrNull(episode) ?: return null + return try { + collaborators.prod(link.uri) + episode.attempt++ + if (link.isRefreshed) { + episode.sentRefreshedLink = true + } + thisLogger().info("Prodded the JetBrains Client to reconnect (attempt ${episode.attempt}).") + ProdDelivery(timing.nowNanos(), collaborators.session.failedDials) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // a dead handle must not crash the watcher: the loop's client-presence check decides + thisLogger().warn("Could not prod the JetBrains Client to reconnect.", e) + null + } + } + + /** [linkFor], with a failing link build treated as "nothing to send yet". */ + @Suppress("TooGenericExceptionCaught") // the seams throw whatever the platform throws + private suspend fun prodLinkOrNull(episode: Episode): ProdLink? = try { + linkFor(episode) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + thisLogger().warn("Could not build a join link to prod the JetBrains Client with.", e) + null + } + + /** + * The link to prod with, or `null` when the Guest must not be prodded yet. + * + * A valid link (the first prod of a non-stale episode) is sent as-is: it costs nothing. A link + * known stale - a replaced pod, or only failed dials - is only ever sent rebuilt: prodding the + * dead one cannot succeed, and every prod makes the Guest dispose and re-open its project + * against a dead session, which burns its project-open retries (CRW-13910 live testing: the + * Guest closed itself after two such prods, exitCode 178). While no fresh link exists yet the + * answer is therefore `null` - no prod, keep polling. + * + * The reconnect nonce is added from the second prod on, where the Guest may already have seen + * the previous link. + */ + private suspend fun linkFor(episode: Episode): ProdLink? { + val attempt = episode.attempt + 1 + val link = if (episode.mustRefreshLink) { + freshLinkOrWait(episode) + } else { + ProdLink(collaborators.cachedLink, isRefreshed = false) + } + return link?.let { ProdLink(withNonceIfNeeded(it.uri, attempt), it.isRefreshed) } + } + + /** + * A rebuilt link, or `null` while the IDE server cannot report one yet. + * + * The wait is logged once per stretch, not on every poll: the watcher keeps calling this until + * the link exists, so a per-call log would flood the one period a live test needs to read. + */ + private suspend fun freshLinkOrWait(episode: Episode): ProdLink? { + val refreshed = collaborators.refreshLink() + if (refreshed != null) { + episode.reportedMissingFreshLink = false + return ProdLink(refreshed, isRefreshed = true) + } + if (!episode.reportedMissingFreshLink) { + episode.reportedMissingFreshLink = true + thisLogger().info( + "The join link is stale and no fresh link is available yet; waiting for the IDE " + + "server to report one." + ) + } + return null + } + + /** Defeats the Guest's same-link no-op guard from the second prod of an episode on. */ + private fun withNonceIfNeeded(link: URI, attempt: Int): URI = + if (attempt == 1) link else ThinClientJoinLink.withReconnectNonce(link, attempt.toLong()) + + /** + * Waits one redial window for the Guest's dials to prove recovery, or to prove the link stale. + * + * The window starts at [ProdDelivery.sentAtNanos] — when the prod was actually delivered — so a + * slow link build (a stale link's status exec) never eats it. + * + * A confirmed dial since the prod means the session came up. A run of failed dials means the + * Guest kept dialing the same dead link. + */ + private suspend fun awaitOutcome(delivery: ProdDelivery): DialOutcome { + val prodAtNanos = delivery.sentAtNanos + val deadlineNanos = prodAtNanos + millisToNanos(timing.redialWaitMs) + while (active.get() && !hasConfirmedDialSince(prodAtNanos) && timing.nowNanos() < deadlineNanos) { + timing.sleep(outcomePollDelay(deadlineNanos)) + } + val failedSinceProd = collaborators.session.failedDials - delivery.failedDialsAtProd + return when { + hasConfirmedDialSince(prodAtNanos) -> DialOutcome.RECOVERED + failedSinceProd >= FAILED_DIALS_FOR_STALE -> DialOutcome.STALE + else -> DialOutcome.NOTHING + } + } + + /** Sleeps at most one poll interval, never past the redial deadline, never zero. */ + private fun outcomePollDelay(deadlineNanos: Long): Long { + val remainingMs = (deadlineNanos - timing.nowNanos()) / NANOS_PER_MILLI + return minOf(OUTCOME_POLL_INTERVAL_MS, maxOf(remainingMs, MIN_SLEEP_MS)) + } + + /** + * Whether a dial confirmed a session since [referenceNanos]: a long-lived dial that ended after + * it, or a connection still open whose handshake has outlived the confirmation threshold. + */ + private fun hasConfirmedDialSince(referenceNanos: Long): Boolean { + val longLivedDialEnded = + collaborators.session.lastLongLivedDialNanos?.let { it > referenceNanos } == true + val oldestHandshakeNanos = collaborators.session.oldestActiveHandshakeNanos + val openConnectionConfirmed = oldestHandshakeNanos != null && + timing.nowNanos() - oldestHandshakeNanos >= millisToNanos(DIAL_CONFIRMATION_MS) + return longLivedDialEnded || openConnectionConfirmed + } + + /** + * The evidence that identifies the session a recovery report refers to: the live connection's + * handshake, or the end of the long-lived dial that proved it. + */ + private fun recoveryEvidence(): Long? = + collaborators.session.oldestActiveHandshakeNanos + ?: collaborators.session.lastLongLivedDialNanos + + private suspend fun waitForNextPoll(episode: Episode) { + timing.sleep(pollIntervalAt(episode)) + } + + /** Cheap polls while the outage is young; a long outage is polled less often. */ + private fun pollIntervalAt(episode: Episode): Long = + if (elapsedMs(episode) < timing.longPollAfterMs) { + timing.pollIntervalMs + } else { + timing.longPollIntervalMs + } + + private fun isBudgetExhausted(episode: Episode): Boolean = + elapsedMs(episode) >= timing.budgetMs + + private fun elapsedMs(episode: Episode): Long = + (timing.nowNanos() - episode.startedAtNanos) / NANOS_PER_MILLI + + private fun millisToNanos(millis: Long): Long = millis * NANOS_PER_MILLI + + /** + * Every dial since the prod ended before it could confirm a session: the pod or the IDE server + * the link points at is gone, so later attempts refresh the link. The flag stays set: the + * refresh is retried until it yields a link, because a stale link must not be prodded forever. + */ + private fun staleLink(episode: Episode) { + episode.mustRefreshLink = true + thisLogger().info( + "Only failed dials since the prod: the join link for port " + + "${collaborators.cachedLink.port} looks stale; refreshing it on the next attempt." + ) + } + + /** + * Reports a recovered session once per confirmed session. + * + * `onRemoteEnd` fires per connection, so several episodes can observe the same established + * session while the Guest's dial churn settles; each would otherwise pull the window to the + * front and log again. + * + * @param evidence the timestamp identifying the confirmed session ([recoveryEvidence]), or + * `null` when it cannot be named; two reports with the same evidence are one recovery. + */ + private fun reportRecovered(episode: Episode, evidence: Long?, reason: String) { + episode.isFinished = true + if (evidence != null && evidence == lastReportedEvidence) { + thisLogger().info("Connection recovery already reported for this session.") + return + } + lastReportedEvidence = evidence + thisLogger().info("Connection recovery succeeded: $reason.") + notify(collaborators.onRecovered, "report the recovered connection") + } + + private fun reportFailure() { + thisLogger().warn( + "Connection recovery failed: the workspace did not come back within " + + "${timing.budgetMs / MILLIS_PER_SECOND} s." + ) + notify(collaborators.onRecoveryFailed, "report the failed recovery") + } + + private fun stopQuietly(episode: Episode, reason: String) { + episode.isFinished = true + thisLogger().info("Stopped connection recovery: $reason.") + } + + /** A callback must never fail the loop: the recovery outcome is already decided by then. */ + private inline fun notify(callback: () -> Unit, action: String) { + runCatching(callback) + .onFailure { e -> thisLogger().warn("Could not $action.", e) } + } + + private fun finish() { + active.set(false) + } + + /** + * Progress of one recovery episode: the delivered prod attempts so far, whether the cached link + * is stale (dials proved it, or the pod was replaced), and whether the episode already ended. + */ + private class Episode(val startedAtNanos: Long) { + var attempt: Int = 0 + var mustRefreshLink: Boolean = false + var podRolled: Boolean = false + + /** Whether a prod has carried a rebuilt link: only then may the Guest's dials be awaited. */ + var sentRefreshedLink: Boolean = false + + /** Whether the "stale but no fresh link yet" wait of this episode has been logged. */ + var reportedMissingFreshLink: Boolean = false + var isFinished: Boolean = false + } + + /** + * What the loop knows once a prod was actually delivered: the start of the observation window + * and the failed-dial count at that moment. Dial outcomes seen before it belong to the previous + * attempt, not to the one being measured. + */ + private class ProdDelivery(val sentAtNanos: Long, val failedDialsAtProd: Long) + + /** + * A link to prod with, and whether it was rebuilt. Only a rebuilt link can unblock a workspace + * whose pod was replaced, which is what re-enables observing the Guest's own dials. + */ + private class ProdLink(val uri: URI, val isRefreshed: Boolean) + + /** + * The Guest's dial state at one sample of the observation. Any change counts as activity, so a + * Guest that is still trying is never mistaken for one that gave up. + */ + private data class DialSnapshot( + val isClientDialed: Boolean, + val oldestActiveHandshakeNanos: Long?, + val failedDials: Long + ) { + /** A dial is open (accepted socket, or a handshake that has not confirmed yet). */ + val isInFlight: Boolean + get() = isClientDialed || oldestActiveHandshakeNanos != null + } + + /** How the pre-prod observation ended. */ + private enum class Observation { + /** A dial confirmed a session: reported as recovered, no prod was sent. */ + RECOVERED, + + /** The Guest's own loop cannot recover: prod. */ + PROD, + + /** The loop was stopped, or the client is gone: no prod, no report. */ + STOPPED + } + + /** What the Guest's dials said after a prod. */ + private enum class DialOutcome { + /** A dial confirmed an established session. */ + RECOVERED, + + /** Only failed dials: the link the Guest was prodded with looks stale. */ + STALE, + + /** No dial at all: prod again (the Guest may have ignored the message). */ + NOTHING + } +} diff --git a/src/main/kotlin/com/redhat/devtools/gateway/openshift/DevWorkspacePods.kt b/src/main/kotlin/com/redhat/devtools/gateway/openshift/DevWorkspacePods.kt index 8d45fe6b..bd85648e 100644 --- a/src/main/kotlin/com/redhat/devtools/gateway/openshift/DevWorkspacePods.kt +++ b/src/main/kotlin/com/redhat/devtools/gateway/openshift/DevWorkspacePods.kt @@ -17,6 +17,7 @@ import io.kubernetes.client.openapi.ApiException import io.kubernetes.client.openapi.apis.CoreV1Api import io.kubernetes.client.openapi.models.V1Pod import io.kubernetes.client.openapi.models.V1PodList +import java.time.OffsetDateTime /** * Queries the Kubernetes API for the pods of a DevWorkspace. @@ -25,6 +26,10 @@ class DevWorkspacePods(private val client: ApiClient) { companion object { const val WORKSPACE_LABEL_KEY = "controller.devfile.io/devworkspace_name" + + private const val POD_PHASE_RUNNING = "Running" + private const val POD_READY_CONDITION = "Ready" + private const val CONDITION_STATUS_TRUE = "True" } /** @@ -46,7 +51,7 @@ class DevWorkspacePods(private val client: ApiClient) { val namespace = pod.metadata?.namespace ?: return false return try { val current = CoreV1Api(client).readNamespacedPod(name, namespace).execute() - current.status?.phase == "Running" && current.metadata?.deletionTimestamp == null + current.status?.phase == POD_PHASE_RUNNING && current.metadata?.deletionTimestamp == null } catch (e: Exception) { if (e.isCancellationException()) throw e false @@ -54,20 +59,37 @@ class DevWorkspacePods(private val client: ApiClient) { } /** - * Returns the first pod matching the given label selector. + * Returns the current usable pod matching the given label selector. + * + * A pod roll leaves several pods of the same DevWorkspace behind for a while: the old pod is + * terminating and the new one is starting. Picking the first list item can therefore pin every + * later operation to the dying pod, which never serves again. Only a pod that is running, has + * passed its readiness probe, and is not terminating can serve; among those the newest one is + * the one the DevWorkspace controller is currently using. + * + * A pod without a creation timestamp is treated as the oldest, so it never shadows a pod with + * a known timestamp. * * @param namespace the namespace to query. * @param labelSelector the Kubernetes label selector, for example * `controller.devfile.io/devworkspace_name=my-workspace`. - * @return the first matching pod, or `null` if no pod matches. + * @return the newest running and ready pod, or `null` if no pod qualifies. * @throws ApiException if the Kubernetes API call fails. */ @Throws(ApiException::class) - fun findFirst(namespace: String, labelSelector: String): V1Pod? { - val pods = list(namespace, labelSelector) - return pods.items.firstOrNull() + fun findFirstRunning(namespace: String, labelSelector: String): V1Pod? { + return list(namespace, labelSelector).items + .filter(::isRunningAndReady) + .maxByOrNull { it.metadata?.creationTimestamp ?: OffsetDateTime.MIN } } + private fun isRunningAndReady(pod: V1Pod): Boolean = + pod.metadata?.deletionTimestamp == null && + pod.status?.phase == POD_PHASE_RUNNING && + pod.status?.conditions.orEmpty().any { condition -> + condition.type == POD_READY_CONDITION && condition.status == CONDITION_STATUS_TRUE + } + /** * Lists the pods matching the given label selector. * diff --git a/src/main/kotlin/com/redhat/devtools/gateway/openshift/ForwardAttempt.kt b/src/main/kotlin/com/redhat/devtools/gateway/openshift/ForwardAttempt.kt index 04d409f8..d296270b 100644 --- a/src/main/kotlin/com/redhat/devtools/gateway/openshift/ForwardAttempt.kt +++ b/src/main/kotlin/com/redhat/devtools/gateway/openshift/ForwardAttempt.kt @@ -19,8 +19,15 @@ import io.kubernetes.client.openapi.models.V1Pod import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.runInterruptible +import kotlinx.coroutines.withTimeout +import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.io.PushbackInputStream @@ -58,11 +65,42 @@ internal sealed interface AttemptResult { data class Ended(val copy: CopyResult) : AttemptResult } +/** + * Upper bound of one port-forward open. + * + * client-java's `PortForward.forward` ends with `WebSocketStreamHandler.waitForInitialized()`, an + * unbounded `Object.wait()` until the port-forward websocket initializes. When that websocket + * stalls - observed right after an idea-server process was killed - the open never returns: the + * dial hangs inside attempt #1, so the retry policy, the client-gone probe and the dial's end are + * all behind a blocked call, and a live `isClientDialed` never clears. Healthy opens take 0.3-0.6 s; + * 10 s bounds the hang with headroom for a slow cluster. + * + * The open is made interruptible ([runInterruptible]): `Object.wait` responds to + * `Thread.interrupt`, so the bound actually frees the thread. Accepted trade-off: an interrupted + * open can leave its half-initialized websocket unclosed, because client-java hands out no handle + * for an open that never completed - a rare, bounded leak instead of an eternal hang. + */ +internal const val OPEN_TIMEOUT_MS: Long = 10_000 + /** * Runs a single forwarding attempt against a pod: opens the port forward, pumps both directions * until one side ends the connection, and closes the streams afterwards. */ -internal class ForwardAttempt(private val client: ApiClient) { +internal class ForwardAttempt( + client: ApiClient, + /** + * Upper bound of one open; see [OPEN_TIMEOUT_MS]. Overridable so tests can exercise the bound + * with a short hang instead of waiting the production timeout out. + */ + private val openTimeoutMs: Long = OPEN_TIMEOUT_MS, + /** + * Opens the tunnel to a pod port. Overridable so a test can block it without mocking + * client-java: the bound works by interrupting the blocked thread, and interrupting a mocked + * call corrupts mockk's global state, which would poison every later test in the class. + */ + private val openForward: (V1Pod, Int) -> PortForward.PortForwardResult = + { pod, remotePort -> PortForward(client).forward(pod, listOf(remotePort)) } +) { companion object { const val COPY_BUFFER_SIZE = 64 * 1024 @@ -70,16 +108,23 @@ internal class ForwardAttempt(private val client: ApiClient) { private val logger = logger() + /** + * [onHandshakeSuccess] is invoked right after [PortForward.forward] succeeds and before the + * streams are copied: it reports "the handshake worked" separately from "the copy ended", + * which the session needs to know when its last successful handshake was. + */ suspend fun attempt( pod: V1Pod, ports: PortMapping, clientSocket: Socket, - clientIn: PushbackInputStream + clientIn: PushbackInputStream, + onHandshakeSuccess: () -> Unit = {} ): AttemptResult { var forwardResult: PortForward.PortForwardResult? = null return try { val opened = openForward(pod, ports) forwardResult = opened + onHandshakeSuccess() AttemptResult.Ended(copyStreams(clientSocket, clientIn, opened, ports.remotePort)) } catch (e: Exception) { if (e.isCancellationException()) throw e @@ -90,12 +135,69 @@ internal class ForwardAttempt(private val client: ApiClient) { } } - private fun openForward(pod: V1Pod, ports: PortMapping): PortForward.PortForwardResult { - val opened = PortForward(client).forward(pod, listOf(ports.remotePort)) + private suspend fun openForward(pod: V1Pod, ports: PortMapping): PortForward.PortForwardResult { + val opened = openForwardTo(pod, ports.remotePort) logger.info("forward successful: ${ports.localPort} -> ${ports.remotePort}...") return opened } + /** + * Opens a forward without copying anything and closes it at once: answers "is the path usable + * right now?" without a client socket or listener. The caller bounds the call; this method just + * classifies the open. + */ + @Suppress("TooGenericExceptionCaught") // any failure to open the tunnel is a failed probe + suspend fun tryOpen(pod: V1Pod, remotePort: Int): Boolean { + var forwardResult: PortForward.PortForwardResult? = null + return try { + forwardResult = openForwardTo(pod, remotePort) + logger.info("Port forward probe succeeded: pod=${pod.metadata?.name}, port=$remotePort") + true + } catch (e: Exception) { + if (e.isCancellationException()) throw e + logger.info( + "Port forward probe failed: pod=${pod.metadata?.name}, port=$remotePort, " + + "cause=${e.javaClass.simpleName}: ${e.message}" + ) + false + } finally { + closeStreams(remotePort, forwardResult) + } + } + + /** + * Opens the forward, bounded to [openTimeoutMs] and interruptible, so a stalled websocket + * initialization cannot pin the dial ([OPEN_TIMEOUT_MS]). + * + * A bound that expires is a *failed handshake*: the connection could not be established, so the + * retry loop may try again. It is not the dial's cancellation, which must keep propagating (the + * session is closing). [runInterruptible] interrupts the blocked thread, which is what makes + * `waitForInitialized` return at all. + */ + private suspend fun openForwardTo(pod: V1Pod, remotePort: Int): PortForward.PortForwardResult = + try { + withTimeout(openTimeoutMs) { + runInterruptible(Dispatchers.IO) { + openForward(pod, remotePort) + } + } + } catch (e: TimeoutCancellationException) { + throw openFailure(e, "timed out after $openTimeoutMs ms") + } catch (e: InterruptedException) { + throw openFailure(e, "was interrupted before the stream initialized") + } + + /** + * Classifies a failed bounded open. The dial being cancelled is not a failure of the attempt and + * keeps propagating; anything else is a retryable [IOException]. + */ + private suspend fun openFailure(cause: Exception, reason: String): Exception = + if (currentCoroutineContext().isActive) { + IOException("Port forward open $reason", cause) + } else { + CancellationException("Port forward open cancelled") + } + private suspend fun copyStreams( clientSocket: Socket, clientIn: PushbackInputStream, diff --git a/src/main/kotlin/com/redhat/devtools/gateway/openshift/ForwardRetryPolicy.kt b/src/main/kotlin/com/redhat/devtools/gateway/openshift/ForwardRetryPolicy.kt index 25443d83..52656818 100644 --- a/src/main/kotlin/com/redhat/devtools/gateway/openshift/ForwardRetryPolicy.kt +++ b/src/main/kotlin/com/redhat/devtools/gateway/openshift/ForwardRetryPolicy.kt @@ -22,19 +22,59 @@ internal data class PortMapping(val localPort: Int, val remotePort: Int) /** Why a failed handshake is or is not retried. */ internal enum class RetryDecision { RETRY, + + /** + * The pod the failed attempt used is gone. Terminal for the policy: whether a forward may + * continue anyway (against the pod that replaced it) is the forwarder's decision, because only + * the forwarder can retarget its session. + */ POD_GONE, BUDGET_EXHAUSTED, ATTEMPTS_EXHAUSTED } +/** + * A failed handshake: which attempt failed, when the series of failures started, and why this one + * failed. + * + * The values only make sense together and always travel as a unit, which keeps + * [ForwardRetryPolicy.decide] within the parameter budget of the code style. + */ +internal data class FailedHandshake( + /** 1-based number of the attempt that just failed. */ + val attempt: Int, + /** + * Clock reading ([ForwardRetryPolicy]'s `nowNanos`) of the first failure of this series; the + * retry budgets start here. + */ + val firstFailureNanos: Long, + /** What the handshake attempt failed with. */ + val cause: Throwable +) + /** * Decides whether a failed port-forward handshake may be retried. * + * The behaviour is split by session phase, because the two phases have opposite requirements: + * connect-time must fail fast (the wizard is waiting and a broken workspace must surface at once), + * while an established session must outlive a transient outage (VPN drop, sleep) without the Guest + * ever noticing. [established] selects the phase; [PodPortForwarder] reads it from the session. + * * The budget starts at the first failed handshake, not at socket accept, so a slow handshake does * not consume the whole budget. The decision is logged here because the log line explains the * [RetryDecision] and both must stay in sync. + * + * The policy judges the pod an attempt used: [RetryDecision.POD_GONE] means that pod is gone, not + * that the forward is over. When the workspace still has a running pod, [PodPortForwarder] + * retargets to it and retries; with no replacement the forward ends, which is the connect-time + * "pod is gone" behaviour. */ internal class ForwardRetryPolicy( + /** + * Reads the clock the budgets are measured against. Overridable so a test can put a series + * past a budget without waiting for it. + */ + private val nowNanos: () -> Long = System::nanoTime, /** Returns pod liveness state to decide whether a failed forward may be retried. */ private val livenessProvider: suspend (V1Pod) -> PodLiveness ) { @@ -44,7 +84,29 @@ internal class ForwardRetryPolicy( // so the 2s retry budget stops the loop after the 3rd attempt — a higher cap could never be reached. const val CONNECT_ATTEMPTS = 3 const val RECONNECT_DELAY_MS: Long = 1000 + + /** + * Safety cap against a stuck socket, not the healing window: retries run only while the + * Guest keeps re-dialing, so the Guest's own dial window bounds recovery from above. + * + * Measured from the first failure of the connection and preserved across pod retargets, so + * a cluster that keeps replacing the pod cannot restart the wall on every replacement. + */ + const val STEADY_STATE_OUTAGE_BUDGET_MS: Long = 10 * 60 * 1000L + const val STEADY_STATE_MAX_DELAY_MS: Long = 5000 + private const val RETRY_BUDGET_MS = 2_000L + + /** Backoff of an established session: heals short blips without hammering the API server. */ + private val STEADY_STATE_BACKOFF_MS = longArrayOf( + RECONNECT_DELAY_MS, + 2 * RECONNECT_DELAY_MS, + 3 * RECONNECT_DELAY_MS, + STEADY_STATE_MAX_DELAY_MS + ) + + private const val CONNECT_PHASE = "connect-time" + private const val STEADY_STATE_PHASE = "steady-state" } private val logger = logger() @@ -54,52 +116,94 @@ internal class ForwardRetryPolicy( */ suspend fun decide( pod: V1Pod, - firstFailureNanos: Long, - attempt: Int, ports: PortMapping, - cause: Throwable + established: Boolean, + failure: FailedHandshake ): RetryDecision { val liveness = livenessProvider(pod) - val retry = when { - liveness == PodLiveness.GONE -> - RetryDecision.POD_GONE - attempt >= CONNECT_ATTEMPTS -> - RetryDecision.ATTEMPTS_EXHAUSTED - System.nanoTime() - firstFailureNanos >= RETRY_BUDGET_MS * NANOS_PER_MILLI -> - RetryDecision.BUDGET_EXHAUSTED - else -> - RetryDecision.RETRY - } - logFailure(retry, liveness, attempt, ports, cause) + val retry = evaluate(liveness, established, failure) + logFailure(retry, liveness, ports, established, failure) return retry } + /** + * Delay before the next attempt in the given phase: connect-time keeps [RECONNECT_DELAY_MS], + * an established session backs off from 1s to [STEADY_STATE_MAX_DELAY_MS]. + */ + fun reconnectDelayMs(attempt: Int, established: Boolean): Long { + require(attempt >= 1) { "attempt is 1-based, was $attempt" } + if (!established) return RECONNECT_DELAY_MS + val index = minOf(attempt, STEADY_STATE_BACKOFF_MS.size) - 1 + return STEADY_STATE_BACKOFF_MS[index] + } + + private fun evaluate( + liveness: PodLiveness, + established: Boolean, + failure: FailedHandshake + ): RetryDecision = when { + // a gone pod serves no retry in either phase + liveness == PodLiveness.GONE -> RetryDecision.POD_GONE + // an established session has no attempt limit: only its outage budget ends the retries + established -> if (isElapsed(failure.firstFailureNanos, STEADY_STATE_OUTAGE_BUDGET_MS)) { + RetryDecision.BUDGET_EXHAUSTED + } else { + RetryDecision.RETRY + } + failure.attempt >= CONNECT_ATTEMPTS -> RetryDecision.ATTEMPTS_EXHAUSTED + isElapsed(failure.firstFailureNanos, RETRY_BUDGET_MS) -> RetryDecision.BUDGET_EXHAUSTED + else -> RetryDecision.RETRY + } + + private fun isElapsed(firstFailureNanos: Long, budgetMs: Long): Boolean = + nowNanos() - firstFailureNanos >= budgetMs * NANOS_PER_MILLI + private fun logFailure( retry: RetryDecision, liveness: PodLiveness, - attempt: Int, ports: PortMapping, - cause: Throwable + established: Boolean, + failure: FailedHandshake ) { val (localPort, remotePort) = ports + // both phases share this method, so the phase must be in every line: operators have to + // tell "wizard fails fast" from "session outlived an outage" in the same log + val phase = if (established) STEADY_STATE_PHASE else CONNECT_PHASE + val context = "phase=$phase, podLiveness=$liveness" + val cause = failure.cause + val lastCause = "${cause.javaClass.simpleName}: ${cause.message}" when (retry) { RetryDecision.RETRY -> logger.info( - "Port forward handshake $localPort -> $remotePort failed on attempt $attempt: ${cause.message} " + - "(podLiveness=$liveness); retrying in ${RECONNECT_DELAY_MS}ms" + "Port forward handshake $localPort -> $remotePort failed on attempt ${failure.attempt}: " + + "${cause.message} ($context); retrying in " + + "${reconnectDelayMs(failure.attempt, established)}ms" ) RetryDecision.POD_GONE -> logger.info( - "Port forward handshake $localPort -> $remotePort failed on attempt $attempt: ${cause.message} " + - "(podLiveness=$liveness); not retrying" + "Port forward handshake $localPort -> $remotePort failed on attempt ${failure.attempt}: " + + "${cause.message} ($context); the pod is gone" + ) + RetryDecision.ATTEMPTS_EXHAUSTED -> + logger.warn( + "Port forward $localPort -> $remotePort failed after ${failure.attempt} attempt(s) " + + "($context, lastCause=$lastCause); giving up", + cause ) - else -> + RetryDecision.BUDGET_EXHAUSTED -> logger.warn( - "Port forward $localPort -> $remotePort failed after $attempt attempt(s) " + - "(podLiveness=$liveness, " + - "lastCause=${cause.javaClass.simpleName}: ${cause.message}); giving up", + "Port forward $localPort -> $remotePort failed after ${failure.attempt} attempt(s) " + + "($context, lastCause=$lastCause); giving up: " + + "${budgetName(established)} exhausted", cause ) } } + + private fun budgetName(established: Boolean): String = + if (established) { + "steady-state outage budget (${STEADY_STATE_OUTAGE_BUDGET_MS}ms)" + } else { + "connect-time retry budget (${RETRY_BUDGET_MS}ms)" + } } diff --git a/src/main/kotlin/com/redhat/devtools/gateway/openshift/PodPortForwarder.kt b/src/main/kotlin/com/redhat/devtools/gateway/openshift/PodPortForwarder.kt index 2512ac67..733068e0 100644 --- a/src/main/kotlin/com/redhat/devtools/gateway/openshift/PodPortForwarder.kt +++ b/src/main/kotlin/com/redhat/devtools/gateway/openshift/PodPortForwarder.kt @@ -13,16 +13,21 @@ package com.redhat.devtools.gateway.openshift import com.intellij.openapi.diagnostic.logger import com.redhat.devtools.gateway.util.isCancellationException +import io.kubernetes.client.PortForward import io.kubernetes.client.openapi.ApiClient import io.kubernetes.client.openapi.models.V1Pod import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import java.io.Closeable import java.io.IOException import java.io.PushbackInputStream @@ -31,32 +36,267 @@ import java.net.ServerSocket import java.net.Socket import java.net.SocketTimeoutException import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong private const val NANOS_PER_MILLI = 1_000_000L +/** + * How long a dial must survive to count as an established RD session. + * + * A dial against a stale link is dropped by the Guest's own transport-creation timeout (6 s) — + * measured 6.5–6.9 s in CRW-13910 live testing — while a real session lives for minutes. 15 s is + * more than twice the failed-dial lifetime. + */ +internal const val DIAL_CONFIRMATION_MS: Long = 15_000 + +/** + * Phase state of one forward session, shared by the session handle ([PortForwardSession]) and the + * per-connection retry loops. + * + * The phase is carried by the session, not by the policy: the same [ForwardRetryPolicy] must fail + * fast while the wizard waits for the Guest (connect-time) and keep retrying once the Guest is up. + * + * The dial outcomes are recorded for the recovery watcher. They are deliberately about *survival*, + * not about bytes flowing: a stale-link dial is copied for seconds before the Guest drops it, so + * neither "a connection is being copied" nor "the last dial lasted a while" proves an RD session. + * Only a dial that outlived [confirmationMs] does. + */ +internal class SessionPhase( + /** + * How long a dial must survive to count as an established session. Overridable so tests can + * exercise both sides of the threshold with short real dials. + */ + private val confirmationMs: Long = DIAL_CONFIRMATION_MS +) { + private val established = AtomicBoolean(false) + private val failedDialCount = AtomicLong(0) + + /** + * Accepted client sockets that have not ended yet, so a dial is visible from the moment the + * Guest's TCP connection arrives - before its forward handshake has completed. + */ + private val clientDials = AtomicInteger(0) + + /** + * Handshakes of the connections currently being copied, with a count per timestamp. + * + * Keyed by [System.nanoTime] of the handshake rather than by connection, because the phase only + * ever sees that timestamp. A count keeps two connections that handshook in the same nanosecond + * distinct: removing one must not hide the other, or the watcher could lose the oldest pending + * handshake and prod a session that is still establishing. + */ + private val activeHandshakes = ConcurrentHashMap() + + @Volatile + private var lastHandshakeNanos: Long? = null + + @Volatile + private var lastFailedNanos: Long? = null + + @Volatile + private var lastLongLivedNanos: Long? = null + + /** Whether the Guest came up for this session; false until [markEstablished]. */ + val isEstablished: Boolean + get() = established.get() + + /** + * Whether the Guest has a dial open right now: an accepted client socket, handshake or not. + * + * The pre-handshake phase matters to the recovery watcher: a dial connecting through the + * forwarder is not "the Guest gave up", even though it has no handshake to report yet. + */ + val isClientDialed: Boolean + get() = clientDials.get() > 0 + + /** + * Whether at least one connection whose handshake succeeded is still being copied. + * + * Not recovery evidence: see the class KDoc. The watcher corroborates with + * [oldestActiveHandshakeNanos]. + */ + val hasActiveForward: Boolean + get() = activeHandshakes.isNotEmpty() + + /** [System.nanoTime] of the last successful handshake, or null when none succeeded yet. */ + val lastSuccessfulHandshakeNanos: Long? + get() = lastHandshakeNanos + + /** + * The earliest handshake among the connections still being copied, or null when none is. + * + * This is how a connection that has not ended yet can still confirm: a handshake this old has + * survived longer than [confirmationMs], so it is an established session rather than a dial the + * Guest is about to drop. + */ + val oldestActiveHandshakeNanos: Long? + get() = activeHandshakes.keys.minOrNull() + + /** [System.nanoTime] when the last failed dial ended; see [DIAL_CONFIRMATION_MS]. */ + val lastFailedDialNanos: Long? + get() = lastFailedNanos + + /** [System.nanoTime] when the last long-lived dial ended; see [DIAL_CONFIRMATION_MS]. */ + val lastLongLivedDialNanos: Long? + get() = lastLongLivedNanos + + /** + * Monotone count of failed dials since the forward started. The watcher compares it with the + * count it saw at its last prod: the timestamp alone cannot tell several dials apart when more + * than one ends between two samples. + */ + val failedDials: Long + get() = failedDialCount.get() + + /** Idempotent: the phase only ever moves from connect-time to steady-state. */ + fun markEstablished() { + established.set(true) + } + + /** Records *when* the handshake succeeded: the caller keeps the same value per connection. */ + fun recordSuccessfulHandshake(atNanos: Long) { + lastHandshakeNanos = atNanos + } + + /** A client socket was accepted: a dial exists from now on, handshake pending. */ + fun recordClientDial() { + clientDials.incrementAndGet() + } + + /** The dial the accepted socket belonged to is over: handshook or not. */ + fun recordClientDialEnded() { + // clamped: a connection coroutine cancelled before it started has no finally, while the + // listener close below resets the count, so a late end must not make it negative + clientDials.updateAndGet { count -> (count - 1).coerceAtLeast(0) } + } + + /** The session's listener is closed: no dial can be in flight any more. */ + fun clearClientDials() { + clientDials.set(0) + } + + /** A connection's handshake succeeded, so it is being copied from [handshakeNanos] on. */ + fun recordActiveForward(handshakeNanos: Long) { + activeHandshakes.merge(handshakeNanos, 1, Int::plus) + } + + /** + * A connection ended. [handshakeNanos] is the handshake of *this* connection: `null` when it + * never handshook, in which case it never counted as an active forward and is not classified. + * + * The classification is about survival: a dial that ended within [confirmationMs] of its + * handshake failed (the Guest dropped the stale-link dial), a later one was a real session the + * server ended. + */ + fun recordEndedForward(handshakeNanos: Long?) { + if (handshakeNanos == null) { + return + } + activeHandshakes.computeIfPresent(handshakeNanos) { _, count -> + (count - 1).takeIf { it > 0 } + } + val endNanos = System.nanoTime() + if (endNanos - handshakeNanos < confirmationMs * NANOS_PER_MILLI) { + failedDialCount.incrementAndGet() + lastFailedNanos = endNanos + } else { + lastLongLivedNanos = endNanos + } + } +} + +/** + * The Guest's dial outcomes on one forward session, as the recovery watcher observes them. + * + * Narrower than [PortForwardSession], and deliberately so: it exposes only facts that can confirm a + * session or prove a link stale. "A connection is being copied" is not one of them - a stale-link + * dial is copied for seconds before the Guest drops it - so the watcher cannot mistake it for + * recovery. + */ +internal interface ForwardDials { + /** + * Whether the Guest has a dial open right now: an accepted client socket, handshake or not. + * + * A dial is not evidence of a session; it is evidence that the Guest has not given up, and that + * prodding now would cut a reconnection the Guest's own loop is attempting. + */ + val isClientDialed: Boolean + + /** + * The earliest handshake among the connections still being copied, or null when none is. A + * handshake older than [DIAL_CONFIRMATION_MS] confirms an established RD session. + */ + val oldestActiveHandshakeNanos: Long? + + /** [System.nanoTime] when the last long-lived dial ended, or null when none lasted long. */ + val lastLongLivedDialNanos: Long? + + /** Monotone count of failed dials; the watcher compares it across a prod. */ + val failedDials: Long +} + /** * A running port forward session. * * [localPort] is the loopback port the session listens on, so the forward describes itself and * callers do not have to carry the port alongside the session. [close] stops the listener and * closes the established connections, so the client reads EOF at once. The listener must not - * outlive the forward: the pod is pinned when the forward is created, so a re-dial could only - * reach that same pod. + * outlive the session it bridges: closing it is what keeps a re-dial away from a stopped + * workspace. The forward itself may retarget to the pod that replaced the one it was opened + * against, so a re-dial reaches whichever pod currently serves the workspace. */ internal class PortForwardSession( val localPort: Int, + /** + * Shared with the retry loops; defaults to a fresh one so a caller that only needs the handle + * (tests, fakes) does not have to carry it. + */ + private val phase: SessionPhase = SessionPhase(), private val stopForward: () -> Unit -) : Closeable { +) : ForwardDials, Closeable { + /** Whether the Guest is up for this session; see [SessionPhase.isEstablished]. */ + val isEstablished: Boolean + get() = phase.isEstablished + + /** [System.nanoTime] of the last successful handshake; see [SessionPhase]. */ + val lastSuccessfulHandshakeNanos: Long? + get() = phase.lastSuccessfulHandshakeNanos + + /** Whether a connection whose handshake succeeded is still being copied; see [SessionPhase]. */ + val hasActiveForward: Boolean + get() = phase.hasActiveForward + + override val isClientDialed: Boolean + get() = phase.isClientDialed + + /** [System.nanoTime] when the last failed dial ended; see [SessionPhase]. */ + val lastFailedDialNanos: Long? + get() = phase.lastFailedDialNanos + + override val oldestActiveHandshakeNanos: Long? + get() = phase.oldestActiveHandshakeNanos + + override val lastLongLivedDialNanos: Long? + get() = phase.lastLongLivedDialNanos + + override val failedDials: Long + get() = phase.failedDials + + /** Switches retries to the steady-state policy; call once the Guest is up. Idempotent. */ + fun markEstablished() = phase.markEstablished() + override fun close() = stopForward() } /** - * Opens a loopback port forward to a port on a pod. + * Opens port forwards to a pod. * - * The seam exists so connection lifecycle code can be exercised without a cluster: - * production wires [PodPortForwarder], tests supply a fake session. + * The seam exists so connection lifecycle and recovery code can be exercised without a cluster: + * production wires [PodPortForwarder], tests supply a fake. */ -internal fun interface PortForwarder { +internal interface PortForwarder { /** * Starts a forward to [remotePort] on a free loopback port the forwarder picks and binds * itself, so port allocation cannot race between "find a free port" and "listen on it". @@ -68,20 +308,126 @@ internal fun interface PortForwarder { */ @Throws(IOException::class) fun forward(pod: V1Pod, remotePort: Int, onRemoteEnd: () -> Unit): PortForwardSession + + /** + * Starts a forward that follows the pod which currently serves the workspace. + * + * When a handshake fails because [pod] is gone, [resolvePod] may name the pod that replaced it, + * and the forward retargets to that pod instead of ending. A resolver that returns `null` or + * the pod the failed attempt already used keeps the "pod gone" outcome terminal, so a + * forwarder that cannot resolve anything behaves exactly like [forward] with a pinned pod. + * + * @param resolvePod resolves the workspace's current running and ready pod; it may block on + * the API server and is therefore called only from the retry loop, never on the caller's + * thread. + * @param onRemoteEnd see [forward]. + */ + @Throws(IOException::class) + fun forward( + pod: V1Pod, + remotePort: Int, + resolvePod: () -> V1Pod?, + onRemoteEnd: () -> Unit + ): PortForwardSession = forward(pod, remotePort, onRemoteEnd) + + /** + * Answers "can a port forward to [remotePort] on [pod] be established right now?". + * + * Opens a real forward and closes it at once: no local listener, no client socket. It proves + * the whole path (auth, API server, pod, listener), which a pod liveness query cannot. Bounded: + * a hanging open counts as `false`, because a hanging API server cannot serve the Guest either. + */ + suspend fun probe(pod: V1Pod, remotePort: Int): Boolean } /** - * Mutable state of one running forward: the pod and ports it bridges, the local sockets currently - * bridged to it, and the notification for a connection the pod side ended. + * Mutable state of one running forward: the pod it bridges, the local sockets currently bridged to + * it, the session phase shared with the retry loops, and the notification for a connection the pod + * side ended. + * + * The pod is retargetable: when the workspace's pod is replaced while the DevWorkspace stays + * Running (eviction, drain, OOM kill), the retry loop swaps in the replacement instead of ending a + * session that could recover. Concurrent connections of one session may each see the old pod gone + * and resolve a replacement, so the swap is idempotent. */ private class ForwardState( - val pod: V1Pod, + pod: V1Pod, + /** Resolves the pod that currently serves the workspace; see [PortForwarder.forward]. */ + val resolvePod: () -> V1Pod?, val localPort: Int, val remotePort: Int, + /** Survival a dial needs to count as an established session; see [SessionPhase]. */ + confirmationMs: Long, val onRemoteEnd: () -> Unit ) { + /** + * Guards [currentPod] for the swap. A plain lock, not a `Mutex`: the critical section is an + * in-memory reference swap and never suspends, so it cannot hold up a dispatcher thread, and + * the suspend retry loop reads the pod through [pod] outside the lock. + */ + private val podLock = Any() + + private var currentPod: V1Pod = pod + val ports = PortMapping(localPort, remotePort) val clientSockets: MutableSet = ConcurrentHashMap.newKeySet() + val phase = SessionPhase(confirmationMs) + + /** The pod this forward currently targets. */ + val pod: V1Pod + get() = synchronized(podLock) { currentPod } + + /** + * Retargets the forward to [replacement]. + * + * Idempotent: a connection that resolved the pod another connection already swapped in gets + * `null` instead of a second swap, so concurrent re-dials never thrash between replacements. + * + * @return the pod the forward targeted before the swap, or `null` when it already targeted + * [replacement]. + */ + fun retarget(replacement: V1Pod): V1Pod? = synchronized(podLock) { + if (isSamePod(currentPod, replacement)) { + return@synchronized null + } + val previous = currentPod + currentPod = replacement + previous + } +} + +/** + * Whether two pod references name the same pod. + * + * The UID is a pod's identity: a replaced pod keeps the name during a roll, so a name comparison + * alone would hide the replacement and keep the forward pinned to a dead pod. The namespace/name + * pair is the fallback for a pod without a UID (a synthetic pod in a test). + * + * Shared with the recovery watcher: the forwarder retargets on a pod roll and the watcher declares + * the cached link stale on one, so both must agree on what "the same pod" means. One rule only. + */ +internal fun isSamePod(first: V1Pod, second: V1Pod): Boolean { + val firstUid = first.metadata?.uid + val secondUid = second.metadata?.uid + if (firstUid != null && secondUid != null) { + return firstUid == secondUid + } + return first.metadata?.namespace == second.metadata?.namespace && + first.metadata?.name == second.metadata?.name +} + +/** Identifies a pod in log lines: the name alone cannot tell two generations of a pod apart. */ +internal fun describePod(pod: V1Pod): String = + "name=${pod.metadata?.name}, uid=${pod.metadata?.uid}" + +/** + * Dial state of one accepted connection. + * + * At most one handshake can succeed for a connection: a successful handshake moves the attempt into + * copying, which closes the connection when it returns, so the retry loop starts no further attempt. + */ +private class DialState { + var handshakeNanos: Long? = null } /** @@ -89,10 +435,45 @@ private class ForwardState( * retrying failed handshakes while the pod is alive and the local client stays connected. * * The listener lifecycle lives here; one attempt is a [ForwardAttempt] and whether a failed - * attempt may be retried is decided by [ForwardRetryPolicy]. + * attempt may be retried is decided by [ForwardRetryPolicy]. A pod that is replaced while the + * DevWorkspace stays Running does not end the session: the forward retargets to the pod that + * replaced it, so a re-dial reaches whatever pod currently serves the workspace. */ +@Suppress("TooManyFunctions", "LongParameterList") // one cohesive unit; the extra params are seams internal class PodPortForwarder( client: ApiClient, + /** + * Upper bound of [probe]; a hanging open counts as a failed probe. + * Overridable so tests can exercise the bound with a short delay. + */ + private val probeTimeoutMs: Long = PROBE_TIMEOUT_MS, + /** + * Resolves the pod that currently serves the workspace, used when the pod a forward was opened + * against is gone. Defaults to no resolution, so a forwarder that was not told how to find the + * workspace's current pod keeps its pinned pod and "pod gone" stays terminal. + */ + private val resolvePod: () -> V1Pod? = { null }, + /** + * Reads the clock the retry decisions use: the outage budget is measured against it. + * Overridable so a test can put the first failure of a series into the past. + */ + private val nowNanos: () -> Long = System::nanoTime, + /** + * Survival a dial needs to count as an established RD session; see [DIAL_CONFIRMATION_MS]. + * Overridable so tests can exercise both sides of the threshold with short real dials. + */ + private val confirmationMs: Long = DIAL_CONFIRMATION_MS, + /** + * Upper bound of one port-forward open; see [OPEN_TIMEOUT_MS]. Overridable so tests can + * exercise a hung open with a short bound instead of waiting the production timeout out. + */ + private val openTimeoutMs: Long = OPEN_TIMEOUT_MS, + /** + * Opens a pod port forward; see [ForwardAttempt.openForward]. Overridable so a test can block + * an open without mocking client-java - the bound interrupts the blocked thread. + */ + private val openForward: (V1Pod, Int) -> PortForward.PortForwardResult = + { pod, remotePort -> PortForward(client).forward(pod, listOf(remotePort)) }, /** * Returns pod liveness state to decide whether a failed forward may be retried. * Overridable in tests because [PodLiveness] is module-internal. @@ -103,15 +484,32 @@ internal class PodPortForwarder( companion object { private const val CLIENT_GONE_PROBE_TIMEOUT_MS = 100 private const val LISTEN_BACKLOG = 50 + + /** OkHttp's default 10s is too slow to poll with; see the plan's probe timeout constant. */ + const val PROBE_TIMEOUT_MS: Long = 3_000 } private val logger = logger() - private val forwardAttempt = ForwardAttempt(client) - private val retryPolicy = ForwardRetryPolicy(livenessProvider) + private val forwardAttempt = ForwardAttempt(client, openTimeoutMs, openForward) + private val retryPolicy = ForwardRetryPolicy(nowNanos, livenessProvider) + + override fun forward( + pod: V1Pod, + remotePort: Int, + onRemoteEnd: () -> Unit + ): PortForwardSession = openSession(pod, remotePort, resolvePod, onRemoteEnd) override fun forward( pod: V1Pod, remotePort: Int, + resolvePod: () -> V1Pod?, + onRemoteEnd: () -> Unit + ): PortForwardSession = openSession(pod, remotePort, resolvePod, onRemoteEnd) + + private fun openSession( + pod: V1Pod, + remotePort: Int, + resolvePod: () -> V1Pod?, onRemoteEnd: () -> Unit ): PortForwardSession { val serverSocket = ServerSocket(0, LISTEN_BACKLOG, InetAddress.getLoopbackAddress()) @@ -119,15 +517,42 @@ internal class PodPortForwarder( // dont cancel if child coroutine fails + use dedicated port-forward dispatcher SupervisorJob() + PortForwardDispatcher.dispatcher ) - val state = ForwardState(pod, serverSocket.localPort, remotePort, onRemoteEnd) + val state = ForwardState( + pod, + resolvePod, + serverSocket.localPort, + remotePort, + confirmationMs, + onRemoteEnd + ) scope.acceptConnections(serverSocket, state) - return PortForwardSession(state.localPort) { + return PortForwardSession(state.localPort, state.phase) { closeQuietly(serverSocket) scope.cancel() closeClientSockets(state) } } + /** + * Opens a real forward to [remotePort] on [pod] and closes it at once, bounded to + * [probeTimeoutMs]. No listener and no client socket: the caller only learns whether the path + * is usable right now. + * + * The open runs in a scope that is not a child of the caller (the [PodLivenessProbe.query] + * pattern), so the bound can return `false` without joining the blocking + * `PortForward.forward` call, which may keep running in the background. A timeout counts as + * `false`: a hanging API server cannot serve the Guest either. + */ + override suspend fun probe(pod: V1Pod, remotePort: Int): Boolean { + val scope = CoroutineScope(Dispatchers.IO + Job()) + val open = scope.async { forwardAttempt.tryOpen(pod, remotePort) } + return try { + withTimeoutOrNull(probeTimeoutMs) { open.await() } ?: false + } finally { + scope.cancel() + } + } + /** * Closes every socket accepted so far so the connected clients read EOF. * @@ -135,8 +560,12 @@ internal class PodPortForwarder( * coroutine cancellation. Closing the sockets is what makes the client notice the loss. */ private fun closeClientSockets(state: ForwardState) { - val sockets = state.clientSockets.toList() + // no size-optimised toList(): a connection can end concurrently and empty the set between + // its size check and its single-element read, which throws NoSuchElementException + val sockets = mutableListOf() + state.clientSockets.forEach { socket -> sockets += socket } state.clientSockets.clear() + state.phase.clearClientDials() if (sockets.isNotEmpty()) { logger.info( "Closing ${sockets.size} client connection(s) of port forward " + @@ -158,6 +587,8 @@ internal class PodPortForwarder( val clientSocket = createClientSocket(serverSocket) ?: break clientSocket.tcpNoDelay = true state.clientSockets.add(clientSocket) + // visible to the recovery watcher from the first byte: the handshake may take a while + state.phase.recordClientDial() launch { handleConnection(clientSocket, state) @@ -181,8 +612,9 @@ internal class PodPortForwarder( private suspend fun CoroutineScope.handleConnection(clientSocket: Socket, state: ForwardState) { val acceptedAtNanos = System.nanoTime() + val dial = DialState() try { - forwardWithRetries(clientSocket, state, acceptedAtNanos) + forwardWithRetries(clientSocket, state, acceptedAtNanos, dial) } catch (e: Exception) { if (e.isCancellationException()) throw e logger.warn( @@ -190,6 +622,10 @@ internal class PodPortForwarder( "using port ${state.localPort} -> ${state.remotePort}", e) } finally { + // this connection is over, whether it was copied, failed or was cancelled: a connection + // that never handshook passes null and must not decrement the active-forward counter + state.phase.recordEndedForward(dial.handshakeNanos) + state.phase.recordClientDialEnded() state.clientSockets.remove(clientSocket) closeQuietly(clientSocket) } @@ -198,61 +634,174 @@ internal class PodPortForwarder( private suspend fun CoroutineScope.forwardWithRetries( clientSocket: Socket, state: ForwardState, - acceptedAtNanos: Long + acceptedAtNanos: Long, + dial: DialState ) { // wraps the client input so the client-gone probe can push back the byte it has to read (see isClientGone) val clientIn = PushbackInputStream(clientSocket.getInputStream(), 1) var firstFailureNanos: Long? = null - for (attempt in 1..ForwardRetryPolicy.CONNECT_ATTEMPTS) { - if (!isActive) return + var attempt = 1 + var keepRetrying = true + // connect-time is capped by the policy; an established session keeps retrying until its + // outage budget or the client gives up, so the loop itself has no attempt limit + while (isActive && keepRetrying) { + // one read per iteration: a concurrent connection may retarget the forward between the + // attempt and the decision, and the decision must judge the pod this attempt used + val pod = state.pod logger.info("Attempt #$attempt: Connecting ${state.localPort} -> ${state.remotePort}...") - val isTerminal = - when (val result = forwardAttempt.attempt(state.pod, state.ports, clientSocket, clientIn)) { - // the copy already closed the local socket: any outcome is terminal - is AttemptResult.Ended -> { - logCopyEnd(result.copy, state.localPort, state.remotePort, acceptedAtNanos) - // a client-side failure is not a client-initiated close: on a messy pod death - // the client pump often fails first, and the Guest still has to report the loss - if (!result.copy.isClosedByClient) { - state.onRemoteEnd() - } - true + val result = forwardAttempt.attempt(pod, state.ports, clientSocket, clientIn) { + onHandshakeSucceeded(state.phase, dial) + } + keepRetrying = when (result) { + // the copy already closed the local socket: any outcome is terminal + is AttemptResult.Ended -> { + logCopyEnd(result.copy, state.localPort, state.remotePort, acceptedAtNanos) + // a client-side failure is not a client-initiated close: on a messy pod death + // the client pump often fails first, and the Guest still has to report the loss + if (!result.copy.isClosedByClient) { + state.onRemoteEnd() } + false + } - is AttemptResult.HandshakeFailed -> { - val failureStartedAt = firstFailureNanos ?: System.nanoTime() - firstFailureNanos = failureStartedAt - retryPolicy.decide( - state.pod, - failureStartedAt, - attempt, - state.ports, - result.cause - ) != RetryDecision.RETRY + is AttemptResult.HandshakeFailed -> { + firstFailureNanos = firstFailureNanos ?: nowNanos() + val failure = FailedHandshake(attempt, firstFailureNanos, result.cause) + val established = state.phase.isEstablished + val retry = retryPolicy.decide(pod, state.ports, established, failure) + when { + retry == RetryDecision.POD_GONE && retarget(state, pod) -> { + // the replacement restarts the attempt (delay) series: the dead pod's + // failure must not shorten it. In steady state it does NOT restart the + // outage budget, which is the safety cap against a stuck socket and + // keeps running from this connection's first failure across any number + // of retargets - otherwise repeated pod churn would defeat the cap. + // Connect-time resets it too: there the window is attempt-capped and + // the dead pod's failure time must not shorten the replacement's 2s. + attempt = 0 + firstFailureNanos = seriesStartAfterRetarget(firstFailureNanos, established) + true + } + + retry != RetryDecision.RETRY -> false + + clientLeftDuringRetry(clientSocket, clientIn, attempt, established) -> { + logger.info( + "Port forward handshake ${state.localPort} -> ${state.remotePort}: " + + "client disconnected; stopping retries" + ) + false + } + + else -> true } } - if (isTerminal) break - if (clientLeftDuringRetry(clientSocket, clientIn)) { - logger.info( - "Port forward handshake ${state.localPort} -> ${state.remotePort}: " + - "client disconnected; stopping retries" - ) - return } + attempt++ + } + } + + /** + * The start of the retry series after a retarget. + * + * Connect-time restarts the series completely: its 2 s window is attempt-capped anyway, and the + * dead pod's failure time must not shorten the replacement's window. An established session + * keeps its original first failure, so the outage budget - the safety cap against a stuck + * socket - keeps running across any number of pod replacements instead of restarting on each. + */ + private fun seriesStartAfterRetarget(firstFailureNanos: Long?, established: Boolean): Long? = + if (established) firstFailureNanos else null + + /** + * The policy says the pod this attempt used is gone: follow the pod that currently serves the + * workspace instead of ending the forward. + * + * A replacement only counts when it is a *different* pod than [attemptedPod]. The resolver + * answers "which pod serves the workspace now", so while the failed pod is still the only one + * running it names exactly that pod, and retargeting to it would only loop. + * + * [ForwardState.resolvePod] lists pods on the API server, so it runs outside the state lock. + * Concurrent connections of one session may each resolve the replacement; the swap is + * idempotent, so a candidate another connection already swapped in is recognized as the + * current pod and no connection swaps twice for the same roll. A failed resolution counts as + * "no replacement known" and ends the forward, like a `null` answer. + * + * @return whether the loop should retry, now against the replacement. + */ + private fun retarget(state: ForwardState, attemptedPod: V1Pod): Boolean { + val replacement = resolveReplacement(state) + if (replacement == null || isSamePod(attemptedPod, replacement)) { + logger.info( + "Port forward ${state.localPort} -> ${state.remotePort}: pod " + + "${describePod(attemptedPod)} is gone and no replacement serves the " + + "workspace; stopping" + ) + return false + } + logRetarget(state, state.retarget(replacement), replacement) + return true + } + + /** + * Logs what the swap did: a `null` [previous] means another connection of the session already + * swapped this pod in, so this connection only joins it instead of swapping again. + */ + private fun logRetarget(state: ForwardState, previous: V1Pod?, replacement: V1Pod) { + val forward = "${state.localPort} -> ${state.remotePort}" + if (previous == null) { + logger.info( + "Port forward $forward: a concurrent connection already retargeted to pod " + + "${describePod(replacement)}; retrying" + ) + } else { + logger.info( + "Port forward $forward: retargeting from pod ${describePod(previous)} to pod " + + "${describePod(replacement)}; retrying immediately" + ) + } + } + + @Suppress("TooGenericExceptionCaught") // a failed pod list only means "no replacement known" + private fun resolveReplacement(state: ForwardState): V1Pod? = try { + state.resolvePod() + } catch (e: Exception) { + if (e.isCancellationException()) throw e + logger.info( + "Port forward ${state.localPort} -> ${state.remotePort}: could not resolve a " + + "replacement pod (${e.javaClass.simpleName}: ${e.message}); not retrying" + ) + null + } + + /** + * Records a successful handshake with its own timestamp: the session keeps the latest one for + * the recovery watcher, while [dial] keeps *this* connection's, so the failed/long-lived + * classification when the connection ends uses this connection's lifetime only. + */ + private fun onHandshakeSucceeded(phase: SessionPhase, dial: DialState) { + if (dial.handshakeNanos != null) { + return // already counted: one handshake per accepted connection } + val handshakeNanos = System.nanoTime() + dial.handshakeNanos = handshakeNanos + phase.recordSuccessfulHandshake(handshakeNanos) + phase.recordActiveForward(handshakeNanos) } /** - * Waits the reconnect delay, checking the client before and after it: a client that already left - * will not come back, so waiting the whole delay for it is pointless. + * Waits the policy's reconnect delay for [attempt] in the current session phase, checking the + * client before and after it: a client that already left will not come back, so waiting the + * whole delay for it is pointless. */ private suspend fun clientLeftDuringRetry( clientSocket: Socket, - clientIn: PushbackInputStream + clientIn: PushbackInputStream, + attempt: Int, + established: Boolean ): Boolean { if (isClientGone(clientSocket, clientIn)) return true @Suppress("ConvertLongToDuration") - delay(ForwardRetryPolicy.RECONNECT_DELAY_MS) + delay(retryPolicy.reconnectDelayMs(attempt, established)) return isClientGone(clientSocket, clientIn) } diff --git a/src/main/kotlin/com/redhat/devtools/gateway/server/RemoteIDEServer.kt b/src/main/kotlin/com/redhat/devtools/gateway/server/RemoteIDEServer.kt index 57664cf7..24cf4cd8 100644 --- a/src/main/kotlin/com/redhat/devtools/gateway/server/RemoteIDEServer.kt +++ b/src/main/kotlin/com/redhat/devtools/gateway/server/RemoteIDEServer.kt @@ -42,8 +42,30 @@ class RemoteIDEServer( private val devSpacesContext: DevSpacesContext, private val workspace: DevWorkspace = devSpacesContext.devWorkspace ) { - var pod: V1Pod - private var container: V1Container + /** + * The pod that serves the workspace and the IDE container inside it, as one unit. + * + * A pod roll replaces both together: a container refreshed on its own could survive onto a new + * pod and make an exec land in the previous pod's container. + */ + private data class Target(val pod: V1Pod, val container: V1Container) + + /** Guards the swap in [refreshPod]; readers see a whole [Target] through the volatile field. */ + private val targetLock = Any() + + @Volatile + private var target: Target = resolveTarget() + + /** The pod that currently serves the workspace. Retargeting swaps it together with its container. */ + val pod: V1Pod + get() = target.pod + + /** + * Name of the IDE container inside [pod]. Exposed to prove the pod/container pairing: a + * container name from the previous pod must never be used with a new pod. + */ + internal val ideContainerName: String + get() = target.container.name companion object { /** Overall wait for remote IDE readiness (wizard "Checking workspace IDE Status..."). */ @@ -59,11 +81,6 @@ class RemoteIDEServer( const val TERMINATED_TIMEOUT: Long = 10 // seconds } - init { - pod = findPod() - container = findContainer() - } - /** * Asks the CDE for the remote IDE server status. */ @@ -71,9 +88,11 @@ class RemoteIDEServer( suspend fun getStatus(checkCancelled: (() -> Unit)? = null): RemoteIDEServerStatus = withContext(Dispatchers.IO) { checkCancelled?.invoke() - if (!DevWorkspacePods(devSpacesContext.client).isPodRunning(pod)) { + // one snapshot: the pod and the container must belong to the same generation + val current = target + if (!DevWorkspacePods(devSpacesContext.client).isPodRunning(current.pod)) { thisLogger().info( - "Pod '${pod.metadata?.name}' is not running; " + + "Pod '${current.pod.metadata?.name}' is not running; " + "returning empty status." ) return@withContext RemoteIDEServerStatus.empty() @@ -81,8 +100,8 @@ class RemoteIDEServer( checkCancelled?.invoke() val output = PodExecSession( client = devSpacesContext.client, - pod = pod, - container = container.name, + pod = current.pod, + container = current.container.name, command = arrayOf( // remote-dev-server.sh writes to several sub-folders of HOME (.config, .cache, etc.) // When registry.access.redhat.com/ubi9 is used for running a user container, @@ -143,22 +162,57 @@ class RemoteIDEServer( ): Boolean { return RemoteIDEServerReadiness( targetDescription = { - "IDE server on pod '${pod.metadata?.name}' container '${container.name}'" + val current = target + "IDE server on pod '${current.pod.metadata?.name}' " + + "container '${current.container.name}'" }, isReady = { cancelled -> getStatus(cancelled).isReady }, - refresh = { - pod = findPod() - container = findContainer() - }, + refresh = { refreshPod() }, ).waitFor(isReadyState, timeout, checkCancelled) } + /** + * Re-resolves the workspace's current running and ready pod and swaps it in together with its + * IDE container, so a later status exec can never land in the previous pod's container. + * + * @return whether a pod was found. When the workspace has no running, ready pod right now the + * previous target is kept, and the next readiness probe reports it as not running. + * @throws ServerContainerNotFoundException if the running pod has no idea-server container: + * that is terminal, not a transient state to poll through (CRW-11897). + */ + @Throws(ServerContainerNotFoundException::class) + fun refreshPod(): Boolean { + val refreshed = resolveTargetOrNull() ?: run { + thisLogger().info( + "No running, ready pod for DevWorkspace '${workspace.name}'; keeping the current target." + ) + return false + } + synchronized(targetLock) { target = refreshed } + thisLogger().info( + "IDE server target refreshed: pod '${refreshed.pod.metadata?.name}' " + + "container '${refreshed.container.name}'." + ) + return true + } + + /** + * Resolves the pod that currently serves the workspace. + * + * Deliberately selects a running, ready pod instead of the first list item: during a pod roll + * the first item can be the terminating pod, which would pin every status exec and + * port-forward to a pod that no longer serves. While the pod is running but not yet ready, the + * constructor throws; [RemoteIDEServerReadiness] and the caller's retry loop re-resolve the pod + * on the next poll. + * + * @throws IOException if no pod of the workspace is running and ready. + */ @Throws(IOException::class) private fun findPod(): V1Pod { val selector = "controller.devfile.io/devworkspace_name=${workspace.name}" return DevWorkspacePods(devSpacesContext.client) - .findFirst( + .findFirstRunning( workspace.namespace, selector ) ?: throw IOException( @@ -167,9 +221,28 @@ class RemoteIDEServer( } @Throws(IOException::class) - private fun findContainer(): V1Container { + private fun resolveTarget(): Target { + val pod = findPod() + return Target(pod, findIdeContainer(pod)) + } + + /** Like [resolveTarget], but `null` when the workspace has no running, ready pod. */ + private fun resolveTargetOrNull(): Target? { + val pod = try { + findPod() + } catch (e: IOException) { + thisLogger().debug("Pod lookup failed while refreshing the IDE server target.", e) + return null + } + return Target(pod, findIdeContainer(pod)) + } + + @Throws(ServerContainerNotFoundException::class) + private fun findIdeContainer(pod: V1Pod): V1Container { return pod.spec!!.containers.find { container -> - container.ports?.any { port -> port.name == "idea-server" } != null + // a container without the idea-server port is not the IDE container; `orEmpty` keeps + // a container whose ports are unset from matching on "has a ports list" + container.ports.orEmpty().any { port -> port.name == "idea-server" } } ?: throw ServerContainerNotFoundException( "Workspace IDE container not found in the Pod: ${pod.metadata?.name}" diff --git a/src/main/kotlin/com/redhat/devtools/gateway/util/ExceptionUtils.kt b/src/main/kotlin/com/redhat/devtools/gateway/util/ExceptionUtils.kt index 329caf8b..72da8fe8 100644 --- a/src/main/kotlin/com/redhat/devtools/gateway/util/ExceptionUtils.kt +++ b/src/main/kotlin/com/redhat/devtools/gateway/util/ExceptionUtils.kt @@ -26,6 +26,26 @@ fun Throwable.isTimeoutException(): Boolean = (this is TimeoutCancellationExcept fun Throwable.isCancellationException(): Boolean = (this is CancellationException && !isTimeoutException() ) +/** Frames a compact caller stack shows: enough to name the trigger, not a stack dump. */ +private const val CALLER_FRAMES = 4 + +/** + * The current call stack as compact `Class.method` frames, for log lines that must attribute an + * action - a cancel, a teardown - without dumping a full stack trace. + * + * Frames of [ownClassName] are skipped, so the first entry is the code that called into it. + */ +fun callerFrames(ownClassName: String): String = + // only the trace is used here; the message just avoids a bare default-constructed exception. + // The first frame is this function; the frames of [ownClassName] are the code being logged. + Exception("caller frames").stackTrace + .drop(1) + .dropWhile { it.className == ownClassName } + .take(CALLER_FRAMES) + .joinToString(" <- ") { frame -> + "${frame.className.substringAfterLast('.')}.${frame.methodName}" + } + /** * Returns true if this throwable or any of its causes is a `ServerContainerNotFoundException`. * Traverses the exception chain to determine if the root cause is a missing server container. diff --git a/src/test/kotlin/com/redhat/devtools/gateway/ThinClientJoinLinkTest.kt b/src/test/kotlin/com/redhat/devtools/gateway/ThinClientJoinLinkTest.kt new file mode 100644 index 00000000..6c938a1a --- /dev/null +++ b/src/test/kotlin/com/redhat/devtools/gateway/ThinClientJoinLinkTest.kt @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2024-2026 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package com.redhat.devtools.gateway + +import com.redhat.devtools.gateway.util.fragmentParameters +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import java.net.URI + +class ThinClientJoinLinkTest { + + private val joinLink = URI("tcp://127.0.0.1:5990#jt=token&p=IU") + + private val localPort = 41_234 + + @Test + fun `toLocal swaps only the IDE server port`() { + // when + val local = ThinClientJoinLink.toLocal(joinLink, localPort) + + // then - everything but the port is preserved, byte for byte + assertThat(local.toString()).isEqualTo("tcp://127.0.0.1:$localPort#jt=token&p=IU") + assertThat(local.scheme).isEqualTo(joinLink.scheme) + assertThat(local.host).isEqualTo(joinLink.host) + assertThat(local.port).isEqualTo(localPort) + assertThat(local.fragmentParameters()).isEqualTo(joinLink.fragmentParameters()) + } + + @Test + fun `toLocal preserves the query`() { + // given + val withQuery = URI("tcp://127.0.0.1:5990?context=abc#jt=token") + + // when + val local = ThinClientJoinLink.toLocal(withQuery, localPort) + + // then + assertThat(local.rawQuery).isEqualTo(withQuery.rawQuery) + assertThat(local.port).isEqualTo(localPort) + } + + @Test + fun `toLocal fails fast when the link does not address the IDE server port`() { + // when + val thrown = assertThrows { + ThinClientJoinLink.toLocal(URI("tcp://127.0.0.1:8080#jt=token"), localPort) + } + + // then - a malformed link must not silently forward the Guest to the wrong port + assertThat(thrown.message).contains(ThinClientJoinLink.REMOTE_IDE_PORT.toString()) + } + + @Test + fun `toLocal fails fast when the link has no port`() { + val thrown = assertThrows { + ThinClientJoinLink.toLocal(URI("tcp://127.0.0.1#jt=token"), localPort) + } + + assertThat(thrown.message).contains(ThinClientJoinLink.REMOTE_IDE_PORT.toString()) + } + + @Test + fun `withReconnectNonce makes the link distinct from the original and from another nonce`() { + // when + val first = ThinClientJoinLink.withReconnectNonce(joinLink, 1L) + val second = ThinClientJoinLink.withReconnectNonce(joinLink, 2L) + + // then - each prod sends a different link, so the Guest's same-link guard does not fire + assertThat(first).isNotEqualTo(joinLink) + assertThat(second).isNotEqualTo(first) + assertThat(first.fragmentParameters()) + .containsEntry(ThinClientJoinLink.RECONNECT_PARAMETER, "1") + assertThat(second.fragmentParameters()) + .containsEntry(ThinClientJoinLink.RECONNECT_PARAMETER, "2") + } + + @Test + fun `withReconnectNonce preserves existing fragment parameters`() { + // when + val nonced = ThinClientJoinLink.withReconnectNonce(joinLink, 7L) + + // then - the Guest merges fragment parameters, so the original ones must survive + assertThat(nonced.fragmentParameters()).isEqualTo( + mapOf( + "jt" to "token", + "p" to "IU", + ThinClientJoinLink.RECONNECT_PARAMETER to "7" + ) + ) + } + + @Test + fun `withReconnectNonce replaces an existing nonce instead of appending it`() { + // given + val nonced = ThinClientJoinLink.withReconnectNonce(joinLink, 7L) + + // when + val reNonced = ThinClientJoinLink.withReconnectNonce(nonced, 8L) + + // then + assertThat(reNonced.fragmentParameters()).hasSize(3) + assertThat(reNonced.fragmentParameters()) + .containsEntry(ThinClientJoinLink.RECONNECT_PARAMETER, "8") + } + + @Test + fun `toLocal after withReconnectNonce keeps the nonce`() { + // when - the recovery watcher builds a prod link from a nonced join link + val nonced = ThinClientJoinLink.withReconnectNonce(joinLink, 42L) + val local = ThinClientJoinLink.toLocal(nonced, localPort) + + // then + assertThat(local.port).isEqualTo(localPort) + assertThat(local.fragmentParameters()) + .containsEntry(ThinClientJoinLink.RECONNECT_PARAMETER, "42") + assertThat(local.fragmentParameters()).containsEntry("jt", "token") + } +} diff --git a/src/test/kotlin/com/redhat/devtools/gateway/ThinClientRecoveryWatcherTest.kt b/src/test/kotlin/com/redhat/devtools/gateway/ThinClientRecoveryWatcherTest.kt new file mode 100644 index 00000000..32cac13a --- /dev/null +++ b/src/test/kotlin/com/redhat/devtools/gateway/ThinClientRecoveryWatcherTest.kt @@ -0,0 +1,760 @@ +/* + * Copyright (c) 2026 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package com.redhat.devtools.gateway + +import com.redhat.devtools.gateway.openshift.DIAL_CONFIRMATION_MS +import com.redhat.devtools.gateway.openshift.ForwardDials +import io.kubernetes.client.openapi.models.V1ObjectMeta +import io.kubernetes.client.openapi.models.V1Pod +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import java.io.IOException +import java.net.URI + +/** Poll interval of the virtual clock; production uses 5s and 15s. */ +private const val POLL_MS = 1_000L + +private const val LONG_POLL_MS = 3_000L +private const val LONG_POLL_AFTER_MS = 4_000L +private const val REDIAL_WAIT_MS = 2_000L + +/** Larger than [DIAL_CONFIRMATION_MS], so an episode can wait a connection out and still reach it. */ +private const val BUDGET_MS = 60_000L + +private const val RUN_TIMEOUT_MS = 20_000L + +/** When the Guest answers a prod: one dial outcome, well inside the redial window. */ +private const val DIAL_AFTER_MS = 300L + +private const val NONCE_PARAMETER = ThinClientJoinLink.RECONNECT_PARAMETER + +private val CACHED_LINK: URI = URI("tcp://127.0.0.1:41000#cb=123&p=1") +private val REFRESHED_LINK: URI = URI("tcp://127.0.0.1:41000#cb=123&p=2") + +private fun pod(name: String, uid: String): V1Pod = V1Pod().apply { + metadata = V1ObjectMeta().apply { + this.name = name + this.uid = uid + } +} + +private val OLD_POD = pod("luke-skywalker-roll-old", "764b6480-old-uid") +private val NEW_POD = pod("luke-skywalker-roll-new", "7a011c35-new-uid") + +/** + * Behaviour of the recovery loop. + * + * Every dependency is a fake and the clock is virtual: each sleep advances it and then suspends for + * a millisecond, so the loop terminates deterministically, `stop()` still cancels it promptly, and + * the suite never waits out a real interval or touches a cluster. + * + * The dial outcomes are scripted as *scheduled* events: the Guest answers a prod (or drops a doomed + * dial) a moment later, which is what the watcher's observation windows must see. + */ +class ThinClientRecoveryWatcherTest { + + private val harness = Harness() + + // --- polling ------------------------------------------------------------ + + @Test + fun `does not prod while the probe fails and keeps polling`() { + harness.probeSucceeds = false + + harness.runWatcher() + + assertThat(harness.prods).isEmpty() + assertThat(harness.probedPods.size).isGreaterThan(1) + assertThat(harness.failed).isEqualTo(1) // the budget, not a crash, ended the loop + } + + @Test + fun `does not probe or prod without a running pod and fails once the budget is spent`() { + harness.pod = null + + harness.runWatcher() + + assertThat(harness.resolvedPods).isGreaterThan(1) + assertThat(harness.probedPods).isEmpty() + assertThat(harness.prods).isEmpty() + assertThat(harness.failed).isEqualTo(1) + } + + @Test + fun `polls less often once the outage lasts`() { + harness.pod = null + + harness.runWatcher() + + // one poll per second would be 60 list calls; the long-outage interval keeps it far below + assertThat(harness.resolvedPods).isGreaterThan(10) + assertThat(harness.resolvedPods).isLessThan(30) + } + + // --- prods -------------------------------------------------------------- + + @Test + fun `prods once with the cached link`() { + harness.stopAfterProds = 1 + + harness.runWatcher() + + assertThat(harness.prods).containsExactly(CACHED_LINK) + assertThat(harness.recovered).isZero() + assertThat(harness.failed).isZero() + } + + @Test + fun `prods again with a different link when the Guest ignored the first prod`() { + harness.stopAfterProds = 2 + + harness.runWatcher() + + assertThat(harness.prods).hasSize(2) + assertThat(harness.prods[0]).isEqualTo(CACHED_LINK) + assertThat(harness.prods[1]).isNotEqualTo(harness.prods[0]) + // nothing stale: the cached link plus the reconnect nonce defeats the no-op guard, and the + // costly status exec of a link refresh is not paid + assertThat(harness.refreshes).isZero() + assertThat(harness.prods[1].rawFragment).contains("$NONCE_PARAMETER=2") + assertThat(harness.prods[1].rawFragment).contains("p=1") + } + + // --- confirmation-based recovery evidence ------------------------------- + + @Test + fun `waits for an open connection to confirm instead of prodding it`() { + // the Guest dialed and the connection is being copied, but it has not outlived a stale dial + harness.openDial() + + harness.runWatcher() + + assertThat(harness.prods).isEmpty() + assertThat(harness.recovered).isEqualTo(1) + assertThat(harness.failed).isZero() + } + + @Test + fun `does not treat an open connection as recovery before it confirms`() { + // the connection ends before the confirmation threshold, like a stale-link dial + harness.openDial(atNanos = 0) + harness.scheduleFailedDialEnd(handshakeNanos = 0, afterMs = DIAL_CONFIRMATION_MS / 2) + harness.stopAfterProds = 1 + + harness.runWatcher() + + assertThat(harness.recovered).isZero() + assertThat(harness.prods).hasSize(1) // it was a doomed dial: prod + } + + /** + * The CRW-13910 live failure: the Guest's doomed dial died while its next seamless attempt was + * already connecting. Prodding there cancelled the dial that was about to work and restarted + * the project, which the user saw as the window being replaced. + */ + @Test + fun `does not prod while a newer dial is in flight when the doomed dial dies`() { + harness.openDial(atNanos = 0) // dial H, opened while the network was down + harness.scheduleDialHandshake(afterMs = 4_000) // the next seamless attempt, about to work + harness.scheduleFailedDialEnd(handshakeNanos = 0, afterMs = 6_000) // dial H's timeout + + harness.runWatcher() + + assertThat(harness.prods).isEmpty() // the attempt in flight was not cut + assertThat(harness.recovered).isEqualTo(1) + assertThat(harness.failed).isZero() + } + + /** + * The CRW-13910 in-place idea-server restart, from the live capture: the Guest's seamless loop + * re-dialed every ~5 s while each doomed dial lived ~6.5 s (its own 6 s transport timeout), so a + * dial was in flight at every sample. Waiting for one to end never terminates; a run of failed + * dials must outrank it. + */ + @Test + fun `prods while a doomed dial is in flight when the Guest redials before the previous one dies`() { + harness.refreshedLink = REFRESHED_LINK + harness.stopAfterProds = 1 + harness.scheduleDoomedDial(handshakeAtMs = 0, lifetimeMs = 6_500) + harness.scheduleDoomedDial(handshakeAtMs = 5_000, lifetimeMs = 6_500) + harness.scheduleDoomedDial(handshakeAtMs = 10_000, lifetimeMs = 6_500) // still open at the prod + + harness.runWatcher() + + // stale rules applied from the first prod: overlapping failed dials proved the link stale + assertThat(harness.prods).hasSize(1) + assertThat(harness.prods[0].rawFragment).contains("p=2") + assertThat(harness.refreshes).isEqualTo(1) + // dial 3 opened at 10 s and only dies at 16.5 s: the prod fired with it still open, as soon + // as dials 1 and 2 had both failed. Waiting for the dial to end would postpone it to 16.5 s + // at best and forever while the Guest keeps overlapping dials. + assertThat(harness.firstProdAtMs).isGreaterThanOrEqualTo(11_000) + assertThat(harness.firstProdAtMs).isLessThan(16_500) + } + + @Test + fun `waits for a dial that is connecting before its handshake`() { + // an accepted socket with no handshake yet: the Guest is dialing, not gone + harness.acceptConnectingDial() + harness.scheduleDialHandshake(afterMs = REDIAL_WAIT_MS + 1_000) + + harness.runWatcher() + + assertThat(harness.prods).isEmpty() + assertThat(harness.recovered).isEqualTo(1) + } + + @Test + fun `prods the refreshed link when the Guest's own loop keeps failing`() { + harness.refreshedLink = REFRESHED_LINK + harness.stopAfterProds = 1 + harness.scheduleFailedDials(afterMs = DIAL_AFTER_MS, count = 2) + + harness.runWatcher() + + // the seamless loop is running but cannot succeed: stale rules apply, so the very first + // prod carries a fresh link + assertThat(harness.prods).hasSize(1) + assertThat(harness.refreshes).isEqualTo(1) + assertThat(harness.prods[0].rawFragment).contains("p=2") + } + + @Test + fun `prods only after the Guest stops dialing`() { + harness.stopAfterProds = 1 + + harness.runWatcher() + + assertThat(harness.prods).containsExactly(CACHED_LINK) + // the Guest gave up: no socket, no handshake, no failed dial for a redial window + assertThat(harness.firstProdAtMs).isGreaterThanOrEqualTo(REDIAL_WAIT_MS) + assertThat(harness.refreshes).isZero() + } + + @Test + fun `reports recovery when a long-lived dial followed the prod`() { + harness.onProd = { harness.scheduleLongLivedDial(DIAL_AFTER_MS) } + + harness.runWatcher() + + assertThat(harness.recovered).isEqualTo(1) + assertThat(harness.failed).isZero() + assertThat(harness.prods).hasSize(1) + assertThat(harness.isWatcherActive).isFalse() + } + + // --- stale link by dial evidence ---------------------------------------- + + @Test + fun `refreshes the link after two failed dials since the prod`() { + harness.refreshedLink = REFRESHED_LINK + harness.stopAfterProds = 2 + harness.onProd = { harness.scheduleFailedDials(DIAL_AFTER_MS, count = 2) } + + harness.runWatcher() + + assertThat(harness.prods).hasSize(2) + assertThat(harness.refreshes).isEqualTo(1) + assertThat(harness.prods[1].rawFragment).contains("p=2") + assertThat(harness.prods[1].rawFragment).contains("$NONCE_PARAMETER=2") + } + + @Test + fun `does not refresh the link for a single failed dial`() { + harness.stopAfterProds = 2 + harness.onProd = { harness.scheduleFailedDials(DIAL_AFTER_MS, count = 1) } + + harness.runWatcher() + + assertThat(harness.refreshes).isZero() + assertThat(harness.prods[1].rawFragment).contains("p=1") + assertThat(harness.prods[1].rawFragment).contains("$NONCE_PARAMETER=2") + } + + @Test + fun `survives client-closed failed dials and refreshes the stale link`() { + // the live failure (CRW-13910): dials the Guest closes itself fire no onRemoteEnd, so the + // episode must not depend on those signals to keep running and reach the stale-link path + harness.refreshedLink = REFRESHED_LINK + harness.openDial(atNanos = 0) // a doomed dial is open right now + harness.scheduleFailedDialEnd(handshakeNanos = 0, afterMs = DIAL_CONFIRMATION_MS / 2) + harness.onProd = { harness.scheduleFailedDials(DIAL_AFTER_MS, count = 2) } + harness.stopAfterProds = 2 + + harness.runWatcher() + + assertThat(harness.recovered).isZero() + assertThat(harness.prods).hasSize(2) + assertThat(harness.refreshes).isEqualTo(1) + assertThat(harness.prods[1].rawFragment).contains("p=2") + } + + // --- stale link by pod identity ---------------------------------------- + + @Test + fun `a replaced pod is stale even while a doomed connection is open`() { + harness.sessionPod = OLD_POD + harness.pod = NEW_POD + harness.refreshedLink = REFRESHED_LINK + harness.openDial() + harness.stopAfterProds = 1 + + harness.runWatcher() + + // an open, unconfirmed dial is not recovery, and the stale link can only be fixed by a + // fresh one: the very first prod carries it + assertThat(harness.recovered).isZero() + assertThat(harness.refreshes).isEqualTo(1) + assertThat(harness.prods).hasSize(1) + assertThat(harness.prods[0].rawFragment).contains("p=2") + } + + @Test + fun `reports recovery after a replaced pod only when a dial confirms`() { + harness.sessionPod = OLD_POD + harness.pod = NEW_POD + harness.refreshedLink = REFRESHED_LINK + harness.onProd = { harness.openDial() } + + harness.runWatcher() + + assertThat(harness.prods).hasSize(1) + assertThat(harness.prods[0].rawFragment).contains("p=2") + assertThat(harness.recovered).isEqualTo(1) + } + + @Test + fun `never prods the cached link after a pod roll while no fresh link exists`() { + // the live failure (CRW-13910, idea-server restart in place): the link is known stale and + // the replacement server does not report a link yet, so prodding could only burn the + // Guest's project-open retries - the Guest closed itself after two such prods + harness.sessionPod = OLD_POD + harness.pod = NEW_POD + harness.refreshedLink = null + + harness.runWatcher() + + assertThat(harness.prods).isEmpty() + assertThat(harness.refreshes).isGreaterThan(1) // kept asking for a fresh link + assertThat(harness.failed).isEqualTo(1) // the budget, exactly once + } + + @Test + fun `never prods a stale link proven by failed dials while no fresh link exists`() { + harness.refreshedLink = null + harness.onProd = {} + harness.scheduleFailedDials(afterMs = DIAL_AFTER_MS, count = 2) + + harness.runWatcher() + + assertThat(harness.prods).isEmpty() + assertThat(harness.prods).doesNotContain(CACHED_LINK) + assertThat(harness.refreshes).isGreaterThan(1) + assertThat(harness.failed).isEqualTo(1) + } + + @Test + fun `prods the fresh link as soon as the IDE server reports one`() { + harness.sessionPod = OLD_POD + harness.pod = NEW_POD + harness.refreshedLink = REFRESHED_LINK + // the new server needs a few polls before it can report a link + harness.refreshLinkResult = { call -> if (call <= 3) null else REFRESHED_LINK } + harness.stopAfterProds = 2 + + harness.runWatcher() + + // the cached link was never sent; the first delivered prod already carries the fresh one + assertThat(harness.prods).hasSize(2) + assertThat(harness.prods[0].rawFragment).contains("p=2") + assertThat(harness.prods[0].rawFragment).doesNotContain(NONCE_PARAMETER) + assertThat(harness.prods[1].rawFragment).contains("$NONCE_PARAMETER=2") + assertThat(harness.refreshes).isGreaterThan(3) // the null stretch plus one rebuild per prod + } + + @Test + fun `does not treat the same pod after a roll check as a roll`() { + harness.sessionPod = OLD_POD + harness.pod = OLD_POD + harness.refreshedLink = REFRESHED_LINK + harness.stopAfterProds = 1 + + harness.runWatcher() + + assertThat(harness.refreshes).isZero() + assertThat(harness.prods).containsExactly(CACHED_LINK) + } + + // --- episode lifecycle -------------------------------------------------- + + @Test + fun `reports recovery without a prod when the already established session is confirmed`() { + harness.openDial(atNanos = 0) + + harness.runWatcher() + + assertThat(harness.recovered).isEqualTo(1) + assertThat(harness.prods).isEmpty() + } + + @Test + fun `stops quietly when the JetBrains Client is gone`() { + harness.clientPresent = false + + harness.runWatcher() + + assertThat(harness.recovered).isZero() + assertThat(harness.failed).isZero() + assertThat(harness.resolvedPods).isZero() + } + + @Test + fun `reports failure exactly once when the budget is spent`() { + harness.pod = null + + harness.runWatcher() + + assertThat(harness.failed).isEqualTo(1) + } + + @Test + fun `repeated starts spawn a single loop`() { + harness.stopAfterProds = 2 + + harness.runWatcher(startTimes = 3) + + // one iteration per prod: a second concurrent loop would resolve and prod twice as often + assertThat(harness.prods).hasSize(2) + assertThat(harness.resolvedPods).isEqualTo(2) + } + + @Test + fun `repeated episodes report one recovery for the same established session`() = runBlocking { + harness.openDial(atNanos = 0) + harness.advanceClock(DIAL_CONFIRMATION_MS + 1) + val watcher = harness.newWatcher() + + withTimeout(RUN_TIMEOUT_MS) { + // every onRemoteEnd of the settling dial churn starts an episode on the same watcher + repeat(3) { watcher.start(this)?.join() } + } + + assertThat(harness.recovered).isEqualTo(1) + assertThat(harness.prods).isEmpty() + } + + @Test + fun `stop ends the loop before the next prod`() { + harness.onProd = { harness.stopWatcher() } + + harness.runWatcher() + + assertThat(harness.prods).hasSize(1) + assertThat(harness.isWatcherActive).isFalse() + assertThat(harness.failed).isZero() + } + + // --- failures inside the loop ------------------------------------------- + + @Test + fun `retries a throwing probe instead of failing`() { + harness.probeFailure = IOException("API server unreachable") + + harness.runWatcher() + + assertThat(harness.prods).isEmpty() + assertThat(harness.probedPods.size).isGreaterThan(1) + assertThat(harness.failed).isEqualTo(1) + } + + @Test + fun `retries a throwing link refresh instead of failing`() { + harness.refreshFailure = IOException("status exec failed") + harness.onProd = { harness.scheduleFailedDials(DIAL_AFTER_MS, count = 2) } + + harness.runWatcher() + + assertThat(harness.prods).hasSize(1) // attempt 2 could not build a link + assertThat(harness.refreshes).isGreaterThan(1) + assertThat(harness.failed).isEqualTo(1) + } + + @Test + fun `retries a throwing prod instead of failing`() { + harness.prodFailure = IllegalStateException("the client handle is dead") + + harness.runWatcher() + + assertThat(harness.prods.size).isGreaterThan(1) + assertThat(harness.failed).isEqualTo(1) + } + + /** Runs the loop to completion; every case ends by recovery, the budget, or a stop. */ + private fun Harness.runWatcher(startTimes: Int = 1) = runBlocking { + withTimeout(RUN_TIMEOUT_MS) { + val watcher = newWatcher() + var job = watcher.start(this) + repeat(startTimes - 1) { job = watcher.start(this) } + job?.join() + } + } +} + +/** + * A virtual clock: the loop only reads time through it, and only advances it by sleeping. + * [sleep] suspends for a real millisecond so `stop()` still cancels the loop. + * + * [schedule] models the world changing as time passes (the Guest answers a prod a moment later): + * the action runs once the clock reaches its time. Scheduled actions must not advance the clock + * themselves, so firing never re-enters. + */ +private class TestClock { + private var nanos: Long = 0 + private val scheduled = mutableListOf() + + private class ScheduledAction(val atNanos: Long, val action: () -> Unit) + + fun now(): Long = nanos + + fun schedule(atNanos: Long, action: () -> Unit) { + scheduled += ScheduledAction(atNanos, action) + } + + fun advance(millis: Long) { + nanos += millis * NANOS_PER_MILLISECOND + fireDue() + } + + private fun fireDue() { + while (true) { + val due = scheduled.filter { it.atNanos <= nanos }.minByOrNull { it.atNanos } ?: return + scheduled.remove(due) + due.action() + } + } + + @Suppress("ConvertLongToDuration") + suspend fun sleep(millis: Long) { + advance(millis) + delay(1) + } +} + +private const val NANOS_PER_MILLISECOND = 1_000_000L + +/** + * Records the Guest's dials as the watcher observes them. + * + * A dial is visible from the accepted socket on ([isDialConnecting]) and keeps existing once it + * handshook (an entry in [openHandshakes]) until it ends. Several dials can overlap, as the live + * capture showed: a doomed dial and the Guest's next seamless attempt. + */ +private class FakeDials : ForwardDials { + private val openHandshakes = mutableListOf() + + /** A dial whose socket is accepted but whose forward handshake has not completed yet. */ + var isDialConnecting: Boolean = false + + override val isClientDialed: Boolean + get() = isDialConnecting || openHandshakes.isNotEmpty() + + override val oldestActiveHandshakeNanos: Long? + get() = openHandshakes.minOrNull() + + override var lastLongLivedDialNanos: Long? = null + override var failedDials: Long = 0 + + /** The dial handshook at [atNanos]: it is now being copied. */ + fun handshake(atNanos: Long) { + isDialConnecting = false + openHandshakes += atNanos + } + + /** The dial whose handshake was [handshakeNanos] ended: before confirmation, or after. */ + fun endDial(handshakeNanos: Long, confirmed: Boolean, endNanos: Long) { + openHandshakes.remove(handshakeNanos) + if (confirmed) { + lastLongLivedDialNanos = endNanos + } else { + failedDials++ + } + } +} + +/** + * Everything a watcher test drives: the fakes, the virtual clock, and the hooks that let a test + * script what the Guest's dials did. + */ +private class Harness { + + val clock = TestClock() + val dials = FakeDials() + + /** Every prod attempt, in order; a throwing prod is an attempt too. */ + val prods = mutableListOf() + val probedPods = mutableListOf() + var resolvedPods = 0 + var refreshes = 0 + var recovered = 0 + var failed = 0 + + /** Virtual time of the first prod, so a test can assert when the observation let it through. */ + var firstProdAtMs: Long = -1 + + /** The pod the cached link was built against; `null` disables the roll check. */ + var sessionPod: V1Pod? = null + + /** The pod that serves the workspace now. */ + var pod: V1Pod? = pod("luke-skywalker", "skywalker-uid") + var probeSucceeds = true + var probeFailure: Exception? = null + var refreshFailure: Exception? = null + var prodFailure: Exception? = null + var refreshedLink: URI? = null + var clientPresent = true + + /** The link a refresh reports, by call number: lets a test model a server that is not ready yet. */ + var refreshLinkResult: (call: Int) -> URI? = { refreshedLink } + + /** Virtual time a link refresh takes: a stale link's status exec can outlast the redial window. */ + var refreshDelayMs = 0L + + /** Runs after every prod attempt, so a test can script how the Guest answers it. */ + var onProd: () -> Unit = {} + + /** Stops the loop after this many prods: a test that does not want further iterations. */ + var stopAfterProds: Int? = null + + lateinit var watcher: ThinClientRecoveryWatcher + + private val timing = ThinClientRecoveryWatcher.Timing( + pollIntervalMs = POLL_MS, + longPollIntervalMs = LONG_POLL_MS, + longPollAfterMs = LONG_POLL_AFTER_MS, + redialWaitMs = REDIAL_WAIT_MS, + budgetMs = BUDGET_MS, + nowNanos = clock::now, + sleep = clock::sleep + ) + + /** The Guest dialed and its forward handshake landed at [atNanos]: a connection is copied. */ + fun openDial(atNanos: Long = clock.now()) { + dials.handshake(atNanos) + } + + /** A dial's socket is accepted but its forward handshake has not completed yet. */ + fun acceptConnectingDial() { + dials.isDialConnecting = true + } + + /** A connecting dial's handshake lands [afterMs] later. */ + fun scheduleDialHandshake(afterMs: Long) { + after(afterMs) { dials.handshake(clock.now()) } + } + + /** The dial that handshook at [handshakeNanos] ends [afterMs] later, before it can confirm. */ + fun scheduleFailedDialEnd(handshakeNanos: Long, afterMs: Long) { + after(afterMs) { dials.endDial(handshakeNanos, confirmed = false, endNanos = clock.now()) } + } + + /** + * A doomed dial as the live capture saw it: its handshake lands [handshakeAtMs] after this call + * and the Guest drops it [lifetimeMs] later, before it can confirm. Several of them can overlap, + * which is what the Guest's seamless loop does while a stale link is cached. + */ + fun scheduleDoomedDial(handshakeAtMs: Long, lifetimeMs: Long) { + val handshakeNanos = clock.now() + handshakeAtMs * NANOS_PER_MILLISECOND + clock.schedule(handshakeNanos) { dials.handshake(handshakeNanos) } + clock.schedule(handshakeNanos + lifetimeMs * NANOS_PER_MILLISECOND) { + dials.endDial(handshakeNanos, confirmed = false, endNanos = clock.now()) + } + } + + /** The dial that handshook at [handshakeNanos] outlives the threshold and then ends. */ + fun scheduleLongLivedDialEnd(handshakeNanos: Long, afterMs: Long) { + after(afterMs) { dials.endDial(handshakeNanos, confirmed = true, endNanos = clock.now()) } + } + + /** The Guest's answer to a prod: [count] failed dials, [afterMs] later. */ + fun scheduleFailedDials(afterMs: Long, count: Int = 2) { + after(afterMs) { dials.failedDials += count } + } + + /** A long-lived dial ends [afterMs] after the prod. */ + fun scheduleLongLivedDial(afterMs: Long) { + after(afterMs) { dials.lastLongLivedDialNanos = clock.now() } + } + + fun advanceClock(millis: Long) { + clock.advance(millis) + } + + fun stopWatcher() { + watcher.stop() + } + + val isWatcherActive: Boolean + get() = watcher.isActive + + private fun after(afterMs: Long, dial: () -> Unit) { + clock.schedule(clock.now() + afterMs * NANOS_PER_MILLISECOND, dial) + } + + fun newWatcher(): ThinClientRecoveryWatcher { + watcher = ThinClientRecoveryWatcher( + ThinClientRecoveryWatcher.Collaborators( + resolvePod = { + resolvedPods++ + pod + }, + probe = { probedPod -> + probedPods += probedPod + probeFailure.throwIfSet() + probeSucceeds + }, + cachedLink = CACHED_LINK, + sessionPod = sessionPod, + refreshLink = { + refreshes++ + if (refreshDelayMs > 0) clock.advance(refreshDelayMs) + refreshFailure.throwIfSet() + refreshLinkResult(refreshes) + }, + prod = { link -> + prods += link + if (firstProdAtMs < 0) { + firstProdAtMs = clock.now() / NANOS_PER_MILLISECOND + } + prodFailure.throwIfSet() + onProd() + if (prods.size == stopAfterProds) { + watcher.stop() + } + }, + session = dials, + isClientPresent = { clientPresent }, + onRecovered = { recovered++ }, + onRecoveryFailed = { failed++ } + ), + timing + ) + return watcher + } +} + +/** Throws a scripted failure, if the test set one: keeps the fakes free of three throw sites. */ +private fun Exception?.throwIfSet() { + if (this != null) throw this +} diff --git a/src/test/kotlin/com/redhat/devtools/gateway/devworkspace/DevSpacesConnectionTest.kt b/src/test/kotlin/com/redhat/devtools/gateway/devworkspace/DevSpacesConnectionTest.kt index 84d65696..bcd68176 100644 --- a/src/test/kotlin/com/redhat/devtools/gateway/devworkspace/DevSpacesConnectionTest.kt +++ b/src/test/kotlin/com/redhat/devtools/gateway/devworkspace/DevSpacesConnectionTest.kt @@ -16,12 +16,18 @@ import com.jetbrains.gateway.thinClientLink.ThinClientHandle import com.redhat.devtools.gateway.ClientWindowFocus import com.redhat.devtools.gateway.ThinClientDownloadException import com.redhat.devtools.gateway.ThinClientLaunchException +import com.redhat.devtools.gateway.ThinClientRecoveryWatcher import com.redhat.devtools.gateway.DevSpacesConnection import com.redhat.devtools.gateway.DevSpacesContext import com.redhat.devtools.gateway.download.DevSpacesClientConnectProgress +import com.redhat.devtools.gateway.openshift.ForwardDials import com.redhat.devtools.gateway.openshift.PortForwardSession import com.redhat.devtools.gateway.openshift.PortForwarder +import com.redhat.devtools.gateway.server.RemoteIDEServer +import io.kubernetes.client.openapi.models.V1Pod import io.mockk.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -37,6 +43,18 @@ import java.net.URI import java.util.concurrent.CancellationException import java.util.concurrent.atomic.AtomicBoolean +/** A forwarder that yields [session] and reports every probe as usable. */ +private fun fixedPortForwarder(session: PortForwardSession): PortForwarder = + object : PortForwarder { + override fun forward( + pod: V1Pod, + remotePort: Int, + onRemoteEnd: () -> Unit + ): PortForwardSession = session + + override suspend fun probe(pod: V1Pod, remotePort: Int): Boolean = true + } + class DevSpacesConnectionTest { private lateinit var devSpacesContext: DevSpacesContext @@ -191,7 +209,7 @@ class DevSpacesConnectionTest { val connectionWithForward = DevSpacesConnection( devSpacesContext, ClientWindowFocus(), - PortForwarder { _, _, _ -> session } + fixedPortForwarder(session) ) connectionWithForward.onThinClientClosed( @@ -223,7 +241,7 @@ class DevSpacesConnectionTest { val connectionWithForward = DevSpacesConnection( devSpacesContext, ClientWindowFocus(), - PortForwarder { _, _, _ -> session } + fixedPortForwarder(session) ) every { anyConstructed().get(any(), any()) } returns mockk(relaxed = true) { @@ -284,4 +302,116 @@ class DevSpacesConnectionTest { clientWindowFocus.requestFocus(thinClient) verify(exactly = 2) { thinClient.focusClientWindow() } } + + @Test + fun `teardown during active recovery withholds the workspace stop`() { + // given - the Guest is closed while recovery is still polling and the IDE looks terminated + val forwardClosed = AtomicBoolean(false) + val session = PortForwardSession(41_234) { forwardClosed.set(true) } + val connectionWithForward = DevSpacesConnection( + devSpacesContext, + ClientWindowFocus(), + fixedPortForwarder(session) + ) + val watcher = activeRecovery() + connectionWithForward.installRecoveryWatcher(watcher) + every { anyConstructed().stop(any(), any()) } just Runs + + // when - the workspace may be merely unreachable, so the stop decision is not ours (§7.9) + connectionWithForward.onThinClientClosed( + AtomicBoolean(false), + AtomicBoolean(true), + thinClient, + devSpacesContext.devWorkspace, + {}, + {}, + terminatingServer(), + session + ) + awaitForwardClosed(forwardClosed) + + // then - the teardown ran in full, the workspace was not stopped, recovery is cancelled + assertThat(forwardClosed).isTrue() + assertThat(watcher.isActive).isFalse() + verify(exactly = 0) { anyConstructed().stop(any(), any()) } + } + + @Test + fun `teardown stops the workspace when recovery already ended`() { + // given - recovery gave up (or succeeded) before the Guest was closed + val forwardClosed = AtomicBoolean(false) + val session = PortForwardSession(41_234) { forwardClosed.set(true) } + val connectionWithForward = DevSpacesConnection( + devSpacesContext, + ClientWindowFocus(), + fixedPortForwarder(session) + ) + val watcher = activeRecovery() + watcher.stop() + connectionWithForward.installRecoveryWatcher(watcher) + every { anyConstructed().stop(any(), any()) } just Runs + + // when - the Guest is closed, the healthy-path close => stop contract is unchanged + connectionWithForward.onThinClientClosed( + AtomicBoolean(false), + AtomicBoolean(true), + thinClient, + devSpacesContext.devWorkspace, + {}, + {}, + terminatingServer(), + session + ) + awaitForwardClosed(forwardClosed) + + // then + verify(exactly = 1) { anyConstructed().stop(any(), any()) } + } + + /** Teardown runs on Dispatchers.IO: wait until it closed the forward, its last step. */ + private fun awaitForwardClosed(closed: AtomicBoolean) { + runBlocking { + withTimeout(2_000) { + while (!closed.get()) { + delay(10) + } + } + } + } + + /** A running recovery: no pod is ever resolved, so it keeps polling until it is stopped. */ + private fun activeRecovery(): ThinClientRecoveryWatcher { + val watcher = ThinClientRecoveryWatcher( + ThinClientRecoveryWatcher.Collaborators( + resolvePod = { null }, + probe = { true }, + cachedLink = URI("tcp://127.0.0.1:41500#cb=1"), + sessionPod = null, + refreshLink = { null }, + prod = {}, + session = idleDials(), + isClientPresent = { true }, + onRecovered = {}, + onRecoveryFailed = {} + ), + ThinClientRecoveryWatcher.Timing( + pollIntervalMs = 60_000, + budgetMs = 600_000 + ) + ) + watcher.start(CoroutineScope(Dispatchers.Default)) + return watcher + } + + private fun idleDials(): ForwardDials = object : ForwardDials { + override val isClientDialed: Boolean = false + override val oldestActiveHandshakeNanos: Long? = null + override val lastLongLivedDialNanos: Long? = null + override val failedDials: Long = 0 + } + + /** An IDE server that reports "terminated": without the guard, teardown would stop the workspace. */ + private fun terminatingServer(): RemoteIDEServer = mockk(relaxed = true) { + coEvery { waitServerTerminated(any()) } returns true + } } diff --git a/src/test/kotlin/com/redhat/devtools/gateway/openshift/DevWorkspacePodsTest.kt b/src/test/kotlin/com/redhat/devtools/gateway/openshift/DevWorkspacePodsTest.kt index 5e21e56d..c0373d38 100644 --- a/src/test/kotlin/com/redhat/devtools/gateway/openshift/DevWorkspacePodsTest.kt +++ b/src/test/kotlin/com/redhat/devtools/gateway/openshift/DevWorkspacePodsTest.kt @@ -16,6 +16,7 @@ import io.kubernetes.client.openapi.ApiException import io.kubernetes.client.openapi.apis.CoreV1Api import io.kubernetes.client.openapi.models.V1ObjectMeta import io.kubernetes.client.openapi.models.V1Pod +import io.kubernetes.client.openapi.models.V1PodCondition import io.kubernetes.client.openapi.models.V1PodList import io.kubernetes.client.openapi.models.V1PodStatus import io.mockk.every @@ -242,16 +243,12 @@ class DevWorkspacePodsTest { } @Test - fun `#findFirst returns null when no pod matches`() { + fun `#findFirstRunning returns null when no pod matches`() { // given - mockkConstructor(CoreV1Api::class) - val listRequest = mockk() - every { listRequest.labelSelector(any()) } returns listRequest - every { listRequest.execute() } returns V1PodList().apply { items = emptyList() } - every { anyConstructed().listNamespacedPod("test-ns") } returns listRequest + mockPodList() // when - val result = pods.findFirst("test-ns", "controller.devfile.io/devworkspace_name=no-workspace") + val result = pods.findFirstRunning("test-ns", "controller.devfile.io/devworkspace_name=no-workspace") // then assertThat(result).isNull() @@ -259,31 +256,149 @@ class DevWorkspacePodsTest { } @Test - fun `#findFirst returns the first matching pod`() { + fun `#findFirstRunning returns the new pod when the old one is terminating`() { + // given — a pod roll: the old pod still reports Running but has a deletion timestamp + val terminating = podWith( + name = "old-pod", + creationTimestamp = BEFORE, + deletionTimestamp = AFTER, + ) + val new = podWith(name = "new-pod", creationTimestamp = AFTER) + mockPodList(terminating, new) + + // when + val result = pods.findFirstRunning("test-ns", "controller.devfile.io/devworkspace_name=my-workspace") + + // then + assertThat(result).isSameAs(new) + unmockkConstructor(CoreV1Api::class) + } + + @Test + fun `#findFirstRunning returns the newest pod when several pods are running`() { // given - mockkConstructor(CoreV1Api::class) - val first = podWith(name = "first-pod", namespace = "test-ns") - val second = podWith(name = "second-pod", namespace = "test-ns") - val listRequest = mockk() - every { listRequest.labelSelector(any()) } returns listRequest - every { listRequest.execute() } returns V1PodList().apply { items = listOf(first, second) } - every { anyConstructed().listNamespacedPod("test-ns") } returns listRequest + val older = podWith(name = "older-pod", creationTimestamp = BEFORE) + val newer = podWith(name = "newer-pod", creationTimestamp = AFTER) + mockPodList(older, newer) + + // when + val result = pods.findFirstRunning("test-ns", "controller.devfile.io/devworkspace_name=my-workspace") + + // then + assertThat(result).isSameAs(newer) + unmockkConstructor(CoreV1Api::class) + } + + @Test + fun `#findFirstRunning treats a pod without creation timestamp as the oldest`() { + // given + val withoutTimestamp = podWith(name = "no-timestamp-pod") + val withTimestamp = podWith(name = "timestamped-pod", creationTimestamp = AFTER) + mockPodList(withoutTimestamp, withTimestamp) + + // when + val result = pods.findFirstRunning("test-ns", "controller.devfile.io/devworkspace_name=my-workspace") + + // then + assertThat(result).isSameAs(withTimestamp) + unmockkConstructor(CoreV1Api::class) + } + + @Test + fun `#findFirstRunning returns null when only terminating pods match`() { + // given + val terminating = podWith( + name = "terminating-pod", + deletionTimestamp = AFTER, + ) + mockPodList(terminating) + + // when + val result = pods.findFirstRunning("test-ns", "controller.devfile.io/devworkspace_name=my-workspace") + + // then + assertThat(result).isNull() + unmockkConstructor(CoreV1Api::class) + } + + @Test + fun `#findFirstRunning returns null when the pod has no Ready condition`() { + // given — running but not yet ready (conditions present, Ready=False) + val notReady = podWith(name = "not-ready-pod", isReady = false) + mockPodList(notReady) // when - val result = pods.findFirst("test-ns", "controller.devfile.io/devworkspace_name=my-workspace") + val result = pods.findFirstRunning("test-ns", "controller.devfile.io/devworkspace_name=my-workspace") // then - assertThat(result).isSameAs(first) + assertThat(result).isNull() unmockkConstructor(CoreV1Api::class) } - private fun podWith(name: String, namespace: String): V1Pod { + @Test + fun `#findFirstRunning returns null when the pod has no conditions at all`() { + // given — running phase but the status carries no conditions + val withoutConditions = podWith(name = "no-conditions-pod").apply { + status = V1PodStatus().apply { phase = "Running" } + } + mockPodList(withoutConditions) + + // when + val result = pods.findFirstRunning("test-ns", "controller.devfile.io/devworkspace_name=my-workspace") + + // then + assertThat(result).isNull() + unmockkConstructor(CoreV1Api::class) + } + + @Test + fun `#findFirstRunning ignores pods whose phase is not Running`() { + // given + val pending = podWith(name = "pending-pod", phase = "Pending") + mockPodList(pending) + + // when + val result = pods.findFirstRunning("test-ns", "controller.devfile.io/devworkspace_name=my-workspace") + + // then + assertThat(result).isNull() + unmockkConstructor(CoreV1Api::class) + } + + private fun mockPodList(vararg pods: V1Pod) { + mockkConstructor(CoreV1Api::class) + val listRequest = mockk() + every { listRequest.labelSelector(any()) } returns listRequest + every { listRequest.execute() } returns V1PodList().apply { items = pods.toList() } + every { anyConstructed().listNamespacedPod("test-ns") } returns listRequest + } + + private fun podWith( + name: String, + phase: String = "Running", + isReady: Boolean = true, + creationTimestamp: OffsetDateTime? = null, + deletionTimestamp: OffsetDateTime? = null, + ): V1Pod { return V1Pod().apply { metadata = V1ObjectMeta().apply { this.name = name - this.namespace = namespace + this.namespace = "test-ns" + this.creationTimestamp = creationTimestamp + this.deletionTimestamp = deletionTimestamp + } + status = V1PodStatus().apply { + this.phase = phase + conditions = listOf( + V1PodCondition().apply { + type = "Ready" + status = if (isReady) "True" else "False" + } + ) } } } - } + +private val BEFORE: OffsetDateTime = OffsetDateTime.parse("2026-01-01T10:00:00Z") +private val AFTER: OffsetDateTime = OffsetDateTime.parse("2026-01-01T10:05:00Z") diff --git a/src/test/kotlin/com/redhat/devtools/gateway/openshift/ForwardRetryPolicyTest.kt b/src/test/kotlin/com/redhat/devtools/gateway/openshift/ForwardRetryPolicyTest.kt new file mode 100644 index 00000000..a8473db2 --- /dev/null +++ b/src/test/kotlin/com/redhat/devtools/gateway/openshift/ForwardRetryPolicyTest.kt @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2026 Red Hat, Inc. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + */ +package com.redhat.devtools.gateway.openshift + +import io.kubernetes.client.openapi.models.V1ObjectMeta +import io.kubernetes.client.openapi.models.V1Pod +import kotlinx.coroutines.runBlocking +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatThrownBy +import org.junit.jupiter.api.Test +import java.io.IOException + +class ForwardRetryPolicyTest { + + companion object { + private const val NANOS_PER_MILLI = 1_000_000L + private const val CONNECT_BUDGET_OVERRUN_MS = 3_000L + private const val OUTAGE_BUDGET_OVERRUN_MS = 1_000L + private const val LONG_RUNNING_ATTEMPT = 42 + } + + private val pod = V1Pod().apply { + metadata = V1ObjectMeta().apply { name = "luke-skywalker" } + } + private val ports = PortMapping(41_234, 5990) + private val cause = IOException("connection reset") + + @Test + fun `connect-time retries up to the attempt cap`(): Unit = runBlocking { + val policy = policy(PodLiveness.RUNNING) + + assertThat(policy.decide(pod, ports, false, handshake(1))).isEqualTo(RetryDecision.RETRY) + assertThat(policy.decide(pod, ports, false, handshake(2))).isEqualTo(RetryDecision.RETRY) + assertThat( + policy.decide(pod, ports, false, handshake(ForwardRetryPolicy.CONNECT_ATTEMPTS)) + ).isEqualTo(RetryDecision.ATTEMPTS_EXHAUSTED) + } + + @Test + fun `connect-time budget exhaustion is terminal`(): Unit = runBlocking { + val policy = policy(PodLiveness.UNKNOWN) + val firstFailureNanos = System.nanoTime() - CONNECT_BUDGET_OVERRUN_MS * NANOS_PER_MILLI + + // attempt 2 is below the attempt cap: only the 2s budget can stop it + assertThat(policy.decide(pod, ports, false, handshake(2, firstFailureNanos))) + .isEqualTo(RetryDecision.BUDGET_EXHAUSTED) + } + + @Test + fun `steady-state retries past the connect-time attempt cap`(): Unit = runBlocking { + val policy = policy(PodLiveness.RUNNING) + val pastConnectCap = ForwardRetryPolicy.CONNECT_ATTEMPTS + 1 + + assertThat(policy.decide(pod, ports, true, handshake(pastConnectCap))) + .isEqualTo(RetryDecision.RETRY) + assertThat(policy.decide(pod, ports, true, handshake(LONG_RUNNING_ATTEMPT))) + .isEqualTo(RetryDecision.RETRY) + } + + @Test + fun `steady-state retries while the pod liveness is unknown`(): Unit = runBlocking { + val policy = policy(PodLiveness.UNKNOWN) + + assertThat(policy.decide(pod, ports, true, handshake(LONG_RUNNING_ATTEMPT))) + .isEqualTo(RetryDecision.RETRY) + } + + @Test + fun `steady-state outage budget exhaustion is terminal`(): Unit = runBlocking { + val policy = policy(PodLiveness.RUNNING) + val firstFailureNanos = System.nanoTime() - + (ForwardRetryPolicy.STEADY_STATE_OUTAGE_BUDGET_MS + OUTAGE_BUDGET_OVERRUN_MS) * + NANOS_PER_MILLI + + assertThat(policy.decide(pod, ports, true, handshake(LONG_RUNNING_ATTEMPT, firstFailureNanos))) + .isEqualTo(RetryDecision.BUDGET_EXHAUSTED) + } + + @Test + fun `a gone pod is terminal in both phases`(): Unit = runBlocking { + val policy = policy(PodLiveness.GONE) + + assertThat(policy.decide(pod, ports, false, handshake(1))) + .isEqualTo(RetryDecision.POD_GONE) + assertThat(policy.decide(pod, ports, true, handshake(LONG_RUNNING_ATTEMPT))) + .isEqualTo(RetryDecision.POD_GONE) + } + + @Test + fun `connect-time keeps the fixed reconnect delay`() { + val policy = policy(PodLiveness.RUNNING) + + assertThat(policy.reconnectDelayMs(1, established = false)) + .isEqualTo(ForwardRetryPolicy.RECONNECT_DELAY_MS) + assertThat(policy.reconnectDelayMs(LONG_RUNNING_ATTEMPT, established = false)) + .isEqualTo(ForwardRetryPolicy.RECONNECT_DELAY_MS) + } + + @Test + fun `steady-state backs off from one second to the cap`() { + val policy = policy(PodLiveness.RUNNING) + val firstFiveAttempts = (1..5).map { policy.reconnectDelayMs(it, established = true) } + + assertThat(firstFiveAttempts).containsExactly(1000L, 2000L, 3000L, 5000L, 5000L) + assertThat(policy.reconnectDelayMs(LONG_RUNNING_ATTEMPT, established = true)) + .isEqualTo(ForwardRetryPolicy.STEADY_STATE_MAX_DELAY_MS) + } + + @Test + fun `an attempt number below one is rejected`() { + val policy = policy(PodLiveness.RUNNING) + + assertThatThrownBy { policy.reconnectDelayMs(0, established = true) } + .isInstanceOf(IllegalArgumentException::class.java) + } + + private fun handshake( + attempt: Int, + firstFailureNanos: Long = System.nanoTime() + ): FailedHandshake = FailedHandshake(attempt, firstFailureNanos, cause) + + private fun policy(liveness: PodLiveness): ForwardRetryPolicy = ForwardRetryPolicy { liveness } +} diff --git a/src/test/kotlin/com/redhat/devtools/gateway/openshift/PodPortForwarderTest.kt b/src/test/kotlin/com/redhat/devtools/gateway/openshift/PodPortForwarderTest.kt index 6a14616f..84d50828 100644 --- a/src/test/kotlin/com/redhat/devtools/gateway/openshift/PodPortForwarderTest.kt +++ b/src/test/kotlin/com/redhat/devtools/gateway/openshift/PodPortForwarderTest.kt @@ -40,7 +40,9 @@ import java.net.Socket import java.net.SocketTimeoutException import java.time.OffsetDateTime import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong import kotlin.time.Duration.Companion.milliseconds /** Opens a forward that does not observe remote end. */ @@ -48,8 +50,71 @@ import kotlin.time.Duration.Companion.milliseconds private fun PortForwarder.forward(pod: V1Pod, remotePort: Int): PortForwardSession = forward(pod, remotePort) {} +@Suppress("LargeClass") // one forward, many retry/retarget cases; keeping them together eases discovery class PodPortForwarderTest { + companion object { + /** More consecutive failures than connect-time allows, so only steady-state can survive them. */ + private const val ESTABLISHED_HANDSHAKE_FAILURES = 4 + + /** + * Covers the steady-state backoff after the failures above (1s + 2s + 3s + 5s) plus the + * 100ms client-gone probes between attempts - and the full-suite load on top of that + * real-time schedule, which alone has pushed this test past its old 25s window. + */ + private const val STEADY_STATE_RETRY_TIMEOUT_MS = 60_000L + + private const val HANDSHAKE_TIMEOUT_MS = 5_000L + + /** + * Scheduler slack added to every observation window. The port-forward dispatcher thread and + * the polling test thread can both be stalled for seconds under full-suite load, so a + * window sized to the event alone fails on the stall, not on the behaviour under test. + */ + private const val TIMING_SLACK_MS = 10_000L + + /** Window for an event that is expected within milliseconds (a handshake, a dial's end). */ + private const val EVENT_TIMEOUT_MS = HANDSHAKE_TIMEOUT_MS + TIMING_SLACK_MS + + /** Probe bound of the hang test: far below the production 3s to keep the test fast. */ + private const val PROBE_BOUND_MS = 100L + + /** + * Bound of one port-forward open in the hang tests: production uses [OPEN_TIMEOUT_MS] + * (10 s), far too long for a test that provokes the hang. + */ + private const val OPEN_BOUND_MS = 200L + + /** How long a bounded open may take to free its blocked thread after the bound fired. */ + private const val OPEN_RELEASE_TIMEOUT_MS = 5_000L + + /** + * Safety cap of the open that outlives [PROBE_BOUND_MS]. The test releases the open itself, + * so the hang lasts until then: no scheduling delay can shorten the margin under test. + */ + private const val HUNG_OPEN_CAP_MS = 30_000L + + /** + * Survival a dial needs to count as an established session. Production uses + * [DIAL_CONFIRMATION_MS] (15s, more than twice the measured 6.5-6.9s of a stale-link dial); + * the tests shrink it so both sides of the threshold are exercised with short dials. + */ + private const val TEST_CONFIRMATION_MS = 200L + + /** Keeps a dialed connection safely past the confirmation threshold, so it is long-lived. */ + private const val LONG_LIVED_MARGIN_MS = 200L + + /** + * Window for a dial to be classified as long-lived. Larger than the dial itself + * ([TEST_CONFIRMATION_MS] + [LONG_LIVED_MARGIN_MS]) by [TIMING_SLACK_MS]: the dial ends with + * a `Thread.sleep` on the dispatcher thread, which load can delay past the dial's own length. + */ + private const val LONG_LIVED_DIAL_TIMEOUT_MS = + TEST_CONFIRMATION_MS + LONG_LIVED_MARGIN_MS + TIMING_SLACK_MS + + private const val NANOS_PER_MILLI = 1_000_000L + } + private val serverData = "from server" private lateinit var client: ApiClient @@ -109,9 +174,13 @@ class PodPortForwarderTest { @Test fun `#forward tries several times if connecting fails`() { // given + val attempts = AtomicInteger() every { anyConstructed().forward(pod, listOf(remotePort)) - } throws IOException("connection reset") + } answers { + attempts.incrementAndGet() + throw IOException("connection reset") + } val podsRunning = PodPortForwarder(client) { PodLiveness.RUNNING } // when @@ -124,23 +193,91 @@ class PodPortForwarderTest { // (CONNECT_ATTEMPTS / retry budget) are what stop the retries val socket = Socket("127.0.0.1", closeable.localPort) try { + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() // attempts land at ~0s, ~1.2s and ~2.4s (1s reconnect delay + 2x100ms client-gone // probes between attempts); attempt #3 is the last one CONNECT_ATTEMPTS allows, and - // by then the 2s budget is exhausted too. Waiting 5s — past where a 4th attempt - // (~3.6s) would land — proves the loop stopped rather than retried forever. - runBlocking { delay(5000.milliseconds) } - verify(atLeast = 2) { // 2+ retries - anyConstructed().forward(pod, listOf(remotePort)) - } - verify(atMost = 3) { // neither the attempts cap nor the budget allows a 4th attempt - anyConstructed().forward(pod, listOf(remotePort)) - } + // by then the 2s budget is exhausted too. Awaiting the series instead of sleeping a + // fixed time keeps this independent of scheduler load: a 4th attempt would leave the + // socket open and the read below would time out. + assertThat( + awaitTrue(EVENT_TIMEOUT_MS) { + attempts.get() >= ForwardRetryPolicy.CONNECT_ATTEMPTS + } + ).isTrue() + assertThat(socket.inputStream.read()).isEqualTo(-1) + assertThat(attempts.get()).isEqualTo(ForwardRetryPolicy.CONNECT_ATTEMPTS) } finally { socket.close() closeable.close() } } + @Test + fun `#forward keeps retrying an established session past the connect-time attempt cap`() { + // given - the handshake fails more often than connect-time allows, then succeeds + val portForwardResult = mockk(relaxed = true) + every { portForwardResult.getInputStream(remotePort) } returns silentPodStream() + every { portForwardResult.getOutboundStream(remotePort) } returns ByteArrayOutputStream() + val handshakes = AtomicInteger() + every { + anyConstructed().forward(pod, listOf(remotePort)) + } answers { + if (handshakes.incrementAndGet() <= ESTABLISHED_HANDSHAKE_FAILURES) { + throw IOException("connection reset") + } + portForwardResult + } + val podsRunning = PodPortForwarder(client) { PodLiveness.RUNNING } + val session = podsRunning.forward(pod, remotePort) + session.markEstablished() + + try { + // when - the Guest re-dials once and stays connected across the outage + runBlocking { delay(100.milliseconds) } + Socket("127.0.0.1", session.localPort).use { + // then - the loop outlives the 3-attempt connect-time cap and the handshake lands + assertThat( + awaitTrue(STEADY_STATE_RETRY_TIMEOUT_MS) { + session.lastSuccessfulHandshakeNanos != null + } + ).isTrue() + assertThat(handshakes.get()).isEqualTo(ESTABLISHED_HANDSHAKE_FAILURES + 1) + } + } finally { + session.close() + } + } + + @Test + fun `#markEstablished is idempotent and records the successful handshake`() { + // given - a silent pod stream, so the handshake is the only observable event + val portForwardResult = mockk(relaxed = true) + every { + anyConstructed().forward(pod, listOf(remotePort)) + } returns portForwardResult + every { portForwardResult.getInputStream(remotePort) } returns silentPodStream() + every { portForwardResult.getOutboundStream(remotePort) } returns ByteArrayOutputStream() + val session = PodPortForwarder(client).forward(pod, remotePort) + + try { + // when - connect calls it once, a re-run may call it again + assertThat(session.isEstablished).isFalse() + session.markEstablished() + session.markEstablished() + + // then - the phase only moves forward and the accepted connection records the handshake + assertThat(session.isEstablished).isTrue() + assertThat(session.lastSuccessfulHandshakeNanos).isNull() + Socket("127.0.0.1", session.localPort).use { + assertThat( + awaitTrue(EVENT_TIMEOUT_MS) { session.lastSuccessfulHandshakeNanos != null } + ).isTrue() + } + } finally { + session.close() + } + } + @Test fun `#forward does not retry when the client disconnects`() { // given - the handshake always fails while the pod stays alive, @@ -185,7 +322,7 @@ class PodPortForwarderTest { // then - the local socket is closed instead of staying open waiting for the other direction Socket("127.0.0.1", closeable.localPort).use { socket -> - socket.soTimeout = 2000 + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() assertThat(socket.inputStream.read()).isEqualTo(-1) } closeable.close() @@ -221,13 +358,12 @@ class PodPortForwarderTest { .forward(pod, remotePort) { remoteEnds.incrementAndGet() } runBlocking { delay(100.milliseconds) } Socket("127.0.0.1", session.localPort).use { socket -> - socket.soTimeout = 2000 + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() assertThat(socket.inputStream.read()).isEqualTo(-1) } - runBlocking { delay(100.milliseconds) } - // then - assertThat(remoteEnds.get()).isEqualTo(1) + // then - the pod-side end is reported, however late the load lets the pump finish + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { remoteEnds.get() == 1 }).isTrue() session.close() } @@ -276,7 +412,7 @@ class PodPortForwarderTest { socket.outputStream.write("ping".toByteArray()) socket.outputStream.flush() } - runBlocking { delay(300.milliseconds) } + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { remoteEnds.get() == 1 }).isTrue() } // then - only a clean client-side close suppresses the report @@ -299,7 +435,7 @@ class PodPortForwarderTest { // then - the accepted socket is closed by the first, failing attempt: // the client sees EOF instead of a connection left hanging Socket("127.0.0.1", closeable.localPort).use { socket -> - socket.soTimeout = 2000 + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() assertThat(socket.inputStream.read()).isEqualTo(-1) } verify(exactly = 1) { @@ -308,6 +444,302 @@ class PodPortForwarderTest { closeable.close() } + @Test + fun `#forward retargets to the pod that replaced a gone pod`() { + // given - the pinned pod is gone, the workspace already runs a replacement + val replacement = podWith("new-pod", uid = "new-uid") + val portForwardResult = silentForwardResult() + every { + anyConstructed().forward(any(), listOf(remotePort)) + } answers { + if (firstArg() === pod) { + throw ApiException("Expected HTTP 101 response but was '404 Not Found'") + } + portForwardResult + } + val forwarder = PodPortForwarder( + client, + resolvePod = { replacement }, + livenessProvider = { target -> + if (target === replacement) PodLiveness.RUNNING else PodLiveness.GONE + } + ) + + // when + val session = forwarder.forward(pod, remotePort) + try { + Socket("127.0.0.1", session.localPort).use { + // then - the retry lands on the replacement and the connection is established + assertThat( + awaitTrue(EVENT_TIMEOUT_MS) { session.lastSuccessfulHandshakeNanos != null } + ).isTrue() + } + verify(exactly = 1) { + anyConstructed().forward(pod, listOf(remotePort)) + } + verify(exactly = 1) { + anyConstructed().forward(replacement, listOf(remotePort)) + } + } finally { + session.close() + } + } + + @Test + fun `#forward stops when the gone pod has no replacement`() { + // given - the pod is gone and the workspace has no running pod to move to + every { + anyConstructed().forward(pod, listOf(remotePort)) + } throws ApiException("Expected HTTP 101 response but was '404 Not Found'") + val resolveCalls = AtomicInteger() + val forwarder = PodPortForwarder( + client, + resolvePod = { + resolveCalls.incrementAndGet() + null + }, + livenessProvider = { PodLiveness.GONE } + ) + + // when + val session = forwarder.forward(pod, remotePort) + try { + runBlocking { delay(100.milliseconds) } + + // then - terminal: the accepted socket is closed after the single failing attempt + Socket("127.0.0.1", session.localPort).use { socket -> + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() + assertThat(socket.inputStream.read()).isEqualTo(-1) + } + verify(exactly = 1) { + anyConstructed().forward(pod, listOf(remotePort)) + } + assertThat(resolveCalls.get()).isEqualTo(1) + } finally { + session.close() + } + } + + @Test + fun `#forward stops when the resolver still names the pod that just failed`() { + // given - the resolver answers "the current pod is the one that just failed" + val gonePod = podWith("luke-skywalker", uid = "old-uid") + every { + anyConstructed().forward(gonePod, listOf(remotePort)) + } throws ApiException("Expected HTTP 101 response but was '404 Not Found'") + val resolveCalls = AtomicInteger() + val forwarder = PodPortForwarder( + client, + resolvePod = { + resolveCalls.incrementAndGet() + podWith("luke-skywalker", uid = "old-uid") + }, + livenessProvider = { PodLiveness.GONE } + ) + + // when + val session = forwarder.forward(gonePod, remotePort) + try { + runBlocking { delay(100.milliseconds) } + + // then - no pointless swap loop: the same pod stays terminal + Socket("127.0.0.1", session.localPort).use { socket -> + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() + assertThat(socket.inputStream.read()).isEqualTo(-1) + } + verify(exactly = 1) { + anyConstructed().forward(gonePod, listOf(remotePort)) + } + assertThat(resolveCalls.get()).isEqualTo(1) + } finally { + session.close() + } + } + + @Test + fun `#forward retargets once for two connections that see the same gone pod`() { + // given - two concurrent re-dials, both failing against the dead pod + val replacement = podWith("new-pod", uid = "new-uid") + val portForwardResult = silentForwardResult() + val replacementAttempts = AtomicInteger() + every { + anyConstructed().forward(any(), listOf(remotePort)) + } answers { + if (firstArg() === pod) { + throw ApiException("Expected HTTP 101 response but was '404 Not Found'") + } + replacementAttempts.incrementAndGet() + portForwardResult + } + val resolveCalls = AtomicInteger() + val forwarder = PodPortForwarder( + client, + resolvePod = { + resolveCalls.incrementAndGet() + replacement + }, + livenessProvider = { PodLiveness.GONE } + ) + val session = forwarder.forward(pod, remotePort) + + try { + val first = Socket("127.0.0.1", session.localPort) + val second = Socket("127.0.0.1", session.localPort) + first.use { + second.use { + // then - both connections end up bridged to the replacement + assertThat( + awaitTrue(EVENT_TIMEOUT_MS) { + session.hasActiveForward && replacementAttempts.get() >= 2 + } + ).isTrue() + } + } + // the dead pod is resolved at most once per connection: one swap serves both + assertThat(resolveCalls.get()).isBetween(1, 2) + assertThat(replacementAttempts.get()).isEqualTo(2) + } finally { + session.close() + } + } + + @Test + fun `#forward starts a fresh attempt series on the replacement pod`() { + // given - a gone pod, and a replacement whose handshake always fails + val replacement = podWith("new-pod", uid = "new-uid") + val replacementAttempts = AtomicInteger() + every { + anyConstructed().forward(any(), listOf(remotePort)) + } answers { + if (firstArg() === pod) { + throw ApiException("Expected HTTP 101 response but was '404 Not Found'") + } + replacementAttempts.incrementAndGet() + throw IOException("connection reset") + } + val forwarder = PodPortForwarder( + client, + resolvePod = { replacement }, + livenessProvider = { target -> + if (target === replacement) PodLiveness.RUNNING else PodLiveness.GONE + } + ) + + // when + val session = forwarder.forward(pod, remotePort) + try { + runBlocking { delay(100.milliseconds) } + Socket("127.0.0.1", session.localPort).use { socket -> + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() + + // then - the connect-time series restarts at the replacement: the dead pod's + // failure did not consume one of its attempts. Waiting for the series to have run + // (rather than sleeping a fixed time) keeps this independent of scheduler load; + // a fourth attempt would keep the socket open and fail the read below. + assertThat( + awaitTrue(EVENT_TIMEOUT_MS) { + replacementAttempts.get() >= ForwardRetryPolicy.CONNECT_ATTEMPTS + } + ).isTrue() + assertThat(socket.inputStream.read()).isEqualTo(-1) + } + assertThat(replacementAttempts.get()).isEqualTo(ForwardRetryPolicy.CONNECT_ATTEMPTS) + verify(exactly = 1) { + anyConstructed().forward(pod, listOf(remotePort)) + } + } finally { + session.close() + } + } + + @Test + fun `#forward stops retargeting once the established outage budget elapsed`() { + // given - an established session whose first failure happened long before the retarget + val replacement = podWith("new-pod", uid = "new-uid") + val replacementAttempts = AtomicInteger() + val clockNanos = AtomicLong(0) + every { + anyConstructed().forward(any(), listOf(remotePort)) + } answers { + if (firstArg() === pod) { + throw ApiException("Expected HTTP 101 response but was '404 Not Found'") + } + replacementAttempts.incrementAndGet() + // the replacement is reached only after the outage budget already elapsed + clockNanos.addAndGet(ForwardRetryPolicy.STEADY_STATE_OUTAGE_BUDGET_MS * NANOS_PER_MILLI) + throw IOException("connection reset") + } + val forwarder = PodPortForwarder( + client, + resolvePod = { replacement }, + nowNanos = { clockNanos.get() }, + livenessProvider = { target -> + if (target === replacement) PodLiveness.RUNNING else PodLiveness.GONE + } + ) + + // when + val session = forwarder.forward(pod, remotePort) + session.markEstablished() + try { + runBlocking { delay(100.milliseconds) } + + // then - the budget keeps running across the retarget and wins over the fresh series: + // the socket is closed after the first attempt on the replacement + Socket("127.0.0.1", session.localPort).use { socket -> + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() + assertThat(socket.inputStream.read()).isEqualTo(-1) + } + assertThat(replacementAttempts.get()).isEqualTo(1) + } finally { + session.close() + } + } + + @Test + fun `#forward keeps retrying a replacement within the established outage budget`() { + // given - an established session early in its outage budget + val replacement = podWith("new-pod", uid = "new-uid") + val replacementAttempts = AtomicInteger() + val clockNanos = AtomicLong(0) + val portForwardResult = silentForwardResult() + every { + anyConstructed().forward(any(), listOf(remotePort)) + } answers { + if (firstArg() === pod) { + throw ApiException("Expected HTTP 101 response but was '404 Not Found'") + } + clockNanos.addAndGet(NANOS_PER_MILLI * 60_000) + if (replacementAttempts.incrementAndGet() == 1) { + throw IOException("connection reset") + } + portForwardResult + } + val forwarder = PodPortForwarder( + client, + resolvePod = { replacement }, + nowNanos = { clockNanos.get() }, + livenessProvider = { target -> + if (target === replacement) PodLiveness.RUNNING else PodLiveness.GONE + } + ) + + // when + val session = forwarder.forward(pod, remotePort) + session.markEstablished() + try { + Socket("127.0.0.1", session.localPort).use { + // then - the retargeted series retries while the budget lasts and succeeds + assertThat( + awaitTrue(EVENT_TIMEOUT_MS) { session.lastSuccessfulHandshakeNanos != null } + ).isTrue() + } + assertThat(replacementAttempts.get()).isEqualTo(2) + } finally { + session.close() + } + } + @Test fun `#forward does not retry when the copy fails mid session`() { // given - the pod stays alive, but the remote stream fails after the handshake @@ -326,10 +758,10 @@ class PodPortForwarderTest { // when val closeable = podsRunning.forward(pod, remotePort) val socket = Socket("127.0.0.1", closeable.localPort) - runBlocking { delay(500.milliseconds) } - // then - the copy failure is terminal: one handshake, no liveness query, socket closed - socket.soTimeout = 500 + // then - the copy failure is terminal: one handshake, no liveness query, socket closed. + // The read itself waits for that close (bounded), so no fixed sleep is needed. + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() val readOutcome = runCatching { socket.inputStream.read() } assertThat(readOutcome.exceptionOrNull() is SocketTimeoutException).isFalse() assertThat(readOutcome.getOrNull() ?: -1).isEqualTo(-1) @@ -359,7 +791,7 @@ class PodPortForwarderTest { // when val closeable = podsRunning.forward(pod, remotePort) Socket("127.0.0.1", closeable.localPort).use { socket -> - socket.soTimeout = 2000 + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() assertThat(socket.inputStream.read()).isEqualTo(-1) } runBlocking { delay(100.milliseconds) } @@ -369,6 +801,310 @@ class PodPortForwarderTest { closeable.close() } + @Test + fun `#probe succeeds when the forward opens and the streams close cleanly`() = runBlocking { + // given + val portForwardResult = mockk(relaxed = true) + val podIn = mockk(relaxed = true) + val podOut = mockk(relaxed = true) + every { + anyConstructed().forward(pod, listOf(remotePort)) + } returns portForwardResult + every { portForwardResult.getInputStream(remotePort) } returns podIn + every { portForwardResult.getOutboundStream(remotePort) } returns podOut + + // when + val opened = PodPortForwarder(client).probe(pod, remotePort) + + // then - the forward is opened and closed at once: no listener, no client socket + assertThat(opened).isTrue() + verify { podIn.close() } + verify { podOut.close() } + } + + @Test + fun `#probe fails when the forward cannot be opened`() = runBlocking { + // given + every { + anyConstructed().forward(pod, listOf(remotePort)) + } throws IOException("connection reset") + + // when / then + assertThat(PodPortForwarder(client).probe(pod, remotePort)).isFalse() + } + + @Test + fun `#probe fails when the open hangs past the bound`() = runBlocking { + // given - the pod websocket never initializes: client-java's open blocks until interrupted + val releaseOpen = CountDownLatch(1) + val openFinished = CountDownLatch(1) + val forwarder = PodPortForwarder( + client, + probeTimeoutMs = PROBE_BOUND_MS, + openForward = { _, _ -> + try { + releaseOpen.await(HUNG_OPEN_CAP_MS, TimeUnit.MILLISECONDS) + hangingOpenResult() + } finally { + openFinished.countDown() + } + } + ) + + // when + val startedAtNanos = System.nanoTime() + val opened = forwarder.probe(pod, remotePort) + val elapsedMs = (System.nanoTime() - startedAtNanos) / NANOS_PER_MILLI + + try { + // then - a hanging open counts as a failed probe within the bound, and the blocked open + // is interrupted, so it does not stay pending for the life of the process + assertThat(opened).isFalse() + assertThat(elapsedMs).isLessThan(HUNG_OPEN_CAP_MS) + assertThat(openFinished.await(OPEN_RELEASE_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + } finally { + // if the interruption ever regressed, fail the assertion above instead of hanging here + releaseOpen.countDown() + } + } + + @Test + fun `#forward reclaims a dial whose open hangs`() { + // given - the live freeze (CRW-13910): client-java's PortForward.forward blocks in + // waitForInitialized() forever, so the dial could neither retry nor end + val releaseOpen = CountDownLatch(1) + val openAttempts = AtomicInteger() + val hangingResult = hangingOpenResult() + val forwarder = PodPortForwarder( + client, + openTimeoutMs = OPEN_BOUND_MS, + openForward = { _, _ -> + openAttempts.incrementAndGet() + // every open blocks until its bound interrupts it, like the stalled websocket + releaseOpen.await(HUNG_OPEN_CAP_MS, TimeUnit.MILLISECONDS) + hangingResult + } + ) { PodLiveness.RUNNING } + val session = forwarder.forward(pod, remotePort) + val socket = Socket("127.0.0.1", session.localPort) + + try { + // when / then - the dial is visible, its bounded opens fail retryably, the loop goes on, + // and the dial can still end: the state the recovery observation froze on clears again + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { session.isClientDialed }).isTrue() + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { openAttempts.get() >= 2 }).isTrue() + } finally { + releaseOpen.countDown() + socket.close() + session.close() + } + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { !session.isClientDialed }).isTrue() + } + + @Test + fun `#forward retries a dial whose open timed out`() { + // given - the first open hangs and is bounded; the pod then answers normally + val portForwardResult = mockk(relaxed = true) + every { portForwardResult.getInputStream(remotePort) } returns silentPodStream() + every { portForwardResult.getOutboundStream(remotePort) } returns ByteArrayOutputStream() + val releaseOpen = CountDownLatch(1) + val openAttempts = AtomicInteger() + val forwarder = PodPortForwarder( + client, + openTimeoutMs = OPEN_BOUND_MS, + openForward = { _, _ -> + if (openAttempts.incrementAndGet() == 1) { + try { + releaseOpen.await(HUNG_OPEN_CAP_MS, TimeUnit.MILLISECONDS) + } finally { + releaseOpen.countDown() + } + } + portForwardResult + } + ) { PodLiveness.RUNNING } + val session = forwarder.forward(pod, remotePort) + val socket = Socket("127.0.0.1", session.localPort) + + try { + // then - the timed-out open is a failed handshake, not a cancellation of the dial + assertThat( + awaitTrue(STEADY_STATE_RETRY_TIMEOUT_MS) { + session.lastSuccessfulHandshakeNanos != null + } + ).isTrue() + assertThat(openAttempts.get()).isGreaterThanOrEqualTo(2) + } finally { + releaseOpen.countDown() + socket.close() + session.close() + } + } + + @Test + fun `#forward reports an active forward while a connection is copied`() { + // given - a pod stream that never ends: only closing the session ends the connection + val portForwardResult = mockk(relaxed = true) + every { + anyConstructed().forward(pod, listOf(remotePort)) + } returns portForwardResult + every { portForwardResult.getInputStream(remotePort) } returns silentPodStream() + every { portForwardResult.getOutboundStream(remotePort) } returns ByteArrayOutputStream() + val session = PodPortForwarder(client).forward(pod, remotePort) + + // when - the Guest dialed and its connection is being copied + assertThat(session.hasActiveForward).isFalse() + assertThat(session.isClientDialed).isFalse() + assertThat(session.oldestActiveHandshakeNanos).isNull() + val socket = Socket("127.0.0.1", session.localPort) + try { + // then - the open connection is visible by its handshake, which is what can confirm it + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { session.hasActiveForward }).isTrue() + assertThat(session.isClientDialed).isTrue() + assertThat(session.oldestActiveHandshakeNanos).isNotNull() + assertThat(session.oldestActiveHandshakeNanos) + .isEqualTo(session.lastSuccessfulHandshakeNanos) + } finally { + session.close() + socket.close() + } + + // then - the connection is over: neither active nor pending confirmation + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { !session.hasActiveForward }).isTrue() + assertThat(session.isClientDialed).isFalse() + assertThat(session.oldestActiveHandshakeNanos).isNull() + } + + @Test + fun `#forward reports a dialing client before its handshake`() { + // given - the forward handshake never completes (Layer A keeps retrying the pod forward), + // so the accepted socket is the only phase the session can report + every { + anyConstructed().forward(pod, listOf(remotePort)) + } throws IOException("connection reset") + val session = PodPortForwarder(client) { PodLiveness.RUNNING }.forward(pod, remotePort) + + val socket = Socket("127.0.0.1", session.localPort) + try { + // when / then - the dial is visible before any handshake: recovery must not read a + // connecting Guest as one that gave up + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { session.isClientDialed }).isTrue() + assertThat(session.oldestActiveHandshakeNanos).isNull() + assertThat(session.hasActiveForward).isFalse() + } finally { + socket.close() + session.close() + } + + // and it disappears with the dial + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { !session.isClientDialed }).isTrue() + } + + @Test + fun `#forward classifies a dial that ended before confirmation as failed`() { + // given - the pod ends the connection well within the confirmation threshold, like the + // 6.5-6.9s stale-link dials measured against the Guest's 6s transport timeout + val portForwardResult = mockk(relaxed = true) + every { + anyConstructed().forward(pod, listOf(remotePort)) + } returns portForwardResult + every { + portForwardResult.getInputStream(remotePort) + } returns eofAfter(TEST_CONFIRMATION_MS / 4) + every { portForwardResult.getOutboundStream(remotePort) } returns ByteArrayOutputStream() + val session = PodPortForwarder(client, confirmationMs = TEST_CONFIRMATION_MS) + .forward(pod, remotePort) + + try { + // when + Socket("127.0.0.1", session.localPort).use { + assertThat( + awaitTrue(EVENT_TIMEOUT_MS) { + session.lastFailedDialNanos != null + } + ).isTrue() + } + + // then + assertThat(session.failedDials).isEqualTo(1) + assertThat(session.lastLongLivedDialNanos).isNull() + } finally { + session.close() + } + } + + @Test + fun `#forward classifies a dial that outlived confirmation as long-lived`() { + // given - the pod holds the connection past the confirmation threshold, like a real session + val portForwardResult = mockk(relaxed = true) + every { + anyConstructed().forward(pod, listOf(remotePort)) + } returns portForwardResult + every { + portForwardResult.getInputStream(remotePort) + } returns eofAfter(TEST_CONFIRMATION_MS + LONG_LIVED_MARGIN_MS) + every { portForwardResult.getOutboundStream(remotePort) } returns ByteArrayOutputStream() + val session = PodPortForwarder(client, confirmationMs = TEST_CONFIRMATION_MS) + .forward(pod, remotePort) + + try { + // when + Socket("127.0.0.1", session.localPort).use { + assertThat( + awaitTrue(LONG_LIVED_DIAL_TIMEOUT_MS) { + session.lastLongLivedDialNanos != null + } + ).isTrue() + } + + // then - a long-lived dial is not evidence of a stale link + assertThat(session.failedDials).isZero() + assertThat(session.lastFailedDialNanos).isNull() + } finally { + session.close() + } + } + + @Test + fun `#forward does not count a connection that never handshook`() { + // given - the first connection fails its handshake while the pod is gone (terminal attempt), + // the second one handshakes and stays connected + val portForwardResult = mockk(relaxed = true) + every { portForwardResult.getInputStream(remotePort) } returns silentPodStream() + every { portForwardResult.getOutboundStream(remotePort) } returns ByteArrayOutputStream() + var podAlive = false + every { + anyConstructed().forward(pod, listOf(remotePort)) + } answers { + if (!podAlive) throw IOException("connection reset") + portForwardResult + } + val forwarder = PodPortForwarder(client) { + if (podAlive) PodLiveness.RUNNING else PodLiveness.GONE + } + val session = forwarder.forward(pod, remotePort) + + try { + runBlocking { delay(100.milliseconds) } + Socket("127.0.0.1", session.localPort).use { socket -> + socket.soTimeout = EVENT_TIMEOUT_MS.toInt() + assertThat(socket.inputStream.read()).isEqualTo(-1) + } + + // when - the Guest re-dials while the pod serves again + podAlive = true + val socket = Socket("127.0.0.1", session.localPort) + try { + // then - the count was never decremented by the connection that never handshook + assertThat(awaitTrue(EVENT_TIMEOUT_MS) { session.hasActiveForward }).isTrue() + } finally { + socket.close() + } + } finally { + session.close() + } + } + @Test fun `#check returns GONE when the pod is not found`() = runBlocking { // given @@ -459,15 +1195,34 @@ class PodPortForwarderTest { unmockkConstructor(CoreV1Api::class) } - private fun podWith(name: String, namespace: String): V1Pod { + /** Polls [condition] until it holds or [timeoutMs] elapses: the retry schedule is time-based. */ + private fun awaitTrue(timeoutMs: Long, condition: () -> Boolean): Boolean { + val deadline = System.currentTimeMillis() + timeoutMs + while (System.currentTimeMillis() < deadline) { + if (condition()) return true + runBlocking { delay(100.milliseconds) } + } + return condition() + } + + private fun podWith(name: String, namespace: String? = "test-ns", uid: String? = null): V1Pod { return V1Pod().apply { metadata = V1ObjectMeta().apply { this.name = name this.namespace = namespace + this.uid = uid } } } + /** A forward whose pod side stays silent: only closing the session ends the connection. */ + private fun silentForwardResult(): PortForward.PortForwardResult { + val portForwardResult = mockk(relaxed = true) + every { portForwardResult.getInputStream(remotePort) } returns silentPodStream() + every { portForwardResult.getOutboundStream(remotePort) } returns ByteArrayOutputStream() + return portForwardResult + } + private fun sendClientData(port: Int, data: String): Int { Socket("127.0.0.1", port).use { // client to server @@ -506,4 +1261,16 @@ class PodPortForwarderTest { throw IOException("broken pipe") } } + + /** The result a hanging open would produce if it ever finished: it never does, the bound wins. */ + private fun hangingOpenResult(): PortForward.PortForwardResult = + mockk(relaxed = true) + + /** A pod stream that reports EOF after [delayMs]: a dialed connection that ends by itself. */ + private fun eofAfter(delayMs: Long): InputStream = object : InputStream() { + override fun read(): Int { + Thread.sleep(delayMs) + return -1 + } + } } diff --git a/src/test/kotlin/com/redhat/devtools/gateway/server/RemoteIDEServerTest.kt b/src/test/kotlin/com/redhat/devtools/gateway/server/RemoteIDEServerTest.kt index 0badfde1..915dbae5 100644 --- a/src/test/kotlin/com/redhat/devtools/gateway/server/RemoteIDEServerTest.kt +++ b/src/test/kotlin/com/redhat/devtools/gateway/server/RemoteIDEServerTest.kt @@ -15,10 +15,15 @@ import com.redhat.devtools.gateway.DevSpacesContext import com.redhat.devtools.gateway.devworkspace.DevWorkspace import com.redhat.devtools.gateway.openshift.DevWorkspacePods import com.redhat.devtools.gateway.openshift.PodExecSession +import io.kubernetes.client.openapi.apis.CoreV1Api import io.kubernetes.client.openapi.models.V1Container +import io.kubernetes.client.openapi.models.V1ContainerPort import io.kubernetes.client.openapi.models.V1ObjectMeta import io.kubernetes.client.openapi.models.V1Pod +import io.kubernetes.client.openapi.models.V1PodCondition +import io.kubernetes.client.openapi.models.V1PodList import io.kubernetes.client.openapi.models.V1PodSpec +import io.kubernetes.client.openapi.models.V1PodStatus import io.mockk.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.runBlocking @@ -29,12 +34,16 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows import java.io.IOException +import java.time.OffsetDateTime class RemoteIDEServerTest { private lateinit var devSpacesContext: DevSpacesContext private lateinit var remoteIDEServer: RemoteIDEServer + /** The pod the workspace currently reports; a test swaps it to emulate a pod roll. */ + private var resolvedPod: V1Pod? = null + @BeforeEach fun beforeEach() { devSpacesContext = mockk(relaxed = true) @@ -58,9 +67,10 @@ class RemoteIDEServerTest { ) } } + resolvedPod = mockPod coEvery { - anyConstructed().findFirst(any(), any()) - } returns mockPod + anyConstructed().findFirstRunning(any(), any()) + } answers { resolvedPod } remoteIDEServer = spyk(RemoteIDEServer(devSpacesContext), recordPrivateCalls = true) } @@ -78,13 +88,78 @@ class RemoteIDEServerTest { // then verify { - anyConstructed().findFirst( + anyConstructed().findFirstRunning( "other-namespace", "controller.devfile.io/devworkspace_name=other-workspace" ) } } + @Test + fun `#findPod does not pick a terminating pod`() { + // given — a pod roll: the old pod is still listed first and reports Running, but it is + // terminating; only the newer pod is ready to serve. + unmockkConstructor(DevWorkspacePods::class) + mockkConstructor(CoreV1Api::class) + val terminatingPod = podWith( + podName = "terminating-pod", + creationTimestamp = OffsetDateTime.parse("2026-01-01T10:00:00Z"), + deletionTimestamp = OffsetDateTime.parse("2026-01-01T10:05:00Z"), + ) + val runningPod = podWith( + podName = "running-pod", + creationTimestamp = OffsetDateTime.parse("2026-01-01T10:04:00Z"), + ) + val listRequest = mockk() + every { listRequest.labelSelector(any()) } returns listRequest + every { + listRequest.execute() + } returns V1PodList().apply { items = listOf(terminatingPod, runningPod) } + every { anyConstructed().listNamespacedPod(any()) } returns listRequest + val workspace = mockk { + every { namespace } returns "test-namespace" + every { name } returns "test-workspace" + } + + // when + val server = RemoteIDEServer(devSpacesContext, workspace) + + // then — the running pod serves, the terminating one is skipped + assertThat(server.pod.metadata?.name).isEqualTo("running-pod") + } + + @Test + fun `#constructor throws when only a terminating pod matches`() { + // given — the workspace is not running (a terminating pod must not be used) + unmockkConstructor(DevWorkspacePods::class) + mockkConstructor(CoreV1Api::class) + val listRequest = mockk() + every { listRequest.labelSelector(any()) } returns listRequest + every { + listRequest.execute() + } returns V1PodList().apply { + items = listOf( + podWith( + podName = "terminating-pod", + deletionTimestamp = OffsetDateTime.parse("2026-01-01T10:05:00Z"), + ) + ) + } + every { anyConstructed().listNamespacedPod(any()) } returns listRequest + val workspace = mockk { + every { namespace } returns "test-namespace" + every { name } returns "test-workspace" + } + + // when + val exception = assertThrows { + RemoteIDEServer(devSpacesContext, workspace) + } + + // then + assertThat(exception.message).isEqualTo("DevWorkspace 'test-workspace' is not running.") + } + @AfterEach fun afterEach() { unmockkAll() @@ -113,10 +188,20 @@ class RemoteIDEServerTest { @Test fun `#waitServerReady fails fast when idea-server container is missing`() { - // given — refreshing the pod/container during the ready-wait finds no idea-server container - every { - remoteIDEServer["findContainer"]() - } throws ServerContainerNotFoundException("Workspace IDE container not found in the Pod: test-pod") + // given — refreshing the target during the ready-wait resolves a pod without an + // idea-server container (the workspace's container spec changed under a pod roll) + resolvedPod = V1Pod().apply { + metadata = V1ObjectMeta().apply { name = "test-pod" } + spec = V1PodSpec().apply { + containers = listOf( + V1Container().apply { + name = "test-container" + // no idea-server port: the container cannot serve the IDE + ports = listOf(V1ContainerPort().apply { name = "http" }) + } + ) + } + } // when val exception = assertThrows { @@ -129,6 +214,36 @@ class RemoteIDEServerTest { assertThat(exception.message).contains("Workspace IDE container not found") } + @Test + fun `#refreshPod swaps the pod and its container together`() { + // given — the IDE server moved to a new pod whose container is in a different state + resolvedPod = runningPod("new-pod", containerName = "new-container") + assertThat(remoteIDEServer.pod.metadata?.name).isEqualTo("test-pod") + assertThat(remoteIDEServer.ideContainerName).isEqualTo("test-container") + + // when + val found = remoteIDEServer.refreshPod() + + // then — the previous pod's container must not survive onto the new pod + assertThat(found).isTrue() + assertThat(remoteIDEServer.pod.metadata?.name).isEqualTo("new-pod") + assertThat(remoteIDEServer.ideContainerName).isEqualTo("new-container") + } + + @Test + fun `#refreshPod keeps the previous target when no pod is running`() { + // given — the workspace has no running, ready pod right now + resolvedPod = null + + // when + val found = remoteIDEServer.refreshPod() + + // then — nothing is swapped, the target stays what it was + assertThat(found).isFalse() + assertThat(remoteIDEServer.pod.metadata?.name).isEqualTo("test-pod") + assertThat(remoteIDEServer.ideContainerName).isEqualTo("test-container") + } + @Test fun `#waitServerReady should NOT reach timeout and throw if server status has a join link but no projects`() { // given @@ -228,6 +343,56 @@ class RemoteIDEServerTest { assertThat(result).isFalse } + private fun podWith( + podName: String, + creationTimestamp: OffsetDateTime? = null, + deletionTimestamp: OffsetDateTime? = null, + ): V1Pod { + return V1Pod().apply { + metadata = V1ObjectMeta().apply { + this.name = podName + this.creationTimestamp = creationTimestamp + this.deletionTimestamp = deletionTimestamp + } + spec = V1PodSpec().apply { + containers = listOf( + V1Container().apply { + this.name = "test-container" + ports = listOf( + mockk(relaxed = true) { + every { name } returns "idea-server" + } + ) + } + ) + } + status = V1PodStatus().apply { + phase = "Running" + conditions = listOf( + V1PodCondition().apply { + type = "Ready" + status = "True" + } + ) + } + } + } + + /** A running, ready pod that serves the IDE on [containerName]: what a pod roll produces. */ + private fun runningPod(podName: String, containerName: String): V1Pod = + podWith(podName).apply { + spec!!.containers = listOf( + V1Container().apply { + this.name = containerName + ports = listOf( + mockk(relaxed = true) { + every { name } returns "idea-server" + } + ) + } + ) + } + private fun remoteIDEServerStatus(joinLink: String? = null, projects: Array?): RemoteIDEServerStatus { return RemoteIDEServerStatus( joinLink,