diff --git a/.gitignore b/.gitignore index 4e4ac988..22a70cb6 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,13 @@ # VM crash logs hs_err_pid* +.hprof # IntelliJ -.idea/ \ No newline at end of file +.idea/ + +# Docker Kotlin +/docs/ + +# Kotlin +.kotlin/ \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index db808413..90ab2f3d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,8 @@ kotlin.code.style=official kotlin.mpp.stability.nowarn=true org.gradle.caching=true org.gradle.parallel=true -org.gradle.unsafe.configuration-cache=true +org.gradle.configuration-cache=true +org.gradle.configuration-cache.parallel=true kotlin.mpp.applyDefaultHierarchyTemplate=false POM_NAME=docker-kotlin diff --git a/src/commonMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.kt b/src/commonMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.kt index dcc97641..da1d5bd6 100644 --- a/src/commonMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.kt +++ b/src/commonMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.kt @@ -1,13 +1,46 @@ package me.devnatan.dockerkt.resource.container +import io.ktor.client.HttpClient +import io.ktor.client.call.body +import io.ktor.client.request.delete +import io.ktor.client.request.get +import io.ktor.client.request.parameter +import io.ktor.client.request.post +import io.ktor.client.request.prepareGet +import io.ktor.client.request.preparePost +import io.ktor.client.request.put +import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsChannel +import io.ktor.client.statement.readRawBytes +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.util.decodeBase64Bytes +import io.ktor.utils.io.ByteReadChannel +import io.ktor.utils.io.readUTF8Line import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.flow +import kotlinx.io.files.Path +import kotlinx.serialization.json.Json import me.devnatan.dockerkt.DockerResponseException +import me.devnatan.dockerkt.io.FileSystemUtils +import me.devnatan.dockerkt.io.TarEntry +import me.devnatan.dockerkt.io.TarOperations +import me.devnatan.dockerkt.io.TarUtils +import me.devnatan.dockerkt.io.collectStream +import me.devnatan.dockerkt.io.collectStreamDemuxed +import me.devnatan.dockerkt.io.readStream +import me.devnatan.dockerkt.io.requestCatching import me.devnatan.dockerkt.models.Frame import me.devnatan.dockerkt.models.ResizeTTYOptions +import me.devnatan.dockerkt.models.Stream import me.devnatan.dockerkt.models.container.Container +import me.devnatan.dockerkt.models.container.ContainerArchiveInfo import me.devnatan.dockerkt.models.container.ContainerCopyOptions import me.devnatan.dockerkt.models.container.ContainerCopyResult import me.devnatan.dockerkt.models.container.ContainerCreateOptions +import me.devnatan.dockerkt.models.container.ContainerCreateResult import me.devnatan.dockerkt.models.container.ContainerListOptions import me.devnatan.dockerkt.models.container.ContainerLogsOptions import me.devnatan.dockerkt.models.container.ContainerLogsResult @@ -19,13 +52,26 @@ import me.devnatan.dockerkt.models.container.ContainerWaitResult import me.devnatan.dockerkt.resource.image.ImageNotFoundException import kotlin.time.Duration -public expect class ContainerResource { +private const val BasePath = "/containers" + +public class ContainerResource internal constructor( + private val httpClient: HttpClient, + private val json: Json, +) { /** * Returns a list of all containers. * * @param options Options to customize the listing result. */ - public suspend fun list(options: ContainerListOptions = ContainerListOptions(all = true)): List + public suspend fun list(options: ContainerListOptions = ContainerListOptions(all = true)): List = + requestCatching { + httpClient.get("$BasePath/json") { + parameter("all", options.all) + parameter("limit", options.limit) + parameter("size", options.size) + parameter("filters", options.filters?.let(json::encodeToString)) + } + }.body() /** * Creates a new container. @@ -34,7 +80,28 @@ public expect class ContainerResource { * @throws ImageNotFoundException If the image specified does not exist or isn't pulled. * @throws ContainerAlreadyExistsException If a container with the same name already exists. */ - public suspend fun create(options: ContainerCreateOptions): String + public suspend fun create(options: ContainerCreateOptions): String { + requireNotNull(options.image) { "Container image is required" } + + val result = + requestCatching( + HttpStatusCode.NotFound to { exception -> ImageNotFoundException(exception, options.image.orEmpty()) }, + HttpStatusCode.Conflict to { exception -> + ContainerAlreadyExistsException( + exception, + options.name.orEmpty(), + ) + }, + ) { + httpClient.post("$BasePath/create") { + parameter("name", options.name) + setBody(options) + } + }.body() + + result.warnings.forEach { warn -> println("Warning from Docker API: $warn") } + return result.id + } /** * Removes a container. @@ -47,7 +114,17 @@ public expect class ContainerResource { public suspend fun remove( container: String, options: ContainerRemoveOptions = ContainerRemoveOptions(), - ) + ): Unit = + requestCatching( + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + HttpStatusCode.Conflict to { cause -> ContainerRemoveConflictException(cause, container) }, + ) { + httpClient.delete("$BasePath/$container") { + parameter("v", options.removeAnonymousVolumes) + parameter("force", options.force) + parameter("link", options.unlink) + } + } /** * Returns low-level information about a container. @@ -58,7 +135,14 @@ public expect class ContainerResource { public suspend fun inspect( container: String, size: Boolean = false, - ): Container + ): Container = + requestCatching( + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + ) { + httpClient.get("$BasePath/$container/json") { + parameter("size", size) + } + }.body() /** * Starts a container. @@ -71,7 +155,15 @@ public expect class ContainerResource { public suspend fun start( container: String, detachKeys: String? = null, - ) + ): Unit = + requestCatching( + HttpStatusCode.NotModified to { cause -> ContainerAlreadyStartedException(cause, container) }, + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + ) { + httpClient.post("$BasePath/$container/start") { + parameter("detachKeys", detachKeys) + } + } /** * Stops a container. @@ -82,7 +174,15 @@ public expect class ContainerResource { public suspend fun stop( container: String, timeout: Duration? = null, - ) + ): Unit = + requestCatching( + HttpStatusCode.NotModified to { cause -> ContainerAlreadyStoppedException(cause, container) }, + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + ) { + httpClient.post("$BasePath/$container/stop") { + parameter("t", timeout?.inWholeSeconds) + } + } /** * Restarts a container. @@ -93,7 +193,14 @@ public expect class ContainerResource { public suspend fun restart( container: String, timeout: Duration? = null, - ) + ): Unit = + requestCatching( + HttpStatusCode.NotFound to { exception -> ContainerNotFoundException(exception, container) }, + ) { + httpClient.post("$BasePath/$container/restart") { + parameter("t", timeout) + } + } /** * Kills a container. @@ -104,7 +211,15 @@ public expect class ContainerResource { public suspend fun kill( container: String, signal: String? = null, - ) + ): Unit = + requestCatching( + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + HttpStatusCode.Conflict to { cause -> ContainerNotRunningException(cause, container) }, + ) { + httpClient.post("$BasePath/$container/kill") { + parameter("signal", signal) + } + } /** * Renames a container. @@ -115,7 +230,15 @@ public expect class ContainerResource { public suspend fun rename( container: String, newName: String, - ) + ): Unit = + requestCatching( + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + HttpStatusCode.Conflict to { cause -> ContainerRenameConflictException(cause, container, newName) }, + ) { + httpClient.post("$BasePath/$container/rename") { + parameter("name", newName) + } + } /** * Pauses a container. @@ -123,7 +246,12 @@ public expect class ContainerResource { * @param container The container id to pause. * @see unpause */ - public suspend fun pause(container: String) + public suspend fun pause(container: String): Unit = + requestCatching( + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + ) { + httpClient.post("$BasePath/$container/pause") + } /** * Resumes a container which has been paused. @@ -131,7 +259,12 @@ public expect class ContainerResource { * @param container The container id to unpause. * @see pause */ - public suspend fun unpause(container: String) + public suspend fun unpause(container: String): Unit = + requestCatching( + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + ) { + httpClient.post("$BasePath/$container/unpause") + } /** * Resizes the TTY for a container. @@ -144,19 +277,56 @@ public expect class ContainerResource { public suspend fun resizeTTY( container: String, options: ResizeTTYOptions = ResizeTTYOptions(), - ) + ): Unit = + requestCatching( + HttpStatusCode.NotFound to { cause -> + ContainerNotFoundException( + cause, + container, + ) + }, + ) { + httpClient.post("$BasePath/$container/resize") { + setBody(options) + } + } // TODO documentation - public fun attach(container: String): Flow + public fun attach(container: String): Flow = + channelFlow { + httpClient + .preparePost("$BasePath/$container/attach") { + parameter("stream", "true") + parameter("stdin", "true") + parameter("stdout", "true") + parameter("stderr", "true") + }.execute { response -> + val channel = response.body() + while (!channel.isClosedForRead) { + val line = channel.readUTF8Line() ?: break + + // TODO handle stream type + send(Frame(line, line.length, Stream.StdOut)) + } + } + } // TODO documentation public suspend fun wait( container: String, condition: String? = null, - ): ContainerWaitResult + ): ContainerWaitResult = + httpClient + .post("$BasePath/$container/wait") { + parameter("condition", condition) + }.body() // TODO documentation - public suspend fun prune(filters: ContainerPruneFilters = ContainerPruneFilters()): ContainerPruneResult + public suspend fun prune(filters: ContainerPruneFilters = ContainerPruneFilters()): ContainerPruneResult = + httpClient + .post("$BasePath/prune") { + parameter("filters", json.encodeToString(filters)) + }.body() /** * Get logs from a container. @@ -181,7 +351,95 @@ public expect class ContainerResource { public suspend fun logs( container: String, options: ContainerLogsOptions = ContainerLogsOptions(), - ): ContainerLogsResult + ): ContainerLogsResult = + if (options.follow ?: false) { + logsStreaming(container, options) + } else { + logsComplete(container, options) + } + + private suspend fun logsComplete( + container: String, + options: ContainerLogsOptions, + ): ContainerLogsResult = + requestCatching( + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + ) { + val response = + httpClient.get("$BasePath/$container/logs") { + parameter("stdout", options.stdout) + parameter("stderr", options.stderr) + parameter("timestamps", options.showTimestamps) + parameter("since", options.since) + parameter("until", options.until) + parameter("tail", options.tail) + parameter("follow", false) + } + + val channel = response.bodyAsChannel() + val multiplexed = response.headers["Content-Type"] == "application/vnd.docker.multiplexed-stream" + + return if (options.demux) { + val (stdout, stderr) = collectStreamDemuxed(channel, multiplexed) + ContainerLogsResult.CompleteDemuxed(stdout, stderr) + } else { + val content = collectStream(channel, multiplexed) + ContainerLogsResult.Complete(content) + } + } + + private fun logsStreaming( + container: String, + options: ContainerLogsOptions, + ): ContainerLogsResult { + val framesFlow = + channelFlow { + requestCatching( + HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, + ) { + httpClient + .prepareGet("$BasePath/$container/logs") { + parameter("stdout", options.stdout) + parameter("stderr", options.stderr) + parameter("timestamps", options.showTimestamps) + parameter("since", options.since) + parameter("until", options.until) + parameter("tail", options.tail) + parameter("follow", true) + }.execute { httpResponse -> + val channel = httpResponse.bodyAsChannel() + val multiplexed = + httpResponse.headers["Content-Type"] == "application/vnd.docker.multiplexed-stream" + + readStream(channel, multiplexed) { frame -> + send(frame) + } + } + } + } + + return if (options.demux) { + val stdoutFlow = + flow { + framesFlow.collect { frame -> + if (frame.stream == Stream.StdOut) { + emit(frame.value) + } + } + } + val stderrFlow = + flow { + framesFlow.collect { frame -> + if (frame.stream == Stream.StdErr) { + emit(frame.value) + } + } + } + ContainerLogsResult.StreamDemuxed(stdoutFlow, stderrFlow) + } else { + ContainerLogsResult.Stream(framesFlow) + } + } /** * Copy files or folders from a container to the local filesystem. @@ -198,7 +456,32 @@ public expect class ContainerResource { public suspend fun copyFrom( container: String, sourcePath: String, - ): ContainerCopyResult + ): ContainerCopyResult = + requestCatching( + HttpStatusCode.NotFound to { exception -> + if (exception.message?.contains("file") == true) { + ArchiveNotFoundException(exception, container, sourcePath) + } else { + ContainerNotFoundException(exception, container) + } + }, + ) { + val response = + httpClient.get("$BasePath/$container/archive") { + parameter("path", sourcePath) + } + + val archiveData = response.readRawBytes() + + val statHeader = response.headers["X-Docker-Container-Path-Stat"] + val stat = + statHeader?.let { header -> + val decoded = header.decodeBase64Bytes() + json.decodeFromString(decoded.decodeToString()) + } + + ContainerCopyResult(archiveData, stat) + } /** * Copy files or folders from the local filesystem to a container. @@ -218,7 +501,22 @@ public expect class ContainerResource { destinationPath: String, tarArchive: ByteArray, options: ContainerCopyOptions = ContainerCopyOptions(path = destinationPath), - ) + ): Unit = + requestCatching( + HttpStatusCode.NotFound to { exception -> ContainerNotFoundException(exception, container) }, + HttpStatusCode.BadRequest to { exception -> + IllegalArgumentException("Invalid destination path: $destinationPath", exception) + }, + ) { + httpClient.put("$BasePath/$container/archive") { + parameter("path", destinationPath) + parameter("noOverwriteDirNonDir", options.noOverwriteDirNonDir.toString()) + parameter("copyUIDGID", options.copyUIDGID.toString()) + + setBody(tarArchive) + contentType(ContentType.Application.OctetStream) + } + } /** * Copy a single file from the local filesystem to a container. @@ -238,7 +536,19 @@ public expect class ContainerResource { sourcePath: String, destinationPath: String, options: ContainerCopyOptions = ContainerCopyOptions(path = destinationPath), - ) + ) { + val path = Path(sourcePath) + if (!FileSystemUtils.exists(path)) { + throw IllegalArgumentException("Source file not found: $sourcePath") + } + + if (FileSystemUtils.isDirectory(path)) { + throw IllegalArgumentException("Source is a directory, use copyDirectoryTo instead: $sourcePath") + } + + val tarArchive = TarOperations.createTarFromFile(path) + copyTo(container, destinationPath, tarArchive, options) + } /** * Copy a file from a container to the local filesystem. @@ -256,7 +566,10 @@ public expect class ContainerResource { container: String, sourcePath: String, destinationPath: String, - ) + ) { + val result = copyFrom(container, sourcePath) + TarOperations.extractTar(result.archiveData, Path(destinationPath)) + } /** * Copy a directory from a container to the local filesystem. @@ -271,7 +584,10 @@ public expect class ContainerResource { container: String, sourcePath: String, destinationPath: String, - ) + ) { + val result = copyFrom(container, sourcePath) + TarOperations.extractTar(result.archiveData, Path(destinationPath)) + } /** * Copy a directory from the local filesystem to a container. @@ -288,5 +604,15 @@ public expect class ContainerResource { sourcePath: String, destinationPath: String, options: ContainerCopyOptions = ContainerCopyOptions(path = destinationPath), - ) + ) { + val path = Path(sourcePath) + if (!FileSystemUtils.exists(path) || !FileSystemUtils.isDirectory(path)) { + throw IllegalArgumentException("Source directory not found: $sourcePath") + } + + val entries = mutableListOf() + TarOperations.collectDirectoryContents(path, "", entries) + val tarArchive = TarUtils.createTarArchive(entries) + copyTo(container, destinationPath, tarArchive, options) + } } diff --git a/src/jvmMain/kotlin/me/devnatan/dockerkt/DockerClient.jvm.kt b/src/jvmMain/kotlin/me/devnatan/dockerkt/DockerClient.jvm.kt index 733e3e24..459e49e0 100644 --- a/src/jvmMain/kotlin/me/devnatan/dockerkt/DockerClient.jvm.kt +++ b/src/jvmMain/kotlin/me/devnatan/dockerkt/DockerClient.jvm.kt @@ -26,25 +26,12 @@ public actual class DockerClient public actual constructor( public actual val json: Json get() = DockerKotlinJson public actual val httpClient: HttpClient = createHttpClient(this) - @get:JvmName("images") public actual val images: ImageResource = ImageResource(httpClient, json) - - @get:JvmName("exec") public actual val exec: ExecResource = ExecResource(httpClient) - - @get:JvmName("containers") - public actual val containers: ContainerResource = ContainerResource(this, json, httpClient) - - @get:JvmName("networks") + public actual val containers: ContainerResource = ContainerResource(httpClient, json) public actual val networks: NetworkResource = NetworkResource(httpClient, json) - - @get:JvmName("volumes") public actual val volumes: VolumeResource = VolumeResource(httpClient, json) - - @get:JvmName("secrets") public actual val secrets: SecretResource = SecretResource(httpClient, json) - - @get:JvmName("system") public actual val system: SystemResource = SystemResource(httpClient, json) public actual fun close() { diff --git a/src/jvmMain/kotlin/me/devnatan/dockerkt/io/Flow.jvm.kt b/src/jvmMain/kotlin/me/devnatan/dockerkt/io/Flow.jvm.kt deleted file mode 100644 index b5df4f34..00000000 --- a/src/jvmMain/kotlin/me/devnatan/dockerkt/io/Flow.jvm.kt +++ /dev/null @@ -1,52 +0,0 @@ -package me.devnatan.dockerkt.io - -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.cancel -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.catch -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.onCompletion -import kotlinx.coroutines.flow.onEach -import kotlinx.coroutines.flow.onStart -import me.devnatan.dockerkt.Closeable - -public fun interface DockerClientFrameListener { - public fun onEach(value: T) - - public fun onStart(): Unit = Unit - - public fun onError(cause: Throwable): Unit = Unit - - public fun onComplete(error: Throwable?): Unit = Unit -} - -internal class InternalDockerClientFrameListener internal constructor() : Closeable { - private val coroutineScope: CoroutineScope = CoroutineScope(Dispatchers.Default) - private var error: Throwable? = null - - fun start( - flow: Flow, - callback: DockerClientFrameListener, - ) { - flow - .onStart { callback.onStart() } - .onCompletion { exception -> - this@InternalDockerClientFrameListener.error = exception - callback.onComplete(exception) - }.onEach(callback::onEach) - .catch { exception -> - this@InternalDockerClientFrameListener.error = exception - callback.onError(exception) - }.launchIn(coroutineScope) - } - - override fun close() { - val exception = - error?.let { cause -> - CancellationException("An error occurred while consuming flow.", cause) - } - coroutineScope.cancel(exception) - } -} diff --git a/src/jvmMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.jvm.kt b/src/jvmMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.jvm.kt deleted file mode 100644 index 8a22cf0b..00000000 --- a/src/jvmMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.jvm.kt +++ /dev/null @@ -1,742 +0,0 @@ -package me.devnatan.dockerkt.resource.container - -import io.ktor.client.HttpClient -import io.ktor.client.call.body -import io.ktor.client.request.delete -import io.ktor.client.request.get -import io.ktor.client.request.parameter -import io.ktor.client.request.post -import io.ktor.client.request.prepareGet -import io.ktor.client.request.preparePost -import io.ktor.client.request.put -import io.ktor.client.request.setBody -import io.ktor.client.statement.bodyAsChannel -import io.ktor.client.statement.readRawBytes -import io.ktor.http.ContentType -import io.ktor.http.HttpStatusCode -import io.ktor.http.contentType -import io.ktor.util.decodeBase64Bytes -import io.ktor.utils.io.ByteReadChannel -import io.ktor.utils.io.readUTF8Line -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.async -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.channelFlow -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.future.asCompletableFuture -import kotlinx.io.files.Path -import kotlinx.serialization.json.Json -import me.devnatan.dockerkt.DockerResponseException -import me.devnatan.dockerkt.io.FileSystemUtils -import me.devnatan.dockerkt.io.TarEntry -import me.devnatan.dockerkt.io.TarOperations -import me.devnatan.dockerkt.io.TarUtils -import me.devnatan.dockerkt.io.collectStream -import me.devnatan.dockerkt.io.collectStreamDemuxed -import me.devnatan.dockerkt.io.readStream -import me.devnatan.dockerkt.io.requestCatching -import me.devnatan.dockerkt.models.Frame -import me.devnatan.dockerkt.models.ResizeTTYOptions -import me.devnatan.dockerkt.models.Stream -import me.devnatan.dockerkt.models.container.Container -import me.devnatan.dockerkt.models.container.ContainerArchiveInfo -import me.devnatan.dockerkt.models.container.ContainerCopyOptions -import me.devnatan.dockerkt.models.container.ContainerCopyResult -import me.devnatan.dockerkt.models.container.ContainerCreateOptions -import me.devnatan.dockerkt.models.container.ContainerCreateResult -import me.devnatan.dockerkt.models.container.ContainerListOptions -import me.devnatan.dockerkt.models.container.ContainerLogsOptions -import me.devnatan.dockerkt.models.container.ContainerLogsResult -import me.devnatan.dockerkt.models.container.ContainerPruneFilters -import me.devnatan.dockerkt.models.container.ContainerPruneResult -import me.devnatan.dockerkt.models.container.ContainerRemoveOptions -import me.devnatan.dockerkt.models.container.ContainerSummary -import me.devnatan.dockerkt.models.container.ContainerWaitResult -import me.devnatan.dockerkt.resource.image.ImageNotFoundException -import java.util.concurrent.CompletableFuture -import kotlin.time.Duration -import kotlin.time.DurationUnit -import kotlin.time.toDuration - -public const val BasePath: String = "/containers" - -public actual class ContainerResource( - private val coroutineScope: CoroutineScope, - private val json: Json, - private val httpClient: HttpClient, -) { - /** - * Returns a list of all containers. - * - * @param options Options to customize the listing result. - */ - @JvmSynthetic - public actual suspend fun list(options: ContainerListOptions): List = - requestCatching { - httpClient.get("$BasePath/json") { - parameter("all", options.all) - parameter("limit", options.limit) - parameter("size", options.size) - parameter("filters", options.filters?.let(json::encodeToString)) - } - }.body() - - /** - * Returns a list of all containers. - * - * @param options Options to customize the listing result. - */ - @JvmOverloads - public fun listAsync(options: ContainerListOptions = ContainerListOptions(all = true)): CompletableFuture> = - coroutineScope.async { list(options) }.asCompletableFuture() - - /** - * Creates a new container. - * - * @param options Options to customize the container creation. - * @throws ImageNotFoundException If the image specified does not exist or isn't pulled. - * @throws ContainerAlreadyExistsException If a container with the same name already exists. - */ - @JvmSynthetic - public actual suspend fun create(options: ContainerCreateOptions): String { - requireNotNull(options.image) { "Container image is required" } - - val result = - requestCatching( - HttpStatusCode.NotFound to { exception -> ImageNotFoundException(exception, options.image.orEmpty()) }, - HttpStatusCode.Conflict to { exception -> - ContainerAlreadyExistsException( - exception, - options.name.orEmpty(), - ) - }, - ) { - httpClient.post("$BasePath/create") { - parameter("name", options.name) - setBody(options) - } - }.body() - - result.warnings.forEach { warn -> println("Warning from Docker API: $warn") } - return result.id - } - - /** - * Creates a new container. - * - * @param options Options to customize the container creation. - * @throws ImageNotFoundException If the image specified does not exist or isn't pulled. - * @throws ContainerAlreadyExistsException If a container with the same name already exists. - */ - public fun createAsync(options: ContainerCreateOptions): CompletableFuture = - coroutineScope - .async { - create(options) - }.asCompletableFuture() - - /** - * Removes a container. - * - * @param container The container id to remove. - * @param options Removal options. - * @throws ContainerNotFoundException If the container is not found for the specified id. - * @throws ContainerRemoveConflictException When trying to remove an active container without the `force` option. - */ - @JvmSynthetic - public actual suspend fun remove( - container: String, - options: ContainerRemoveOptions, - ): Unit = - requestCatching( - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - HttpStatusCode.Conflict to { cause -> ContainerRemoveConflictException(cause, container) }, - ) { - httpClient.delete("$BasePath/$container") { - parameter("v", options.removeAnonymousVolumes) - parameter("force", options.force) - parameter("link", options.unlink) - } - } - - /** - * Removes a container. - * - * @param container The container id to remove. - * @param options Removal options. - * @throws ContainerNotFoundException If the container is not found for the specified id. - * @throws ContainerRemoveConflictException When trying to remove an active container without the `force` option. - */ - @JvmOverloads - public fun removeAsync( - container: String, - options: ContainerRemoveOptions = ContainerRemoveOptions(), - ): CompletableFuture = coroutineScope.async { remove(container, options) }.asCompletableFuture() - - /** - * Returns low-level information about a container. - * - * @param container ID or name of the container. - * @param size Should return the size of container as fields `SizeRw` and `SizeRootFs` - */ - @JvmSynthetic - public actual suspend fun inspect( - container: String, - size: Boolean, - ): Container = - requestCatching( - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - ) { - httpClient.get("$BasePath/$container/json") { - parameter("size", size) - } - }.body() - - /** - * Returns low-level information about a container. - * - * @param container ID or name of the container. - * @param size Should return the size of container as fields `SizeRw` and `SizeRootFs` - */ - @JvmOverloads - public fun inspectAsync( - container: String, - size: Boolean = false, - ): CompletableFuture = coroutineScope.async { inspect(container, size) }.asCompletableFuture() - - /** - * Starts a container. - * - * @param container The container id to be started. - * @param detachKeys The key sequence for detaching a container. - * @throws ContainerAlreadyStartedException If the container was already started. - * @throws ContainerNotFoundException If container was not found. - */ - @JvmSynthetic - public actual suspend fun start( - container: String, - detachKeys: String?, - ): Unit = - requestCatching( - HttpStatusCode.NotModified to { cause -> ContainerAlreadyStartedException(cause, container) }, - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - ) { - httpClient.post("$BasePath/$container/start") { - parameter("detachKeys", detachKeys) - } - } - - /** - * Starts a container. - * - * @param id The container id to be started. - * @param detachKeys The key sequence for detaching a container. - * @throws ContainerAlreadyStartedException If the container was already started. - * @throws ContainerNotFoundException If container was not found. - */ - @JvmOverloads - public fun startAsync( - id: String, - detachKeys: String? = null, - ): CompletableFuture = - coroutineScope - .async { - start(id, detachKeys) - }.asCompletableFuture() - - /** - * Stops a container. - * - * @param container The container id to stop. - * @param timeout Duration to wait before killing the container. - */ - @JvmSynthetic - public actual suspend fun stop( - container: String, - timeout: Duration?, - ): Unit = - requestCatching( - HttpStatusCode.NotModified to { cause -> ContainerAlreadyStoppedException(cause, container) }, - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - ) { - httpClient.post("$BasePath/$container/stop") { - parameter("t", timeout?.inWholeSeconds) - } - } - - /** - * Stops a container. - * - * @param container The container id to stop. - */ - public fun stopAsync(container: String): CompletableFuture = - coroutineScope - .async { - stop(container, timeout = null) - }.asCompletableFuture() - - /** - * Stops a container. - * - * @param container The container id to stop. - * @param timeoutInSeconds Duration in seconds to wait before killing the container. - */ - public fun stopAsync( - container: String, - timeoutInSeconds: Int, - ): CompletableFuture = - coroutineScope - .async { - stop(container, timeoutInSeconds.toDuration(DurationUnit.SECONDS)) - }.asCompletableFuture() - - /** - * Restarts a container. - * - * @param container The container id to restart. - * @param timeout Duration to wait before killing the container. - */ - @JvmSynthetic - public actual suspend fun restart( - container: String, - timeout: Duration?, - ): Unit = - requestCatching( - HttpStatusCode.NotFound to { exception -> ContainerNotFoundException(exception, container) }, - ) { - httpClient.post("$BasePath/$container/restart") { - parameter("t", timeout) - } - } - - /** - * Restarts a container. - * - * @param container The container id to restart. - */ - public fun restartAsync(container: String): CompletableFuture = - coroutineScope - .async { - restart(container, timeout = null) - }.asCompletableFuture() - - /** - * Restarts a container. - * - * @param container The container id to restart. - * @param timeoutInSeconds Duration in seconds to wait before killing the container. - */ - public fun restartAsync( - container: String, - timeoutInSeconds: Int, - ): CompletableFuture = - coroutineScope - .async { - restart(container, timeoutInSeconds.toDuration(DurationUnit.SECONDS)) - }.asCompletableFuture() - - /** - * Kills a container. - * - * @param container The container id to kill. - * @param signal Signal to send for container to be killed, Docker's default is "SIGKILL". - */ - @JvmSynthetic - public actual suspend fun kill( - container: String, - signal: String?, - ): Unit = - requestCatching( - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - HttpStatusCode.Conflict to { cause -> ContainerNotRunningException(cause, container) }, - ) { - httpClient.post("$BasePath/$container/kill") { - parameter("signal", signal) - } - } - - /** - * Kills a container. - * - * @param container The container id to kill. - * @param signal Signal to send for container to be killed, Docker's default is "SIGKILL". - */ - @JvmOverloads - public fun killAsync( - container: String, - signal: String? = null, - ): CompletableFuture = - coroutineScope - .async { - kill(container, signal) - }.asCompletableFuture() - - /** - * Renames a container. - * - * @param container The container id to rename. - * @param newName The new container name. - */ - @JvmSynthetic - public actual suspend fun rename( - container: String, - newName: String, - ): Unit = - requestCatching( - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - HttpStatusCode.Conflict to { cause -> ContainerRenameConflictException(cause, container, newName) }, - ) { - httpClient.post("$BasePath/$container/rename") { - parameter("name", newName) - } - } - - /** - * Renames a container. - * - * @param container The container id to rename. - * @param newName The new container name. - */ - public fun renameAsync( - container: String, - newName: String, - ): CompletableFuture = - coroutineScope - .async { - rename(container, newName) - }.asCompletableFuture() - - /** - * Pauses a container. - * - * @param container The container id to pause. - * @see unpause - */ - @JvmSynthetic - public actual suspend fun pause(container: String): Unit = - requestCatching( - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - ) { - httpClient.post("$BasePath/$container/pause") - } - - /** - * Pauses a container. - * - * @param container The container id to pause. - * @see unpause - */ - public fun pauseAsync(container: String): CompletableFuture = coroutineScope.async { pause(container) }.asCompletableFuture() - - /** - * Resumes a container which has been paused. - * - * @param container The container id to unpause. - * @see pause - */ - @JvmSynthetic - public actual suspend fun unpause(container: String): Unit = - requestCatching( - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - ) { - httpClient.post("$BasePath/$container/unpause") - } - - /** - * Resumes a container which has been paused. - * - * @param container The container id to unpause. - * @see pause - */ - public fun unpauseAsync(container: String): CompletableFuture = coroutineScope.async { unpause(container) }.asCompletableFuture() - - /** - * Resizes the TTY for a container. - * - * @param container The container id to resize. - * @param options Resize options like width and height. - * @throws ContainerNotFoundException If the container is not found. - * @throws DockerResponseException If the container cannot be resized or if an error occurs in the request. - */ - @JvmSynthetic - public actual suspend fun resizeTTY( - container: String, - options: ResizeTTYOptions, - ): Unit = - requestCatching( - HttpStatusCode.NotFound to { cause -> - ContainerNotFoundException( - cause, - container, - ) - }, - ) { - httpClient.post("$BasePath/$container/resize") { - setBody(options) - } - } - - /** - * Resizes the TTY for a container. - * - * @param container Unique identifier or name of the container. - * @param options Resize options like width and height. - * @throws ContainerNotFoundException If the container is not found. - * @throws DockerResponseException If the container cannot be resized or if an error occurs in the request. - */ - @JvmOverloads - public fun resizeTTYAsync( - container: String, - options: ResizeTTYOptions = ResizeTTYOptions(), - ): CompletableFuture = coroutineScope.async { resizeTTY(container, options) }.asCompletableFuture() - - @JvmSynthetic - public actual fun attach(container: String): Flow = - channelFlow { - httpClient - .preparePost("$BasePath/$container/attach") { - parameter("stream", "true") - parameter("stdin", "true") - parameter("stdout", "true") - parameter("stderr", "true") - }.execute { response -> - val channel = response.body() - while (!channel.isClosedForRead) { - val line = channel.readUTF8Line() ?: break - - // TODO handle stream type - send(Frame(line, line.length, Stream.StdOut)) - } - } - } - - @JvmSynthetic - public actual suspend fun wait( - container: String, - condition: String?, - ): ContainerWaitResult = - httpClient - .post("$BasePath/$container/wait") { - parameter("condition", condition) - }.body() - - @JvmOverloads - public fun waitAsync( - id: String, - condition: String? = null, - ): CompletableFuture = coroutineScope.async { wait(id, condition) }.asCompletableFuture() - - @JvmSynthetic - public actual suspend fun prune(filters: ContainerPruneFilters): ContainerPruneResult = - httpClient - .post("$BasePath/prune") { - parameter("filters", json.encodeToString(filters)) - }.body() - - @JvmOverloads - public fun pruneAsync(filters: ContainerPruneFilters = ContainerPruneFilters()): CompletableFuture = - coroutineScope.async { prune(filters) }.asCompletableFuture() - - public actual suspend fun copyFrom( - container: String, - sourcePath: String, - ): ContainerCopyResult = - requestCatching( - HttpStatusCode.NotFound to { exception -> - if (exception.message?.contains("file") == true) { - ArchiveNotFoundException(exception, container, sourcePath) - } else { - ContainerNotFoundException(exception, container) - } - }, - ) { - val response = - httpClient.get("$BasePath/$container/archive") { - parameter("path", sourcePath) - } - - val archiveData = response.readRawBytes() - - val statHeader = response.headers["X-Docker-Container-Path-Stat"] - val stat = - statHeader?.let { header -> - val decoded = header.decodeBase64Bytes() - json.decodeFromString(decoded.decodeToString()) - } - - ContainerCopyResult(archiveData, stat) - } - - public actual suspend fun copyTo( - container: String, - destinationPath: String, - tarArchive: ByteArray, - options: ContainerCopyOptions, - ): Unit = - requestCatching( - HttpStatusCode.NotFound to { exception -> ContainerNotFoundException(exception, container) }, - HttpStatusCode.BadRequest to { exception -> - IllegalArgumentException("Invalid destination path: $destinationPath", exception) - }, - ) { - httpClient.put("$BasePath/$container/archive") { - parameter("path", destinationPath) - parameter("noOverwriteDirNonDir", options.noOverwriteDirNonDir.toString()) - parameter("copyUIDGID", options.copyUIDGID.toString()) - - setBody(tarArchive) - contentType(ContentType.Application.OctetStream) - } - } - - public actual suspend fun copyFileFrom( - container: String, - sourcePath: String, - destinationPath: String, - ) { - val result = copyFrom(container, sourcePath) - TarOperations.extractTar(result.archiveData, Path(destinationPath)) - } - - public actual suspend fun copyFileTo( - container: String, - sourcePath: String, - destinationPath: String, - options: ContainerCopyOptions, - ) { - val path = Path(sourcePath) - if (!FileSystemUtils.exists(path)) { - throw IllegalArgumentException("Source file not found: $sourcePath") - } - - if (FileSystemUtils.isDirectory(path)) { - throw IllegalArgumentException("Source is a directory, use copyDirectoryTo instead: $sourcePath") - } - - val tarArchive = TarOperations.createTarFromFile(path) - copyTo(container, destinationPath, tarArchive, options) - } - - public actual suspend fun copyDirectoryFrom( - container: String, - sourcePath: String, - destinationPath: String, - ) { - val result = copyFrom(container, sourcePath) - TarOperations.extractTar(result.archiveData, Path(destinationPath)) - } - - public actual suspend fun copyDirectoryTo( - container: String, - sourcePath: String, - destinationPath: String, - options: ContainerCopyOptions, - ) { - val path = Path(sourcePath) - if (!FileSystemUtils.exists(path) || !FileSystemUtils.isDirectory(path)) { - throw IllegalArgumentException("Source directory not found: $sourcePath") - } - - // Create tar with directory contents only (not including the root directory name) - val tarArchive = createTarFromDirectoryContents(path) - copyTo(container, destinationPath, tarArchive, options) - } - - private fun createTarFromDirectoryContents(dirPath: Path): ByteArray { - val entries = mutableListOf() - TarOperations.collectDirectoryContents(dirPath, "", entries) - return TarUtils.createTarArchive(entries) - } - - public actual suspend fun logs( - container: String, - options: ContainerLogsOptions, - ): ContainerLogsResult = - if (options.follow ?: false) { - logsStreaming(container, options) - } else { - logsComplete(container, options) - } - - private suspend fun logsComplete( - container: String, - options: ContainerLogsOptions, - ): ContainerLogsResult = - requestCatching( - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - ) { - val response = - httpClient.get("$BasePath/$container/logs") { - parameter("stdout", options.stdout) - parameter("stderr", options.stderr) - parameter("timestamps", options.showTimestamps) - parameter("since", options.since) - parameter("until", options.until) - parameter("tail", options.tail) - parameter("follow", false) - } - - val channel = response.bodyAsChannel() - val multiplexed = response.headers.get("Content-Type") == "application/vnd.docker.multiplexed-stream" - - return if (options.demux) { - val (stdout, stderr) = collectStreamDemuxed(channel, multiplexed) - ContainerLogsResult.CompleteDemuxed(stdout, stderr) - } else { - val content = collectStream(channel, multiplexed) - ContainerLogsResult.Complete(content) - } - } - - private fun logsStreaming( - container: String, - options: ContainerLogsOptions, - ): ContainerLogsResult { - val framesFlow = - channelFlow { - requestCatching( - HttpStatusCode.NotFound to { cause -> ContainerNotFoundException(cause, container) }, - ) { - httpClient - .prepareGet("$BasePath/$container/logs") { - parameter("stdout", options.stdout) - parameter("stderr", options.stderr) - parameter("timestamps", options.showTimestamps) - parameter("since", options.since) - parameter("until", options.until) - parameter("tail", options.tail) - parameter("follow", true) - }.execute { httpResponse -> - val channel = httpResponse.bodyAsChannel() - val multiplxed = - httpResponse.headers.get("Content-Type") == "application/vnd.docker.multiplexed-stream" - - readStream(channel, multiplxed) { frame -> - send(frame) - } - } - } - } - - return if (options.demux) { - val stdoutFlow = - flow { - framesFlow.collect { frame -> - if (frame.stream == Stream.StdOut) { - emit(frame.value) - } - } - } - val stderrFlow = - flow { - framesFlow.collect { frame -> - if (frame.stream == Stream.StdErr) { - emit(frame.value) - } - } - } - ContainerLogsResult.StreamDemuxed(stdoutFlow, stderrFlow) - } else { - ContainerLogsResult.Stream(framesFlow) - } - } -} diff --git a/src/nativeMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.native.kt b/src/nativeMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.native.kt deleted file mode 100644 index 9bb12986..00000000 --- a/src/nativeMain/kotlin/me/devnatan/dockerkt/resource/container/ContainerResource.native.kt +++ /dev/null @@ -1,253 +0,0 @@ -package me.devnatan.dockerkt.resource.container - -import io.ktor.client.HttpClient -import io.ktor.client.call.body -import io.ktor.client.request.get -import io.ktor.client.request.parameter -import kotlinx.coroutines.flow.Flow -import kotlinx.serialization.json.Json -import me.devnatan.dockerkt.io.requestCatching -import me.devnatan.dockerkt.models.Frame -import me.devnatan.dockerkt.models.ResizeTTYOptions -import me.devnatan.dockerkt.models.container.Container -import me.devnatan.dockerkt.models.container.ContainerCopyOptions -import me.devnatan.dockerkt.models.container.ContainerCopyResult -import me.devnatan.dockerkt.models.container.ContainerCreateOptions -import me.devnatan.dockerkt.models.container.ContainerListOptions -import me.devnatan.dockerkt.models.container.ContainerLogsOptions -import me.devnatan.dockerkt.models.container.ContainerLogsResult -import me.devnatan.dockerkt.models.container.ContainerPruneFilters -import me.devnatan.dockerkt.models.container.ContainerPruneResult -import me.devnatan.dockerkt.models.container.ContainerRemoveOptions -import me.devnatan.dockerkt.models.container.ContainerSummary -import me.devnatan.dockerkt.models.container.ContainerWaitResult -import kotlin.jvm.JvmSynthetic -import kotlin.time.Duration - -public actual class ContainerResource( - public val httpClient: HttpClient, - public val json: Json, -) { - /** - * Returns a list of all containers. - * - * @param options Options to customize the listing result. - */ - public actual suspend fun list(options: ContainerListOptions): List = - requestCatching { - httpClient.get("containers/json") { - parameter("all", options.all) - parameter("limit", options.limit) - parameter("size", options.size) - parameter("filters", options.filters?.let(json::encodeToString)) - } - }.body() - - /** - * Creates a new container. - * - * @param options Options to customize the container creation. - * @throws ImageNotFoundException If the image specified does not exist or isn't pulled. - * @throws ContainerAlreadyExistsException If a container with the same name already exists. - */ - public actual suspend fun create(options: ContainerCreateOptions): String { - TODO("Not yet implemented") - } - - /** - * Removes a container. - * - * @param container The container id to remove. - * @param options Removal options. - * @throws ContainerNotFoundException If the container is not found for the specified id. - * @throws ContainerRemoveConflictException When trying to remove an active container without the `force` option. - */ - public actual suspend fun remove( - container: String, - options: ContainerRemoveOptions, - ) { - TODO("Not yet implemented") - } - - /** - * Returns low-level information about a container. - * - * @param container ID or name of the container. - * @param size Should return the size of container as fields `SizeRw` and `SizeRootFs` - */ - public actual suspend fun inspect( - container: String, - size: Boolean, - ): Container { - TODO("Not yet implemented") - } - - /** - * Starts a container. - * - * @param container The container id to be started. - * @param detachKeys The key sequence for detaching a container. - * @throws ContainerAlreadyStartedException If the container was already started. - * @throws ContainerNotFoundException If container was not found. - */ - public actual suspend fun start( - container: String, - detachKeys: String?, - ) { - TODO("Not yet implemented") - } - - /** - * Stops a container. - * - * @param container The container id to stop. - * @param timeout Duration to wait before killing the container. - */ - public actual suspend fun stop( - container: String, - timeout: Duration?, - ) { - TODO("Not yet implemented") - } - - /** - * Restarts a container. - * - * @param container The container id to restart. - * @param timeout Duration to wait before killing the container. - */ - public actual suspend fun restart( - container: String, - timeout: Duration?, - ) { - TODO("Not yet implemented") - } - - /** - * Kills a container. - * - * @param container The container id to kill. - * @param signal Signal to send for container to be killed, Docker's default is "SIGKILL". - */ - public actual suspend fun kill( - container: String, - signal: String?, - ) { - TODO("Not yet implemented") - } - - /** - * Renames a container. - * - * @param container The container id to rename. - * @param newName The new container name. - */ - public actual suspend fun rename( - container: String, - newName: String, - ) { - TODO("Not yet implemented") - } - - /** - * Pauses a container. - * - * @param container The container id to pause. - * @see unpause - */ - public actual suspend fun pause(container: String) { - TODO("Not yet implemented") - } - - /** - * Resumes a container which has been paused. - * - * @param container The container id to unpause. - * @see pause - */ - public actual suspend fun unpause(container: String) { - TODO("Not yet implemented") - } - - /** - * Resizes the TTY for a container. - * - * @param container The container id to resize. - * @param options Resize options like width and height. - * @throws ContainerNotFoundException If the container is not found. - * @throws me.devnatan.dockerkt.DockerResourceException If the container cannot be resized or if an error occurs in the request. - */ - public actual suspend fun resizeTTY( - container: String, - options: ResizeTTYOptions, - ) { - TODO("Not yet implemented") - } - - public actual fun attach(container: String): Flow { - TODO("Not yet implemented") - } - - public actual suspend fun wait( - container: String, - condition: String?, - ): ContainerWaitResult { - TODO("Not yet implemented") - } - - public actual suspend fun prune(filters: ContainerPruneFilters): ContainerPruneResult { - TODO("Not yet implemented") - } - - public actual suspend fun logs( - container: String, - options: ContainerLogsOptions, - ): ContainerLogsResult { - TODO("Not yet implemented") - } - - public actual suspend fun copyFrom( - container: String, - sourcePath: String, - ): ContainerCopyResult { - TODO("Not yet implemented") - } - - public actual suspend fun copyTo( - container: String, - destinationPath: String, - tarArchive: ByteArray, - options: ContainerCopyOptions, - ) { - } - - public actual suspend fun copyFileTo( - container: String, - sourcePath: String, - destinationPath: String, - options: ContainerCopyOptions, - ) { - } - - public actual suspend fun copyFileFrom( - container: String, - sourcePath: String, - destinationPath: String, - ) { - } - - public actual suspend fun copyDirectoryFrom( - container: String, - sourcePath: String, - destinationPath: String, - ) { - } - - public actual suspend fun copyDirectoryTo( - container: String, - sourcePath: String, - destinationPath: String, - options: ContainerCopyOptions, - ) { - } -}