-
Notifications
You must be signed in to change notification settings - Fork 1k
/
ApplicationEngineEnvironmentReloading.kt
386 lines (324 loc) · 13.2 KB
/
ApplicationEngineEnvironmentReloading.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.engine
import io.ktor.events.*
import io.ktor.events.EventDefinition
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.engine.internal.*
import io.ktor.util.*
import io.ktor.util.logging.*
import io.ktor.util.pipeline.*
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import java.io.*
import java.net.*
import java.nio.file.*
import java.nio.file.StandardWatchEventKinds.*
import java.nio.file.attribute.*
import java.util.concurrent.locks.*
import kotlin.concurrent.*
import kotlin.coroutines.*
/**
* Implements [ApplicationEngineEnvironment] by loading an [Application] from a folder or jar.
*
* [watchPaths] specifies substrings to match against class path entries to monitor changes in folder/jar and implements hot reloading
*/
public class ApplicationEngineEnvironmentReloading(
override val classLoader: ClassLoader,
override val log: Logger,
override val config: ApplicationConfig,
override val connectors: List<EngineConnectorConfig>,
internal val modules: List<Application.() -> Unit>,
internal val watchPaths: List<String> = emptyList(),
parentCoroutineContext: CoroutineContext = EmptyCoroutineContext,
override val rootPath: String = "",
override val developmentMode: Boolean = true
) : ApplicationEngineEnvironment {
private val configuredWatchPath get() = config.propertyOrNull("ktor.deployment.watch")?.getList() ?: listOf()
private val watchPatterns: List<String> = configuredWatchPath + watchPaths
override val parentCoroutineContext: CoroutineContext = when {
developmentMode && watchPatterns.isNotEmpty() ->
parentCoroutineContext + ClassLoaderAwareContinuationInterceptor
else -> parentCoroutineContext
}
public constructor(
classLoader: ClassLoader,
log: Logger,
config: ApplicationConfig,
connectors: List<EngineConnectorConfig>,
modules: List<Application.() -> Unit>,
watchPaths: List<String> = emptyList(),
parentCoroutineContext: CoroutineContext = EmptyCoroutineContext,
rootPath: String = "",
) : this(
classLoader, log, config, connectors, modules, watchPaths,
parentCoroutineContext, rootPath, developmentMode = true
)
private var _applicationInstance: Application? = Application(this)
private var recreateInstance: Boolean = false
private var _applicationClassLoader: ClassLoader? = null
private val applicationInstanceLock = ReentrantReadWriteLock()
private var packageWatchKeys = emptyList<WatchKey>()
private val configModulesNames: List<String> = run {
config.propertyOrNull("ktor.application.modules")?.getList() ?: emptyList()
}
internal val modulesNames: List<String> = configModulesNames
private val watcher: WatchService? by lazy {
try {
FileSystems.getDefault().newWatchService()
} catch (_: NoClassDefFoundError) {
null
}
}
override val monitor: Events = Events()
override val application: Application
get() = currentApplication()
/**
* Reload application: destroy it first and then create again
*/
public fun reload() {
applicationInstanceLock.write {
destroyApplication()
val (application, classLoader) = createApplication()
_applicationInstance = application
_applicationClassLoader = classLoader
}
}
private fun currentApplication(): Application = applicationInstanceLock.read {
val currentApplication = _applicationInstance ?: error("ApplicationEngineEnvironment was not started")
if (!developmentMode) {
return@read currentApplication
}
val changes = packageWatchKeys.flatMap { it.pollEvents() }
if (changes.isEmpty()) {
return@read currentApplication
}
log.info("Changes in application detected.")
var count = changes.size
while (true) {
Thread.sleep(200)
val moreChanges = packageWatchKeys.flatMap { it.pollEvents() }
if (moreChanges.isEmpty()) {
break
}
log.debug("Waiting for more changes.")
count += moreChanges.size
}
log.debug("Changes to $count files caused application restart.")
changes.take(5).forEach { log.debug("... ${it.context()}") }
applicationInstanceLock.write {
destroyApplication()
val (application, classLoader) = createApplication()
_applicationInstance = application
_applicationClassLoader = classLoader
}
return@read _applicationInstance ?: error("ApplicationEngineEnvironment was not started")
}
private fun createApplication(): Pair<Application, ClassLoader> {
val classLoader = createClassLoader()
val currentThread = Thread.currentThread()
val oldThreadClassLoader = currentThread.contextClassLoader
currentThread.contextClassLoader = classLoader
try {
return instantiateAndConfigureApplication(classLoader) to classLoader
} finally {
currentThread.contextClassLoader = oldThreadClassLoader
}
}
private fun createClassLoader(): ClassLoader {
val baseClassLoader = classLoader
if (!developmentMode) {
log.info("Autoreload is disabled because the development mode is off.")
return baseClassLoader
}
val watchPatterns = watchPatterns
if (watchPatterns.isEmpty()) {
log.info("No ktor.deployment.watch patterns specified, automatic reload is not active.")
return baseClassLoader
}
val allUrls = baseClassLoader.allURLs()
val jre = File(System.getProperty("java.home")).parent
val debugUrls = allUrls.map { it.file }
log.debug("Java Home: $jre")
log.debug("Class Loader: $baseClassLoader: ${debugUrls.filter { !it.toString().startsWith(jre) }}")
// we shouldn't watch URL for ktor-server classes, even if they match patterns,
// because otherwise it loads two ApplicationEnvironment (and other) types which do not match
val coreUrls = listOf(
ApplicationEnvironment::class.java, // ktor-server
ApplicationEngineEnvironment::class.java, // ktor-server-host-common
Pipeline::class.java, // ktor-parsing
HttpStatusCode::class.java, // ktor-http
kotlin.jvm.functions.Function1::class.java, // kotlin-stdlib
Logger::class.java, // slf4j
ByteReadChannel::class.java,
Input::class.java, // kotlinx-io
Attributes::class.java
).mapNotNullTo(HashSet()) { it.protectionDomain.codeSource.location }
val watchUrls = allUrls.filter { url ->
url !in coreUrls && watchPatterns.any { pattern -> url.toString().contains(pattern) } &&
!(url.path ?: "").startsWith(jre)
}
if (watchUrls.isEmpty()) {
log.info("No ktor.deployment.watch patterns match classpath entries, automatic reload is not active")
return baseClassLoader
}
watchUrls(watchUrls)
return OverridingClassLoader(watchUrls, baseClassLoader)
}
private fun safeRiseEvent(event: EventDefinition<Application>, application: Application) {
monitor.raiseCatching(event, application)
}
private fun destroyApplication() {
val currentApplication = _applicationInstance
val applicationClassLoader = _applicationClassLoader
_applicationInstance = null
_applicationClassLoader = null
if (currentApplication != null) {
safeRiseEvent(ApplicationStopping, currentApplication)
try {
currentApplication.dispose()
(applicationClassLoader as? OverridingClassLoader)?.close()
} catch (e: Throwable) {
log.error("Failed to destroy application instance.", e)
}
safeRiseEvent(ApplicationStopped, currentApplication)
}
packageWatchKeys.forEach { it.cancel() }
packageWatchKeys = mutableListOf()
}
private fun watchUrls(urls: List<URL>) {
val paths = HashSet<Path>()
for (url in urls) {
val path = url.path ?: continue
val decodedPath = URLDecoder.decode(path, "utf-8")
val folder = runCatching { File(decodedPath).toPath() }.getOrNull() ?: continue
if (!Files.exists(folder)) {
continue
}
val visitor = object : SimpleFileVisitor<Path>() {
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
paths.add(dir)
return FileVisitResult.CONTINUE
}
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
val dir = file.parent
if (dir != null) {
paths.add(dir)
}
return FileVisitResult.CONTINUE
}
}
if (Files.isDirectory(folder)) {
Files.walkFileTree(folder, visitor)
}
}
paths.forEach { path ->
log.debug("Watching $path for changes.")
}
val modifiers = get_com_sun_nio_file_SensitivityWatchEventModifier_HIGH()?.let { arrayOf(it) } ?: emptyArray()
packageWatchKeys = paths.mapNotNull { path ->
watcher?.let {
path.register(it, arrayOf(ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY), *modifiers)
}
}
}
override fun start() {
applicationInstanceLock.write {
val (application, classLoader) = try {
createApplication()
} catch (cause: Throwable) {
destroyApplication()
if (watchPatterns.isNotEmpty()) {
cleanupWatcher()
}
throw cause
}
_applicationInstance = application
_applicationClassLoader = classLoader
}
}
override fun stop() {
applicationInstanceLock.write {
destroyApplication()
}
if (watchPatterns.isNotEmpty()) {
cleanupWatcher()
}
}
private fun instantiateAndConfigureApplication(currentClassLoader: ClassLoader): Application {
val newInstance = if (recreateInstance || _applicationInstance == null) {
Application(this)
} else {
recreateInstance = true
_applicationInstance!!
}
safeRiseEvent(ApplicationStarting, newInstance)
avoidingDoubleStartup {
modulesNames.forEach { name ->
launchModuleByName(name, currentClassLoader, newInstance)
}
modules.forEach { module ->
val name = module.methodName()
try {
launchModuleByName(name, currentClassLoader, newInstance)
} catch (_: ReloadingException) {
module(newInstance)
}
}
}
safeRiseEvent(ApplicationStarted, newInstance)
return newInstance
}
private fun launchModuleByName(name: String, currentClassLoader: ClassLoader, newInstance: Application) {
avoidingDoubleStartupFor(name) {
executeModuleFunction(currentClassLoader, name, newInstance)
}
}
private fun avoidingDoubleStartup(block: () -> Unit) {
try {
block()
} finally {
currentStartupModules.get()?.let {
if (it.isEmpty()) {
currentStartupModules.remove()
}
}
}
}
private fun avoidingDoubleStartupFor(fqName: String, block: () -> Unit) {
val modules = currentStartupModules.getOrSet { ArrayList(1) }
check(!modules.contains(fqName)) {
"Module startup is already in progress for function $fqName (recursive module startup from module main?)"
}
modules.add(fqName)
try {
block()
} finally {
modules.remove(fqName)
}
}
private fun cleanupWatcher() {
try {
watcher?.close()
} catch (_: NoClassDefFoundError) {
}
}
public companion object
}
private object ClassLoaderAwareContinuationInterceptor : ContinuationInterceptor {
override val key: CoroutineContext.Key<*> =
object : CoroutineContext.Key<ClassLoaderAwareContinuationInterceptor> {}
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
val classLoader = Thread.currentThread().contextClassLoader
return object : Continuation<T> {
override val context: CoroutineContext = continuation.context
override fun resumeWith(result: Result<T>) {
Thread.currentThread().contextClassLoader = classLoader
continuation.resumeWith(result)
}
}
}
}