You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

55 lines
1.7 KiB

package net.aiterp.git.ykonsole2.application.services
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import net.aiterp.git.ykonsole2.domain.runtime.Command
import net.aiterp.git.ykonsole2.domain.runtime.Driver
import net.aiterp.git.ykonsole2.domain.runtime.Event
import net.aiterp.git.ykonsole2.domain.runtime.FlowBus
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.aiterp.git.ykonsole2.application.logging.log
import java.lang.Exception
import java.util.concurrent.atomic.AtomicInteger
import kotlin.system.exitProcess
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
class DriverStarter(
private val drivers: List<Driver>,
private val input: FlowBus<Command>,
private val output: FlowBus<Event>,
private val retryInterval: Duration = 10.seconds
) {
val logger = log
fun startDrivers() = runBlocking {
val jobs = drivers.map { driver ->
val name = driver.javaClass.kotlin.simpleName
logger.info("Starting driver \"$name\"...")
launch {
val health = AtomicInteger(12)
while (true) {
try {
driver.start(input, output)
} catch (e: Exception) {
logger.error("Driver \"$name\" interrupted by exception: ${e.message}", e)
if (health.decrementAndGet() <= 0) {
logger.error("Driver \"$name\" was interrupted too many times, will not be reset")
break
}
delay(retryInterval)
logger.info("Restarting driver \"$name\"...")
}
}
}
}
logger.info("Started ${drivers.size} drivers")
jobs.forEach { it.join() }
}
}