Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Created February 20, 2022 21:09
Show Gist options
  • Save svanellewee/cfdb935e2662e7f115a07c470c0e583a to your computer and use it in GitHub Desktop.
Save svanellewee/cfdb935e2662e7f115a07c470c0e583a to your computer and use it in GitHub Desktop.
Kotlin coroutines, ktor, tls k8s logs.
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.network.tls.*
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.Serializable
import java.io.File
import java.io.FileInputStream
import java.security.KeyStore
import java.security.cert.X509Certificate
import javax.net.ssl.X509TrustManager
@Serializable
data class Post (var userId: Int, var id: Int, var title: String, var body: String)
fun CoroutineScope.logSource(client: HttpClient, outputChan: Channel<ByteArray>) = launch {
client.get<HttpStatement>("https://127.0.0.1:37761/api/v1/namespaces/default/pods/county-dep-58567fd459-lgxb4/log")
.execute { response ->
val channel = response.receive<ByteReadChannel>()
while (!channel.isClosedForRead) {
val packet = channel.readRemaining(800)
while (!packet.isEmpty) {
val bytes: ByteArray = packet.readBytes()
outputChan.send(bytes)
}
}
outputChan.close()
}
}
fun main() {
val someFile = File("./keystore.jks")
val keystore = KeyStore.getInstance("JKS")
val fis = FileInputStream("/home/stephan/entersekt/kotlin-prometheus/keystore.jks")
keystore.load(fis, "changeit".toCharArray())
for (i in keystore.aliases()) {
println("[${i}] [${keystore.getCertificate(i)}]")
}
val naiveTrustManager = object : X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
}
val client: HttpClient = HttpClient(CIO) {
engine {
https {
addKeyStore(keystore, "changeit".toCharArray() as CharArray?)
trustManager = naiveTrustManager
}
}
}
runBlocking {
val outputChan: Channel<ByteArray> = Channel<ByteArray>()
logSource(client, outputChan)
launch {
for (x in outputChan) {
println("...${String(x, Charsets.UTF_8)}>>")
}
println("Done!!!")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment