Skip to content
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

feat: Remove print lines from Corellium client #2034

Merged
merged 2 commits into from
Jun 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ class Agent internal constructor(
internal val format: Json = Json {},
)

internal typealias TasksMap = ConcurrentHashMap<Int, (CommandResult) -> Unit>
internal typealias TasksMap = ConcurrentHashMap<Int, suspend (CommandResult) -> Unit>

class TaskException(val error: CommandResult.Error) : Exception("${error.name}: ${error.message}")
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@ import io.ktor.client.request.header
import io.ktor.client.request.url
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import kotlinx.serialization.decodeFromString

/**
Expand All @@ -42,10 +40,8 @@ internal suspend fun connectAgent(
connection = client
.createSession(agentUrl, token)
.let(::Agent)
.apply {
handleIncomingFrames()
waitForReady()
}
.apply { handleIncomingFrames() }
.waitForReady()
} catch (ex: Exception) {
delay(20_000)
}
Expand All @@ -63,8 +59,7 @@ private suspend fun HttpClient.createSession(
header("Authorization", token)
}

private suspend fun Agent.waitForReady() {
val task = Job()
private suspend fun Agent.waitForReady() = apply {
val id = counter.getAndIncrement()
sendCommand(
AgentOperation(
Expand All @@ -73,15 +68,7 @@ private suspend fun Agent.waitForReady() {
id = id
)
)
tasks[id] = { result ->
if (result.success) task.complete() else {
println("Task ${result.id} failed")
println(result)
}
}
withTimeout(20_000) {
task.join()
}
await(id, 20_000)
}

private fun Agent.handleIncomingFrames() =
Expand All @@ -91,13 +78,12 @@ private fun Agent.handleIncomingFrames() =
is Frame.Text -> handleTestFrame(frame)
is Frame.Ping -> println("got ping")
is Frame.Pong -> println("got pong")
else -> println(frame.data.decodeToString())
else -> Unit
}
}
}

private fun Agent.handleTestFrame(frame: Frame.Text) {
println("Received: ${frame.readText()}")
private suspend fun Agent.handleTestFrame(frame: Frame.Text) {
val result = format.decodeFromString<CommandResult>(frame.readText())
tasks[result.id]?.invoke(result)
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package flank.corellium.client.agent

import flank.corellium.client.data.AgentOperation
import io.ktor.http.cio.websocket.Frame
import kotlinx.coroutines.Job
import kotlinx.coroutines.withTimeout
import java.nio.ByteBuffer
import java.nio.ByteOrder

Expand Down Expand Up @@ -38,9 +36,5 @@ suspend fun Agent.uploadFile(
session.send(Frame.Binary(true, payload))
session.send(Frame.Binary(true, idBytes))

val task = Job()
tasks[id] = defaultResultHandler(task)
withTimeout(100_000) {
task.join()
}
await(id, 100_000)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,26 @@ package flank.corellium.client.agent
import flank.corellium.client.data.AgentOperation
import flank.corellium.client.data.CommandResult
import io.ktor.http.cio.websocket.Frame
import kotlinx.coroutines.CompletableJob
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.withTimeout
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

internal fun defaultResultHandler(task: CompletableJob): (CommandResult) -> Unit = { result ->
if (result.success) task.complete() else {
println("Task ${result.id} failed")
println(format.encodeToString(result))
}
}

internal suspend fun Agent.sendCommand(command: AgentOperation) =
session.send(Frame.Text(format.encodeToString(command)))

internal suspend fun Agent.await(operationId: Int, timeMillis: Long) {
val task = CompletableDeferred<CommandResult>(Job())
tasks[operationId] = { task.complete(it) }
try {
val error = withTimeout(timeMillis) { task.await() }.error
if (error != null) throw TaskException(error)
} finally {
tasks -= operationId
}
}

private val format = Json {
ignoreUnknownKeys = true
encodeDefaults = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.launch

/**
* Send a command to serial console.
Expand All @@ -29,17 +28,6 @@ suspend fun Console.waitForIdle(timeToWait: Long) {
*/
suspend fun Console.close(): Unit = session.close()

@Deprecated("Use Console.flowLogs()")
fun Console.launchOutputPrinter() = session.launch {
// drop console bash history which is received as first frame
session.incoming.receive()

for (frame in session.incoming) {
lastResponseTime = System.currentTimeMillis()
print(frame.data.decodeToString())
}
}

/**
* Clear unread log messages buffer.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,45 +1,16 @@
package flank.corellium.client.util

import io.ktor.client.features.ServerResponseException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.pow

// TODO convert print lines to structural logging

suspend inline fun <T> withRetry(crossinline block: suspend CoroutineScope.() -> T) = coroutineScope {
var currentDelay = 500L
repeat(6) {
suspend inline fun <R> withRetry(crossinline block: suspend () -> R): R =
(0 until 5).mapNotNull { multi ->
try {
return@coroutineScope block()
block()
} catch (e: ServerResponseException) {
println("Request failed due to: ${e.message}")
println("Waiting $currentDelay ms before $it attempt")
}
delay(currentDelay)
currentDelay = (currentDelay * 2).coerceAtMost(20_000)
}
return@coroutineScope block()
}

suspend inline fun <T> withProgress(
initialDelay: Long = 0,
crossinline block: suspend CoroutineScope.() -> T
) = coroutineScope {
if (initialDelay > 0) delay(initialDelay)
val progress = launch {
println("Progress")
while (true) {
print(".")
delay(2500)
val wait = (2.0).pow(multi).times(1000).toLong()
delay(wait)
null
}
}
try {
return@coroutineScope block()
} finally {
progress.cancelAndJoin()
println()
}
}
}.firstOrNull() ?: block()
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package flank.corellium.sandbox.android
import flank.corellium.client.agent.disconnect
import flank.corellium.client.agent.uploadFile
import flank.corellium.client.console.close
import flank.corellium.client.console.launchOutputPrinter
import flank.corellium.client.console.flowLogs
import flank.corellium.client.console.sendCommand
import flank.corellium.client.console.waitForIdle
import flank.corellium.client.core.connectAgent
Expand All @@ -20,6 +20,8 @@ import flank.corellium.client.data.Instance
import flank.corellium.client.data.Instance.BootOptions
import flank.corellium.sandbox.config.Config
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.File

Expand Down Expand Up @@ -95,7 +97,7 @@ fun main(): Unit = runBlocking {

println("Running tests... ")
console.sendCommand("am instrument -r -w com.example.test_app.test/androidx.test.runner.AndroidJUnitRunner")
console.launchOutputPrinter()
console.launch { console.flowLogs().collect { println(it) } }

console.waitForIdle(5_000)
println()
Expand Down