-
Notifications
You must be signed in to change notification settings - Fork 32
/
LocalInstance.kt
443 lines (340 loc) · 15.2 KB
/
LocalInstance.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package com.cognifide.gradle.aem.common.instance
import com.cognifide.gradle.aem.AemExtension
import com.cognifide.gradle.aem.AemVersion
import com.cognifide.gradle.aem.common.CommonOptions
import com.cognifide.gradle.aem.common.file.FileOperations
import com.cognifide.gradle.aem.common.instance.local.JavaAgentResolver
import com.cognifide.gradle.aem.common.instance.local.Script
import com.cognifide.gradle.aem.common.instance.local.Status
import com.cognifide.gradle.aem.common.instance.oak.OakRun
import com.cognifide.gradle.aem.common.instance.service.osgi.Bundle
import com.cognifide.gradle.common.utils.Formats
import com.cognifide.gradle.common.utils.using
import org.apache.commons.io.FileUtils
import org.gradle.internal.os.OperatingSystem
import org.gradle.jvm.toolchain.JavaLanguageVersion
import java.io.File
import java.io.FileFilter
@Suppress("TooManyFunctions")
class LocalInstance(aem: AemExtension, name: String) : Instance(aem, name) {
val debugPort = common.obj.int {
convention(aem.obj.provider { httpUrlDetails.debugPort })
prop.int("debugPort")?.let { set(it) }
}
val debugAddress = common.obj.string {
prop.string("debugAddress")?.let { set(it) }
}
val openPath = common.obj.string {
convention("/")
prop.string("openPath")?.let { set(it) }
}
val httpOpenUrl get() = when (openPath.get()) {
"/" -> httpUrl.get()
else -> "${httpUrl.get()}${openPath.get()}"
}
val jvmOpts = common.obj.strings {
set(listOf("-server", "-Xmx2048m", "-XX:MaxPermSize=512M", "-Djava.awt.headless=true"))
prop.strings("jvmOpts")?.let { set(it) }
}
val jvmAgents = JavaAgentResolver(aem).apply {
prop.strings("jvmAgents")?.let { files(it) }
}
fun jvmAgents(options: JavaAgentResolver.() -> Unit) = jvmAgents.using(options)
val jvmAgentOpt: String? get() = jvmAgents.files.joinToString(" ") { "-javaagent:$it" }.ifBlank { null }
@Suppress("MagicNumber")
val jvmDebugOpt: String? get() = when (debugPort.orNull) {
in 1..65535 -> {
val address = when {
localManager.javaLauncher.get().metadata.languageVersion >= JavaLanguageVersion.of(9) -> {
when {
debugAddress.orNull == "*" -> "0.0.0.0:${debugPort.get()}"
debugAddress.orNull.isNullOrBlank() -> "${debugPort.get()}"
else -> "${debugAddress.orNull}:${debugPort.get()}"
}
}
else -> {
"${debugPort.get()}"
}
}
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$address"
}
else -> null
}
val jvmOptsString: String get() = (jvmOpts.get() + jvmDebugOpt + jvmAgentOpt).filterNot { it.isNullOrBlank() }.joinToString(" ")
val javaExecutablePath: String get() = localManager.javaExecutablePath
val startOpts = common.obj.strings {
set(listOf())
prop.strings("startOpts")?.let { set(it) }
}
val startOptsString: String get() = startOpts.get().filterNot { it.isNullOrBlank() }.joinToString(" ")
val runModes = common.obj.strings {
set(listOf())
prop.strings("runModes")?.let { set(it) }
}
val runModesString: String get() = (runModes.get() + listOf(purpose.name.lowercase()))
.filter { it.isNotBlank() }.joinToString(",")
val dir: File get() = aem.localInstanceManager.instanceDir.get().asFile.resolve(purposeId)
val controlDir: File get() = dir.resolve("control")
val overridesDirs: List<File> get() = localManager.overrideDir.get().asFile.run { listOf(resolve("common"), resolve(purposeId)) }
val jar: File? get() = quickstartDir.resolve("app").takeIf { it.exists() }?.listFiles(FileFilter { it.extension == "jar" })?.firstOrNull()
val license: File get() = dir.resolve("license.properties")
val quickstartDir: File get() = dir.resolve("crx-quickstart")
val bundlesDir: File get() = quickstartDir.resolve("launchpad/felix")
fun bundleDir(bundle: Bundle) = bundleDir(bundle.id.toInt())
fun bundleDir(no: Int) = bundlesDir.resolve("bundle$no")
val pidFile: File get() = quickstartDir.resolve("conf/cq.pid")
val pid: Int get() = pidFile.takeIf { it.exists() }?.readText()
?.trim()?.ifBlank { null }?.toInt() ?: 0
val logsDir: File get() = quickstartDir.resolve("logs")
val stdoutLog: File get() = logsDir.resolve("stdout.log")
val errorLog: File get() = logsDir.resolve("error.log")
val requestLog: File get() = logsDir.resolve("request.log")
override val version: AemVersion
get() {
val remoteVersion = super.version
if (remoteVersion != AemVersion.UNKNOWN) {
return remoteVersion
}
val jarVersion = readVersionFromJar()
if (jarVersion != AemVersion.UNKNOWN) {
return jarVersion
}
return AemVersion.UNKNOWN
}
private fun readVersionFromJar() = readVersionFromExtractedJar() ?: readVersionFromProvidedJar() ?: AemVersion.UNKNOWN
private fun readVersionFromExtractedJar() = jar?.name?.let { AemVersion.fromJarFileName(it) }
private fun readVersionFromProvidedJar() = localManager.quickstart.distJar?.let { AemVersion.fromJar(it) }
private val startScript: Script get() = script("start")
internal fun executeStartScript() {
try {
startScript.executeVerbosely { withTimeoutMillis(localManager.startTimeout.get()) }
} catch (e: LocalInstanceException) {
throw LocalInstanceException("Instance start script failed! Check resources like disk free space, open HTTP ports etc.", e)
}
}
private val stopScript: Script get() = script("stop")
internal fun executeStopScript() {
val pidOrigin = pid
try {
stopScript.executeVerbosely { withTimeoutMillis(localManager.stopTimeout.get()) }
} catch (e: LocalInstanceException) {
throw LocalInstanceException("Instance stop script failed! Consider killing process manually using PID: $pidOrigin.", e)
}
}
private val statusScript: Script get() = script("status")
val touched: Boolean get() = dir.exists()
val created: Boolean get() = locked(LOCK_CREATE)
val installDir get() = quickstartDir.resolve("install")
val oakRun get() = OakRun(aem, this)
private fun script(name: String, os: OperatingSystem = OperatingSystem.current()) = if (os.isWindows) {
Script(this, listOf("cmd", "/C"), controlDir.resolve("$name.bat"), quickstartDir.resolve("bin/$name.bat"))
} else {
Script(this, listOf("sh"), controlDir.resolve("$name.sh"), quickstartDir.resolve("bin/$name"))
}
val localManager: LocalInstanceManager get() = aem.localInstanceManager
fun create() = localManager.create(this)
internal fun prepare() {
cleanDir(true)
unpackFiles()
correctFiles()
customizeWhenDown()
lock(LOCK_CREATE)
}
private fun correctFiles() {
FileOperations.amendFile(script("start", OperatingSystem.forName("windows")).bin) { origin ->
var result = origin
// Update 'timeout' to 'ping' as of it does not work when called from process without GUI
result = result.replace(
"timeout /T 1 /NOBREAK >nul",
"ping 127.0.0.1 -n 3 > nul"
)
// Force AEM to be launched in background
result = result.replace(
"start \"CQ\" cmd.exe /K java %CQ_JVM_OPTS% -jar %CurrDirName%\\%CQ_JARFILE% %START_OPTS%",
"cbp.exe cmd.exe /C \"java %CQ_JVM_OPTS% -jar %CurrDirName%\\%CQ_JARFILE% %START_OPTS% 1> %CurrDirName%\\logs\\stdout.log 2>&1\""
) // AEM <= 6.2
result = result.replace(
"start \"CQ\" cmd.exe /C java %CQ_JVM_OPTS% -jar %CurrDirName%\\%CQ_JARFILE% %START_OPTS%",
"cbp.exe cmd.exe /C \"java %CQ_JVM_OPTS% -jar %CurrDirName%\\%CQ_JARFILE% %START_OPTS% 1> %CurrDirName%\\logs\\stdout.log 2>&1\""
) // AEM 6.3
// Introduce missing CQ_START_OPTS injectable by parent script.
result = result.replace(
"set START_OPTS=start -c %CurrDirName% -i launchpad",
"set START_OPTS=start -c %CurrDirName% -i launchpad %CQ_START_OPTS%"
)
result
}
FileOperations.amendFile(script("start", OperatingSystem.forName("unix")).bin) { origin ->
var result = origin
// Introduce missing CQ_START_OPTS injectable by parent script.
result = result.replace(
"START_OPTS=\"start -c ${'$'}{CURR_DIR} -i launchpad\"",
"START_OPTS=\"start -c ${'$'}{CURR_DIR} -i launchpad ${'$'}{CQ_START_OPTS}\""
)
result
}
// Use java executable path explicitly to make instance working even when running from non-interactive shells (e.g as systemd service).
aem.project.fileTree(dir)
.matching { it.include(localManager.executableFiles.get()) }
.forEach { file ->
FileOperations.amendFile(file) {
it.replace(
"java ",
when (file.extension) {
"bat" -> "%JAVA_EXECUTABLE% "
else -> "\$JAVA_EXECUTABLE "
}
)
}
}
// Ensure that 'logs' directory exists
logsDir.mkdirs()
}
private fun unpackFiles() {
unpackQuickstartJar()
logger.info("Copying quickstart license from '${localManager.license}' to '$license'")
FileUtils.copyFile(localManager.license, license)
}
private fun unpackQuickstartJar() {
logger.info("Unpacking quickstart from JAR '${localManager.jar}' to directory '$quickstartDir'")
common.progressIndicator {
step = "Copying quickstart JAR"
val tmpJar = dir.resolve(localManager.jar.name)
localManager.jar.copyTo(tmpJar, true)
step = "Unpacking quickstart JAR: ${tmpJar.name} (${Formats.fileSize(tmpJar)})"
aem.project.javaexec { spec ->
spec.executable(localManager.javaExecutablePath)
spec.workingDir = dir
spec.mainClass.set("-jar")
spec.args = listOf(tmpJar.absolutePath, "-unpack")
}
if (localManager.cleanJar.get()) {
step = "Cleaning quickstart JAR"
tmpJar.delete()
}
}
}
internal fun delete() = cleanDir(create = false)
private fun cleanDir(create: Boolean) {
if (dir.exists()) {
dir.deleteRecursively()
}
if (create) {
dir.mkdirs()
}
}
internal fun customizeWhenDown() {
aem.assetManager.copyDir(FILES_PATH, dir)
copyOverrideFiles()
expandFiles()
copyInstallFiles()
makeFilesExecutable()
}
internal fun customizeWhenUp() {
auth.update()
}
private fun copyOverrideFiles() {
overridesDirs.filter { it.exists() }.forEach {
FileUtils.copyDirectory(it, dir)
}
}
private fun expandFiles() {
val propertiesAll = mapOf(
"instance" to this,
"service" to localManager.serviceComposer
) + localManager.expandProperties.get()
aem.project.fileTree(dir)
.matching { it.include(localManager.expandFiles.get()) }
.forEach { file ->
FileOperations.amendFile(file) { content ->
aem.prop.expand(content, propertiesAll, file.absolutePath)
}
}
}
private fun copyInstallFiles() {
val installFiles = localManager.install.files
if (installFiles.isNotEmpty()) {
installDir.mkdirs()
installFiles.forEach { source ->
val target = installDir.resolve(source.name)
if (!target.exists()) {
logger.info("Copying quickstart install file from '$source' to '$target'")
FileUtils.copyFileToDirectory(source, installDir)
}
}
}
}
@Suppress("TooGenericExceptionCaught")
private fun makeFilesExecutable() {
if (OperatingSystem.current().isWindows) {
return
}
aem.project.fileTree(dir)
.matching { it.include(localManager.executableFiles.get()).exclude("**/*.bat") }
.forEach { file ->
try {
FileOperations.makeExecutable(file)
} catch (e: Exception) {
logger.info("Cannot make file '$file' executable!", e)
}
}
}
fun up() = localManager.up(this)
fun down() = localManager.down(this)
fun open() = localManager.open(this)
fun kill() = localManager.kill(this)
val status: Status get() = checkStatus()
fun checkStatus(): Status {
var result = Status.UNRECOGNIZED
if (created) {
try {
val exitValue = statusScript.executeQuietly { withTimeoutMillis(localManager.statusTimeout.get()) }.exitValue
result = Status.byExitValue(exitValue).also { status ->
logger.debug("Instance status of $this is $status")
}
} catch (e: LocalInstanceException) {
logger.debug("Instance status checking error: $this", e)
logger.info("Instance status of $this is not available")
}
}
return result
}
val running: Boolean get() = created && checkStatus().running
val runnable: Boolean get() = created && checkStatus().runnable
val runningDir get() = aem.project.file(runningPath)
val runningOther get() = available && (dir != runningDir)
fun destroy() = localManager.destroy(this)
val initialized: Boolean get() = locked(LOCK_INIT)
internal fun init(callback: LocalInstance.() -> Unit) {
apply(callback)
lock(LOCK_INIT)
}
val auth by lazy { Auth(this) }
private fun lockFile(name: String) = dir.resolve("$name.lock")
internal fun lock(name: String) = FileOperations.lock(lockFile(name))
internal fun locked(name: String): Boolean = lockFile(name).exists()
fun resetPassword() {
if (running) {
throw LocalInstanceException("Instance is running so resetting password on $this is not possible!")
}
if (!initialized) {
throw LocalInstanceException("Instance is not initialized so resetting password is not possible for $this!")
}
oakRun.resetPassword(user.get(), password.get())
}
override fun toString() = "LocalInstance(name='$name', httpUrl='${httpUrl.get()}')"
init {
user.apply {
set(USER)
finalizeValue() // only 'admin' is allowed
}
}
companion object {
const val FILES_PATH = "localInstance/defaults"
const val SERVICE_PATH = "localInstance/service"
const val ENVIRONMENT = CommonOptions.ENVIRONMENT_LOCAL
const val USER = "admin"
const val LOCK_CREATE = "create"
const val LOCK_INIT = "init"
}
}