Skip to content

Add status and start/stop buttons to recents view #243

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 8, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions src/main/kotlin/com/coder/gateway/WorkspaceParams.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ private const val IDE_PRODUCT_CODE = "ide_product_code"
private const val IDE_BUILD_NUMBER = "ide_build_number"
private const val IDE_PATH_ON_HOST = "ide_path_on_host"
private const val WEB_TERMINAL_LINK = "web_terminal_link"
private const val CONFIG_DIRECTORY = "config_directory"
private const val NAME = "name"

private val localTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm")

Expand All @@ -33,7 +35,9 @@ fun RecentWorkspaceConnection.toWorkspaceParams(): Map<String, String> {
PROJECT_PATH to this.projectPath!!,
IDE_PRODUCT_CODE to IntelliJPlatformProduct.fromProductCode(this.ideProductCode!!)!!.productCode,
IDE_BUILD_NUMBER to "${this.ideBuildNumber}",
WEB_TERMINAL_LINK to "${this.webTerminalLink}"
WEB_TERMINAL_LINK to "${this.webTerminalLink}",
CONFIG_DIRECTORY to "${this.configDirectory}",
NAME to "${this.name}"
)

if (!this.downloadSource.isNullOrBlank()) {
Expand Down Expand Up @@ -80,6 +84,19 @@ fun Map<String, String>.withWebTerminalLink(webTerminalLink: String): Map<String
return map
}

fun Map<String, String>.withConfigDirectory(dir: String): Map<String, String> {
val map = this.toMutableMap()
map[CONFIG_DIRECTORY] = dir
return map
}

fun Map<String, String>.withName(name: String): Map<String, String> {
val map = this.toMutableMap()
map[NAME] = name
return map
}


