| 6 | * This program is free software: you can redistribute it and/or modify * |
| 7 | * it under the terms of the GNU General Public License as published by * |
| 8 | * the Free Software Foundation, either version 3 of the License, or * |
| 9 | * (at your option) any later version. * |
| 10 | * * |
| 11 | * This program is distributed in the hope that it will be useful, * |
| 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
| 14 | * GNU General Public License for more details. * |
| 15 | * * |
| 16 | * You should have received a copy of the GNU General Public License * |
| 17 | * along with this program. If not, see <http://www.gnu.org/licenses/>. * |
| 18 | * * |
| 19 | *******************************************************************************/ |
| 20 |
| 21 | package tw.nekomimi.nekogram |
| 22 |
| 23 | import android.annotation.SuppressLint |
| 24 | import android.os.Build |
| 25 | import android.os.SystemClock |
| 26 | import android.system.ErrnoException |
| 27 | import android.system.Os |
| 28 | import android.system.OsConstants |
| 29 | import androidx.annotation.MainThread |
| 30 | import kotlinx.coroutines.* |
| 31 | import kotlinx.coroutines.channels.Channel |
| 32 | import org.telegram.messenger.ApplicationLoader |
| 33 | import org.telegram.messenger.FileLog |
| 34 | import java.io.File |
| 35 | import java.io.IOException |
| 36 | import java.io.InputStream |
| 37 | import kotlin.concurrent.thread |
| 38 |
| 39 | class GuardedProcessPool(private val onFatal: suspend (IOException) -> Unit) : CoroutineScope { |
| 40 | companion object { |
| 41 | private const val TAG = "GuardedProcessPool" |
| 42 | } |
| 43 |
| 44 | private inner class Guard(private val cmd: List<String>) { |
| 45 | private lateinit var process: Process |
| 46 |
| 47 | private fun streamLogger(input: InputStream, logger: (String) -> Unit) = try { |
| 48 | input.bufferedReader().forEachLine(logger) |
| 49 | } catch (_: IOException) { } // ignore |
| 50 |
| 51 | fun start() { |
| 52 | process = ProcessBuilder(cmd).directory(ApplicationLoader.applicationContext.cacheDir).start() |
| 53 | } |
| 54 |
| 55 | suspend fun looper(onRestartCallback: (suspend () -> Unit)?) { |
| 56 | var running = true |
| 57 | val cmdName = File(cmd.first()).nameWithoutExtension |
| 58 | val exitChannel = Channel<Int>() |
| 59 | try { |
| 60 | while (true) { |
| 61 | thread(name = "stderr-$cmdName") { |
| 62 | streamLogger(process.errorStream) { |
| 63 | FileLog.e("[$cmdName]$it") |
| 64 | } |
| 65 | } |
| 66 | thread(name = "stdout-$cmdName") { |
| 67 | streamLogger(process.inputStream) { |
| 68 | FileLog.d("[$cmdName]$it") |
| 69 | } |
| 70 | // this thread also acts as a daemon thread for waitFor |
| 71 | runBlocking { exitChannel.send(process.waitFor()) } |
| 72 | } |
| 73 | val startTime = SystemClock.elapsedRealtime() |
| 74 | val exitCode = exitChannel.receive() |
| 75 | running = false |
| 76 | when { |
| 77 | SystemClock.elapsedRealtime() - startTime < 1000 -> throw IOException( |
| 78 | "$cmdName exits too fast (exit code: $exitCode)") |
| 79 | exitCode == 128 + OsConstants.SIGKILL -> FileLog.w("$cmdName was killed") |
| 80 | else -> FileLog.e(IOException("$cmdName unexpectedly exits with code $exitCode")) |
| 81 | } |
| 82 | start() |
| 83 | running = true |
| 84 | onRestartCallback?.invoke() |
| 85 | } |
| 86 | } catch (e: IOException) { |
| 87 | FileLog.w("error occurred. stop guard: " + cmd.joinToString(" ")) |
| 88 | GlobalScope.launch(Dispatchers.Main) { onFatal(e) } |
| 89 | } finally { |
| 90 | if (running) withContext(NonCancellable) { |
| 91 | process.destroy() // kill the process |
| 92 | if (Build.VERSION.SDK_INT >= 26) { |
| 93 | if (withTimeoutOrNull(1000) { exitChannel.receive() } != null) return@withContext |
| 94 | process.destroyForcibly() // Force to kill the process if it's still alive |
| 95 | } |
| 96 | exitChannel.receive() |
| 97 | } // otherwise process already exited, nothing to be done |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 |
| 102 | override val coroutineContext = Dispatchers.Main.immediate + Job() |
| 103 |
| 104 | @MainThread |
| 105 | fun start(cmd: List<String>, onRestartCallback: (suspend () -> Unit)? = null) { |
| 106 | FileLog.d("start process: " + cmd.joinToString (" ")) |
| 107 | Guard(cmd).apply { |
| 108 | start() // if start fails, IOException will be thrown directly |
| 109 | launch { looper(onRestartCallback) } |
| 110 | } |
| 111 | } |
| 112 |
| 113 | @MainThread |
| 114 | fun close(scope: CoroutineScope) { |
| 115 | cancel() |
| 116 | coroutineContext[Job]!!.also { job -> scope.launch { job.join() } } |
| 117 | } |
| 118 | } |
| 119 |