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

Improve console shutdown #2016

Merged
merged 6 commits into from
Jun 6, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
19 changes: 17 additions & 2 deletions mirai-console/backend/mirai-console/src/MiraiConsole.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@

package net.mamoe.mirai.console

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.*
import me.him188.kotlin.dynamic.delegation.dynamicDelegation
import net.mamoe.mirai.Bot
import net.mamoe.mirai.BotFactory
Expand Down Expand Up @@ -239,6 +238,22 @@ public interface MiraiConsole : CoroutineScope {
@ConsoleExperimentalApi("This is a low-level API and might be removed in the future.")
public val isActive: Boolean
get() = job.isActive

/**
* 停止 Console 运行
*
* Console 会在一个合适的时间进行关闭, 并不是调用马上关闭 Console
*/
@ConsoleExperimentalApi
@JvmStatic
public fun shutdown() {
val consoleJob = job
if (!consoleJob.isActive) return
@OptIn(DelicateCoroutinesApi::class)
GlobalScope.launch {
MiraiConsoleImplementation.shutdown()
}
}
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import net.mamoe.mirai.console.internal.data.builtins.ConsoleDataScopeImpl
import net.mamoe.mirai.console.internal.logging.LoggerControllerImpl
import net.mamoe.mirai.console.internal.plugin.BuiltInJvmPluginLoaderImpl
import net.mamoe.mirai.console.internal.pluginManagerImpl
import net.mamoe.mirai.console.internal.shutdown.ShutdownDaemon
import net.mamoe.mirai.console.logging.LoggerController
import net.mamoe.mirai.console.plugin.Plugin
import net.mamoe.mirai.console.plugin.jvm.JvmPluginLoader
Expand Down Expand Up @@ -396,10 +397,29 @@ public interface MiraiConsoleImplementation : CoroutineScope {
override val resolvedPlugins: MutableList<Plugin> get() = MiraiConsole.pluginManagerImpl.resolvedPlugins
}

internal suspend fun shutdown() {
val bridge = currentBridge ?: return
if (!bridge.isActive) return
bridge.shutdownDaemon.tryStart()

Bot.instances.forEach { bot ->
lateinit var logger: MiraiLogger
kotlin.runCatching {
logger = bot.logger
bot.closeAndJoin()
}.onFailure { t ->
kotlin.runCatching { logger.error("Error in closing bot", t) }
}
}
MiraiConsole.job.cancelAndJoin()
Karlatemp marked this conversation as resolved.
Show resolved Hide resolved
}

init {
Runtime.getRuntime().addShutdownHook(thread(false) {
Runtime.getRuntime().addShutdownHook(thread(false, name = "Mirai Console Shutdown Hook") {
if (instanceInitialized) {
runBlocking { MiraiConsole.job.cancelAndJoin() }
runBlocking {
shutdown()
}
}
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ package net.mamoe.mirai.console.command

import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
Expand Down Expand Up @@ -54,7 +53,6 @@ import net.mamoe.mirai.console.util.ConsoleInternalApi
import net.mamoe.mirai.console.util.sendAnsiMessage
import net.mamoe.mirai.event.events.EventCancelledException
import net.mamoe.mirai.utils.BotConfiguration
import net.mamoe.mirai.utils.MiraiLogger
import java.lang.management.ManagementFactory
import java.lang.management.MemoryMXBean
import java.lang.management.MemoryUsage
Expand Down Expand Up @@ -140,16 +138,7 @@ public object BuiltInCommands {
if (!MiraiConsole.isActive) return@withLock
sendMessage("Stopping mirai-console")
kotlin.runCatching {
Bot.instances.forEach { bot ->
lateinit var logger: MiraiLogger
kotlin.runCatching {
logger = bot.logger
bot.closeAndJoin()
}.onFailure { t ->
kotlin.runCatching { logger.error("Error in closing bot", t) }
}
}
MiraiConsole.job.cancelAndJoin()
MiraiConsoleImplementation.shutdown()
}.fold(
onSuccess = {
runIgnoreException<EventCancelledException> { sendMessage("mirai-console stopped successfully.") }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import net.mamoe.mirai.console.internal.logging.LoggerControllerImpl
import net.mamoe.mirai.console.internal.logging.MiraiConsoleLogger
import net.mamoe.mirai.console.internal.permission.BuiltInPermissionService
import net.mamoe.mirai.console.internal.plugin.PluginManagerImpl
import net.mamoe.mirai.console.internal.shutdown.ShutdownDaemon
import net.mamoe.mirai.console.internal.util.runIgnoreException
import net.mamoe.mirai.console.logging.LoggerController
import net.mamoe.mirai.console.permission.PermissionService
Expand All @@ -58,6 +59,7 @@ import net.mamoe.mirai.utils.*
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlin.reflect.KProperty
Expand Down Expand Up @@ -85,6 +87,7 @@ internal class MiraiConsoleImplementationBridge(

// used internally
val globalComponentStorage: GlobalComponentStorageImpl by lazy { GlobalComponentStorageImpl() }
val shutdownDaemon = ShutdownDaemon.DaemonStarter(this)

// tentative workaround for https://github.com/mamoe/mirai/pull/1889#pullrequestreview-887903183
@Volatile
Expand Down Expand Up @@ -147,6 +150,7 @@ internal class MiraiConsoleImplementationBridge(
}

MiraiConsole.job.invokeOnCompletion {
shutdownDaemon.tryStart()
Karlatemp marked this conversation as resolved.
Show resolved Hide resolved
Bot.instances.forEach { kotlin.runCatching { it.close() }.exceptionOrNull()?.let(mainLogger::error) }
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import net.mamoe.mirai.console.data.runCatchingLog
import net.mamoe.mirai.console.extension.PluginComponentStorage
import net.mamoe.mirai.console.internal.data.mkdir
import net.mamoe.mirai.console.internal.extension.GlobalComponentStorage
import net.mamoe.mirai.console.internal.shutdown.ShutdownDaemon
import net.mamoe.mirai.console.permission.Permission
import net.mamoe.mirai.console.permission.PermissionService
import net.mamoe.mirai.console.plugin.Plugin
Expand Down Expand Up @@ -89,7 +90,13 @@ internal abstract class JvmPluginInternal(
internal fun internalOnDisable() {
firstRun = false
kotlin.runCatching {
onDisable()
val crtThread = Thread.currentThread()
ShutdownDaemon.pluginDisablingThreads.add(crtThread)
try {
onDisable()
} finally {
ShutdownDaemon.pluginDisablingThreads.remove(crtThread)
}
Karlatemp marked this conversation as resolved.
Show resolved Hide resolved
}.fold(
onSuccess = {
cancel(CancellationException("plugin disabled"))
Expand Down
Loading