fun Map<String, String>.areCoderType(): Boolean {
return this[TYPE] == VALUE_FOR_TYPE && !this[CODER_WORKSPACE_HOSTNAME].isNullOrBlank() && !this[PROJECT_PATH].isNullOrBlank()
}
Expand Down Expand Up @@ -140,7 +157,9 @@ fun Map<String, String>.toRecentWorkspaceConnection(): RecentWorkspaceConnection
this[IDE_BUILD_NUMBER]!!,
this[IDE_DOWNLOAD_LINK]!!,
null,
this[WEB_TERMINAL_LINK]!!
this[WEB_TERMINAL_LINK]!!,
this[CONFIG_DIRECTORY]!!,
this[NAME]!!,
) else RecentWorkspaceConnection(
this.workspaceHostname(),
this.projectPath(),
Expand All @@ -149,6 +168,8 @@ fun Map<String, String>.toRecentWorkspaceConnection(): RecentWorkspaceConnection
this[IDE_BUILD_NUMBER]!!,
null,
this[IDE_PATH_ON_HOST],
this[WEB_TERMINAL_LINK]!!
this[WEB_TERMINAL_LINK]!!,
this[CONFIG_DIRECTORY]!!,
this[NAME]!!,
)
}
}
6 changes: 5 additions & 1 deletion src/main/kotlin/com/coder/gateway/icons/CoderIcons.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ object CoderIcons {

val OPEN_TERMINAL = IconLoader.getIcon("open_terminal.svg", javaClass)

val PENDING = IconLoader.getIcon("pending.svg", javaClass)
val RUNNING = IconLoader.getIcon("running.svg", javaClass)
val OFF = IconLoader.getIcon("off.svg", javaClass)

val HOME = IconLoader.getIcon("homeFolder.svg", javaClass)
val CREATE = IconLoader.getIcon("create.svg", javaClass)
val RUN = IconLoader.getIcon("run.svg", javaClass)
Expand Down Expand Up @@ -55,4 +59,4 @@ object CoderIcons {
val Y = IconLoader.getIcon("y.svg", javaClass)
val Z = IconLoader.getIcon("z.svg", javaClass)

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ data class CoderWorkspacesWizardModel(
var token: Pair<String, TokenSource>? = null,
var selectedWorkspace: WorkspaceAgentModel? = null,
var useExistingToken: Boolean = false,
var configDirectory: String = "",
)
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import com.intellij.openapi.components.BaseState
import com.intellij.util.xmlb.annotations.Attribute

class RecentWorkspaceConnection() : BaseState(), Comparable<RecentWorkspaceConnection> {
constructor(hostname: String, prjPath: String, openedAt: String, productCode: String, buildNumber: String, source: String?, idePath: String?, terminalLink: String) : this() {
constructor(hostname: String, prjPath: String, openedAt: String, productCode: String, buildNumber: String, source: String?, idePath: String?, terminalLink: String, config: String, name: String) : this() {
coderWorkspaceHostname = hostname
projectPath = prjPath
lastOpened = openedAt
Expand All @@ -13,6 +13,8 @@ class RecentWorkspaceConnection() : BaseState(), Comparable<RecentWorkspaceConne
downloadSource = source
idePathOnHost = idePath
webTerminalLink = terminalLink
configDirectory = config
this.name = name
}

@get:Attribute
Expand Down Expand Up @@ -40,6 +42,12 @@ class RecentWorkspaceConnection() : BaseState(), Comparable<RecentWorkspaceConne
@get:Attribute
var webTerminalLink by string()

@get:Attribute
var configDirectory by string()

@get:Attribute
var name by string()

override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
Expand Down Expand Up @@ -88,11 +96,11 @@ class RecentWorkspaceConnection() : BaseState(), Comparable<RecentWorkspaceConne
if (m != null && m != 0) return m

val n = other.idePathOnHost?.let { idePathOnHost?.compareTo(it) }
if (n != null && m != 0) return n
if (n != null && n != 0) return n

val o = other.webTerminalLink?.let { webTerminalLink?.compareTo(it) }
if (o != null && n != 0) return o
if (o != null && o != 0) return o

return 0
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ class RecentWorkspaceConnectionState : BaseState() {
var recentConnections by treeSet<RecentWorkspaceConnection>()

fun add(connection: RecentWorkspaceConnection): Boolean {
// if the item is already there but with a different last update timestamp, remove it
// If the item is already there but with a different last updated
// timestamp or config directory, remove it.
recentConnections.remove(connection)
// and add it again with the new timestamp
val result = recentConnections.add(connection)
if (result) incrementModificationCount()
return result
Expand All @@ -21,4 +21,4 @@ class RecentWorkspaceConnectionState : BaseState() {
if (result) incrementModificationCount()
return result
}
}
}
54 changes: 27 additions & 27 deletions src/main/kotlin/com/coder/gateway/models/WorkspaceAndAgentStatus.kt
Original file line number Diff line number Diff line change
@@ -1,44 +1,46 @@
package com.coder.gateway.models

import com.coder.gateway.icons.CoderIcons
import com.coder.gateway.sdk.v2.models.Workspace
import com.coder.gateway.sdk.v2.models.WorkspaceAgent
import com.coder.gateway.sdk.v2.models.WorkspaceAgentLifecycleState
import com.coder.gateway.sdk.v2.models.WorkspaceAgentStatus
import com.coder.gateway.sdk.v2.models.WorkspaceStatus
import com.intellij.ui.JBColor
import javax.swing.Icon

/**
* WorkspaceAndAgentStatus represents the combined status of a single agent and
* its workspace (or just the workspace if there are no agents).
*/
enum class WorkspaceAndAgentStatus(val label: String, val description: String) {
enum class WorkspaceAndAgentStatus(val icon: Icon, val label: String, val description: String) {
// Workspace states.
QUEUED("◍ Queued", "The workspace is queueing to start."),
STARTING("⦿ Starting", "The workspace is starting."),
FAILED("ⓧ Failed", "The workspace has failed to start."),
DELETING("⦸ Deleting", "The workspace is being deleted."),
DELETED("⦸ Deleted", "The workspace has been deleted."),
STOPPING("◍ Stopping", "The workspace is stopping."),
STOPPED("◍ Stopped", "The workspace has stopped."),
CANCELING("◍ Canceling action", "The workspace is being canceled."),
CANCELED("◍ Canceled action", "The workspace has been canceled."),
RUNNING("⦿ Running", "The workspace is running, waiting for agents."),
QUEUED(CoderIcons.PENDING, "Queued", "The workspace is queueing to start."),
STARTING(CoderIcons.PENDING, "Starting", "The workspace is starting."),
FAILED(CoderIcons.OFF, "Failed", "The workspace has failed to start."),
DELETING(CoderIcons.PENDING, "Deleting", "The workspace is being deleted."),
DELETED(CoderIcons.OFF, "Deleted", "The workspace has been deleted."),
STOPPING(CoderIcons.PENDING, "Stopping", "The workspace is stopping."),
STOPPED(CoderIcons.OFF, "Stopped", "The workspace has stopped."),
CANCELING(CoderIcons.PENDING, "Canceling action", "The workspace is being canceled."),
CANCELED(CoderIcons.OFF, "Canceled action", "The workspace has been canceled."),
RUNNING(CoderIcons.RUN, "Running", "The workspace is running, waiting for agents."),

// Agent states.
CONNECTING("⦿ Connecting", "The agent is connecting."),
DISCONNECTED("⦸ Disconnected", "The agent has disconnected."),
TIMEOUT("ⓧ Timeout", "The agent is taking longer than expected to connect."),
AGENT_STARTING("⦿ Starting", "The startup script is running."),
AGENT_STARTING_READY("⦿ Starting", "The startup script is still running but the agent is ready to accept connections."),
CREATED("⦿ Created", "The agent has been created."),
START_ERROR("◍ Started with error", "The agent is ready but the startup script errored."),
START_TIMEOUT("◍ Starting", "The startup script is taking longer than expected."),
START_TIMEOUT_READY("◍ Starting", "The startup script is taking longer than expected but the agent is ready to accept connections."),
SHUTTING_DOWN("◍ Shutting down", "The agent is shutting down."),
SHUTDOWN_ERROR("⦸ Shutdown with error", "The agent shut down but the shutdown script errored."),
SHUTDOWN_TIMEOUT("⦸ Shutting down", "The shutdown script is taking longer than expected."),
OFF("⦸ Off", "The agent has shut down."),
READY("⦿ Ready", "The agent is ready to accept connections.");
CONNECTING(CoderIcons.PENDING, "Connecting", "The agent is connecting."),
DISCONNECTED(CoderIcons.OFF, "Disconnected", "The agent has disconnected."),
TIMEOUT(CoderIcons.PENDING, "Timeout", "The agent is taking longer than expected to connect."),
AGENT_STARTING(CoderIcons.PENDING, "Starting", "The startup script is running."),
AGENT_STARTING_READY(CoderIcons.RUNNING, "Starting", "The startup script is still running but the agent is ready to accept connections."),
CREATED(CoderIcons.PENDING, "Created", "The agent has been created."),
START_ERROR(CoderIcons.RUNNING, "Started with error", "The agent is ready but the startup script errored."),
START_TIMEOUT(CoderIcons.PENDING, "Starting", "The startup script is taking longer than expected."),
START_TIMEOUT_READY(CoderIcons.RUNNING, "Starting", "The startup script is taking longer than expected but the agent is ready to accept connections."),
SHUTTING_DOWN(CoderIcons.PENDING, "Shutting down", "The agent is shutting down."),
SHUTDOWN_ERROR(CoderIcons.OFF, "Shutdown with error", "The agent shut down but the shutdown script errored."),
SHUTDOWN_TIMEOUT(CoderIcons.OFF, "Shutting down", "The shutdown script is taking longer than expected."),
OFF(CoderIcons.OFF, "Off", "The agent has shut down."),
READY(CoderIcons.RUNNING, "Ready", "The agent is ready to accept connections.");

fun statusColor(): JBColor = when (this) {
READY, AGENT_STARTING_READY, START_TIMEOUT_READY -> JBColor.GREEN
Expand Down Expand Up @@ -100,7 +102,5 @@ enum class WorkspaceAndAgentStatus(val label: String, val description: String) {
WorkspaceStatus.DELETING -> DELETING
WorkspaceStatus.DELETED -> DELETED
}

fun from(str: String) = WorkspaceAndAgentStatus.values().first { it.label.contains(str, true) }
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/com/coder/gateway/sdk/CoderCLIManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class CoderCLIManager @JvmOverloads constructor(
) {
var remoteBinaryURL: URL
var localBinaryPath: Path
private var coderConfigPath: Path
var coderConfigPath: Path

init {
val binaryName = getCoderCLIForOS(getOS(), getArch())
Expand Down
55 changes: 34 additions & 21 deletions src/main/kotlin/com/coder/gateway/sdk/CoderRestClientService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,30 @@ import java.util.UUID
class CoderRestClientService {
var isReady: Boolean = false
private set
private lateinit var httpClient: OkHttpClient
private lateinit var retroRestClient: CoderV2RestFacade
private lateinit var sessionToken: String
lateinit var coderURL: URL
lateinit var me: User
lateinit var buildVersion: String
lateinit var client: CoderRestClient

/**
* This must be called before anything else. It will authenticate with coder and retrieve a session token
* This must be called before anything else. It will authenticate and load
* information about the current user and the build version.
*
* @throws [AuthenticationResponseException] if authentication failed.
*/
fun initClientSession(url: URL, token: String): User {
client = CoderRestClient(url, token)
me = client.me()
buildVersion = client.buildInfo().version
isReady = true
return me
}
}

class CoderRestClient(var url: URL, private var token: String) {
private var httpClient: OkHttpClient
private var retroRestClient: CoderV2RestFacade

init {
val gson: Gson = GsonBuilder().registerTypeAdapter(Instant::class.java, InstantConverter()).setPrettyPrinting().create()
val pluginVersion = PluginManagerCore.getPlugin(PluginId.getId("com.coder.gateway"))!! // this is the id from the plugin.xml

Expand All @@ -54,18 +66,19 @@ class CoderRestClientService {
.build()

retroRestClient = Retrofit.Builder().baseUrl(url.toString()).client(httpClient).addConverterFactory(GsonConverterFactory.create(gson)).build().create(CoderV2RestFacade::class.java)
}

/**
* Retrieve the current user.
* @throws [AuthenticationResponseException] if authentication failed.
*/
fun me(): User {
val userResponse = retroRestClient.me().execute()
if (!userResponse.isSuccessful) {
throw AuthenticationResponseException("Could not retrieve information about logged user:${userResponse.code()}, reason: ${userResponse.message()}")
throw AuthenticationResponseException("Could not retrieve information about logged user:${userResponse.code()}, reason: ${userResponse.message().ifBlank { "no reason provided" }}")
}

coderURL = url
sessionToken = token
me = userResponse.body()!!
buildVersion = buildInfo().version
isReady = true
return me
return userResponse.body()!!
}

/**
Expand All @@ -75,24 +88,24 @@ class CoderRestClientService {
fun workspaces(): List<Workspace> {
val workspacesResponse = retroRestClient.workspaces("owner:me").execute()
if (!workspacesResponse.isSuccessful) {
throw WorkspaceResponseException("Could not retrieve Coder Workspaces:${workspacesResponse.code()}, reason: ${workspacesResponse.message()}")
throw WorkspaceResponseException("Could not retrieve Coder Workspaces:${workspacesResponse.code()}, reason: ${workspacesResponse.message().ifBlank { "no reason provided" }}")
}

return workspacesResponse.body()!!.workspaces
}

private fun buildInfo(): BuildInfo {
fun buildInfo(): BuildInfo {
val buildInfoResponse = retroRestClient.buildInfo().execute()
if (!buildInfoResponse.isSuccessful) {
throw java.lang.IllegalStateException("Could not retrieve build information for Coder instance $coderURL, reason:${buildInfoResponse.message()}")
throw java.lang.IllegalStateException("Could not retrieve build information for Coder instance $url, reason:${buildInfoResponse.message().ifBlank { "no reason provided" }}")
}
return buildInfoResponse.body()!!
}

private fun template(templateID: UUID): Template {
fun template(templateID: UUID): Template {
val templateResponse = retroRestClient.template(templateID).execute()
if (!templateResponse.isSuccessful) {
throw TemplateResponseException("Failed to retrieve template with id: $templateID, reason: ${templateResponse.message()}")
throw TemplateResponseException("Failed to retrieve template with id: $templateID, reason: ${templateResponse.message().ifBlank { "no reason provided" }}")
}
return templateResponse.body()!!
}
Expand All @@ -101,7 +114,7 @@ class CoderRestClientService {
val buildRequest = CreateWorkspaceBuildRequest(null, WorkspaceTransition.START, null, null, null, null)
val buildResponse = retroRestClient.createWorkspaceBuild(workspaceID, buildRequest).execute()
if (buildResponse.code() != HTTP_CREATED) {
throw WorkspaceResponseException("Failed to build workspace ${workspaceName}: ${buildResponse.code()}, reason: ${buildResponse.message()}")
throw WorkspaceResponseException("Failed to build workspace ${workspaceName}: ${buildResponse.code()}, reason: ${buildResponse.message().ifBlank { "no reason provided" }}")
}

return buildResponse.body()!!
Expand All @@ -111,7 +124,7 @@ class CoderRestClientService {
val buildRequest = CreateWorkspaceBuildRequest(null, WorkspaceTransition.STOP, null, null, null, null)
val buildResponse = retroRestClient.createWorkspaceBuild(workspaceID, buildRequest).execute()
if (buildResponse.code() != HTTP_CREATED) {
throw WorkspaceResponseException("Failed to stop workspace ${workspaceName}: ${buildResponse.code()}, reason: ${buildResponse.message()}")
throw WorkspaceResponseException("Failed to stop workspace ${workspaceName}: ${buildResponse.code()}, reason: ${buildResponse.message().ifBlank { "no reason provided" }}")
}

return buildResponse.body()!!
Expand All @@ -123,9 +136,9 @@ class CoderRestClientService {
val buildRequest = CreateWorkspaceBuildRequest(template.activeVersionID, lastWorkspaceTransition, null, null, null, null)
val buildResponse = retroRestClient.createWorkspaceBuild(workspaceID, buildRequest).execute()
if (buildResponse.code() != HTTP_CREATED) {
throw WorkspaceResponseException("Failed to update workspace ${workspaceName}: ${buildResponse.code()}, reason: ${buildResponse.message()}")
throw WorkspaceResponseException("Failed to update workspace ${workspaceName}: ${buildResponse.code()}, reason: ${buildResponse.message().ifBlank { "no reason provided" }}")
}

return buildResponse.body()!!
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ import javax.swing.Icon

@Service(Service.Level.APP)
class TemplateIconDownloader {
private val coderClient: CoderRestClientService = service()
private val clientService: CoderRestClientService = service()
private val cache = mutableMapOf<Pair<String, String>, Icon>()

fun load(path: String, workspaceName: String): Icon {
var url: URL? = null
if (path.startsWith("http")) {
url = path.toURL()
} else if (!path.contains(":") && !path.contains("//")) {
url = coderClient.coderURL.withPath(path)
url = clientService.client.url.withPath(path)
}

if (url != null) {
Expand Down Expand Up @@ -115,4 +115,4 @@ class TemplateIconDownloader {
else -> CoderIcons.UNKNOWN
}

}
}
Loading