forked from wttech/gradle-aem-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalInstance.kt
421 lines (331 loc) · 12.6 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
package com.cognifide.gradle.aem.common.instance
import com.cognifide.gradle.aem.AemException
import com.cognifide.gradle.aem.AemExtension
import com.cognifide.gradle.aem.common.file.FileOperations
import com.cognifide.gradle.aem.common.instance.local.Script
import com.cognifide.gradle.aem.common.instance.local.Status
import com.cognifide.gradle.aem.common.utils.Formats
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.StringUtils
import org.gradle.internal.os.OperatingSystem
import org.gradle.util.GFileUtils
import java.io.File
import java.io.Serializable
class LocalInstance private constructor(aem: AemExtension) : AbstractInstance(aem), Serializable {
override val user: String = USER
override lateinit var password: String
var debugPort: Int = 5005
@get:JsonIgnore
val jvmOptsDefaults: List<String>
get() = mutableListOf<String>().apply {
if (debugPort > 0) {
add("-Xdebug")
add("-Xrunjdwp:transport=dt_socket,address=$debugPort,server=y,suspend=n")
}
if (password != Instance.PASSWORD_DEFAULT) {
add("-Dadmin.password=$password")
}
}
@get:JsonIgnore
var jvmOpts: List<String> = listOf(
"-server", "-Xmx2048m", "-XX:MaxPermSize=512M", "-Djava.awt.headless=true"
)
@get:JsonProperty("jvmOpts")
val jvmOptsString: String
get() = (jvmOptsDefaults + jvmOpts).joinToString(" ")
@get:JsonIgnore
var startOpts: List<String> = listOf()
@get:JsonProperty("startOpts")
val startOptsString: String
get() = startOpts.joinToString(" ")
@get:JsonIgnore
val runModesDefault
get() = listOf(type.name.toLowerCase())
@get:JsonIgnore
var runModes: List<String> = listOf(ENVIRONMENT)
@get:JsonProperty("runModes")
val runModesString: String
get() = (runModesDefault + runModes).joinToString(",")
@get:JsonIgnore
val dir: File
get() = File(aem.localInstanceManager.rootDir, id)
@get:JsonIgnore
val overridesDirs: List<File>
get() = listOf(
File(manager.overridesDir, "common"),
File(manager.overridesDir, id)
)
@get:JsonIgnore
val jar: File
get() = File(dir, "aem-quickstart.jar")
@get:JsonIgnore
val quickstartDir: File
get() = File(dir, "crx-quickstart")
@get:JsonIgnore
val license: File
get() = File(dir, "license.properties")
@get:JsonIgnore
val versionFile
get() = File(dir, "version.txt")
override val version: String
get() {
var result = super.version
if (result == Formats.VERSION_UNKNOWN.version && versionFile.exists()) {
result = versionFile.readText()
}
return result
}
fun saveVersion() {
if (version != Formats.VERSION_UNKNOWN.version) {
versionFile.writeText(version)
}
}
@get:JsonIgnore
val startScript: Script
get() = binScript("start")
@get:JsonIgnore
val stopScript: Script
get() = binScript("stop")
@get:JsonIgnore
val statusScript: Script
get() = binScript("status")
@get:JsonIgnore
val created: Boolean
get() = locked(LOCK_CREATE)
@get:JsonIgnore
val initialized: Boolean
get() = locked(LOCK_INIT)
@get:JsonIgnore
val installDir: File
get() = File(quickstartDir, "install")
private fun binScript(name: String, os: OperatingSystem = OperatingSystem.current()): Script {
return if (os.isWindows) {
Script(this, listOf("cmd", "/C"), File(dir, "$name.bat"), File(quickstartDir, "bin/$name.bat"))
} else {
Script(this, listOf("sh"), File(dir, name), File(quickstartDir, "bin/$name"))
}
}
@get:JsonIgnore
val manager: LocalInstanceManager
get() = aem.localInstanceManager
fun create() {
if (created) {
logger.info(("Instance already created: $this"))
return
}
logger.info("Creating: $this")
cleanDir(true)
copyFiles()
validateFiles()
unpackFiles()
correctFiles()
customize()
lock(LOCK_CREATE)
logger.info("Created: $this")
}
private fun copyFiles() {
GFileUtils.mkdirs(dir)
logger.info("Copying quickstart JAR '$jar' to directory '$quickstartDir'")
manager.quickstart.jar?.let { FileUtils.copyFile(it, jar) }
logger.info("Copying quickstart license '$license' to directory '$quickstartDir'")
manager.quickstart.license?.let { FileUtils.copyFile(it, license) }
}
private fun validateFiles() {
if (!jar.exists()) {
throw AemException("Instance JAR file not found at path: ${jar.absolutePath}. Is instance JAR URL configured?")
}
if (!license.exists()) {
throw AemException("License file not found at path: ${license.absolutePath}. Is instance license URL configured?")
}
}
private fun correctFiles() {
FileOperations.amendFile(binScript("start", OperatingSystem.forName("windows")).bin) { origin ->
var result = origin
// Force CMD to be launched in closable window mode.
result = result.replace(
"start \"CQ\" cmd.exe /K",
"start /min \"CQ\" cmd.exe /C"
) // AEM <= 6.2
result = result.replace(
"start \"CQ\" cmd.exe /C",
"start /min \"CQ\" cmd.exe /C"
) // 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(binScript("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
}
// Ensure that 'logs' directory exists
GFileUtils.mkdirs(File(quickstartDir, "logs"))
}
private fun unpackFiles() {
logger.info("Unpacking quickstart from JAR '$jar' to directory '$quickstartDir'")
aem.progressIndicator {
message = "Unpacking quickstart JAR: ${jar.name}, size: ${Formats.size(jar)}"
aem.project.javaexec { spec ->
spec.workingDir = dir
spec.main = "-jar"
spec.args = listOf(jar.name, "-unpack")
}
}
}
private fun cleanDir(create: Boolean) {
if (dir.exists()) {
dir.deleteRecursively()
}
if (create) {
dir.mkdirs()
}
}
fun customize() {
logger.info("Customizing: $this")
FileOperations.copyResources(FILES_PATH, dir, false)
overridesDirs.filter { it.exists() }.forEach {
FileUtils.copyDirectory(it, dir)
}
val propertiesAll = mapOf("instance" to this) + properties + manager.expandProperties
FileOperations.amendFiles(dir, manager.expandFiles) { file, source ->
aem.props.expand(source, propertiesAll, file.absolutePath)
}
FileOperations.amendFile(binScript("start", OperatingSystem.forName("windows")).bin) { origin ->
var result = origin
// Update window title
val previousWindowTitle = StringUtils.substringBetween(origin, "start /min \"", "\" cmd.exe ")
if (previousWindowTitle != null) {
result = StringUtils.replace(result,
"start /min \"$previousWindowTitle\" cmd.exe ",
"start /min \"$windowTitle\" cmd.exe "
)
}
result
}
val installFiles = manager.install.files
if (installFiles.isNotEmpty()) {
GFileUtils.mkdirs(installDir)
installFiles.forEach { source ->
val target = File(installDir, source.name)
if (!target.exists()) {
logger.info("Copying quickstart install file from '$source' to '$target'")
FileUtils.copyFileToDirectory(source, installDir)
}
}
}
logger.info("Customized: $windowTitle")
}
fun up() {
if (!created) {
logger.info("Instance not created, so it could not be up: $this")
return
}
val status = checkStatus()
if (status == Status.RUNNING) {
logger.info("Instance already running. No need to start: $this")
return
}
customize()
try {
logger.info("Executing start script: $startScript")
startScript.executeAsync()
} catch (e: InstanceException) {
throw InstanceException("Instance start script failed! Check resources like disk free space, open HTTP ports etc.", e)
}
}
fun down() {
if (!created) {
logger.info("Instance not created, so it could not be down: $this")
return
}
val status = checkStatus()
if (status != Status.RUNNING) {
logger.info("Instance is not running (reports status '$status'). No need to stop: $this")
return
}
try {
logger.info("Executing stop script: $stopScript")
stopScript.executeAsync()
} catch (e: InstanceException) {
throw InstanceException("Instance stop script failed!", e)
}
try {
sync.osgiFramework.stop()
} catch (e: InstanceException) {
// ignore, fallback for sure
}
}
@get:JsonIgnore
val status: Status
get() = checkStatus()
fun checkStatus(): Status {
if (!created) {
return Status.UNKNOWN
}
return try {
val procResult = statusScript.executeSync()
Status.byExitCode(procResult.exitValue)
} catch (e: InstanceException) {
logger.info("Instance status not available: $this")
logger.debug("Instance status error", e)
Status.UNKNOWN
}
}
fun init() {
saveVersion()
if (!initialized) {
logger.info("Initializing: $this")
manager.initOptions(this)
lock(LOCK_INIT)
}
}
fun destroy() {
logger.info("Destroying: $this")
cleanDir(false)
logger.info("Destroyed: $this")
}
private fun lockFile(name: String): File = File(dir, "$name.lock")
fun lock(name: String) = FileOperations.lock(lockFile(name))
fun locked(name: String): Boolean = lockFile(name).exists()
@get:JsonIgnore
val windowTitle get() = "LocalInstance(name='$name', httpUrl='$httpUrl'" +
(version.takeIf { it != Formats.VERSION_UNKNOWN.version }?.run { ", version=$this" } ?: "") +
", debugPort=$debugPort, user='$user', password='${Formats.asPassword(password)}')"
override fun toString(): String {
return "LocalInstance(name='$name', httpUrl='$httpUrl')"
}
companion object {
const val FILES_PATH = "instance"
const val ENVIRONMENT = "local"
const val USER = "admin"
const val LOCK_CREATE = "create"
const val LOCK_INIT = "init"
fun create(aem: AemExtension, httpUrl: String, configurer: LocalInstance.() -> Unit): LocalInstance {
return LocalInstance(aem).apply {
val instanceUrl = InstanceUrl.parse(httpUrl)
if (instanceUrl.user != USER) {
throw InstanceException("User '${instanceUrl.user}' (other than 'admin') is not allowed while using local instance(s).")
}
this.httpUrl = instanceUrl.httpUrl
this.password = instanceUrl.password
this.id = instanceUrl.id
this.debugPort = instanceUrl.debugPort
this.environment = aem.env
this.apply(configurer)
}
}
fun create(aem: AemExtension, httpUrl: String): LocalInstance {
return create(aem, httpUrl) {}
}
}
}