-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathbuild.gradle
More file actions
460 lines (348 loc) · 11.7 KB
/
build.gradle
File metadata and controls
460 lines (348 loc) · 11.7 KB
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import com.liferay.docker.workspace.environments.Util
import groovy.json.JsonSlurper
import java.time.format.DateTimeFormatter
plugins {
id "com.avast.gradle.docker-compose" version "0.17.10"
id "docker-common"
id "docker-database-saas"
id "docker-keycloak"
id "docker-liferay-bundle"
}
if (Boolean.getBoolean("env.mode.ci")) {
formatSource {
failOnAutoFix = true
}
}
gradle.liferayWorkspace {
dockerImageId = config.liferayDockerImageId
}
Instant now = Instant.now()
DateTimeFormatter formatter = DateTimeFormatter.
ofPattern("yyyyMMdd.HHmmss").
withZone(ZoneId.systemDefault())
String timestamp = formatter.format(now)
tasks.register("exportContainerData") {
doFirst {
List<String> existingVolumeNames = getExistingVolumeNames()
if (existingVolumeNames.isEmpty()) {
println "There is no data to export. Skipping."
return
}
File exportDir = file("exported_data/data_${config.namespace}_${timestamp}")
String hostPath = projectDir.relativePath(exportDir)
existingVolumeNames.each {
String volumeName ->
String backupFileName = "${volumeName.substring(config.namespace.length() + 1)}.tar"
if (backupFileName.equals("dumps.tar")) {
return
}
println "Creating backup of volume ${volumeName} in ${hostPath}/${backupFileName}"
waitForCommand("docker run --rm -v ${volumeName}:/source -v ${exportDir.absolutePath}:/target busybox:latest tar --create --file=/target/${backupFileName} --directory=/source .")
}
updateGradleLocalProperties(["lr.docker.environment.data.directory" : hostPath])
logger.lifecycle("\nUpdated gradle-local.properties with the new value:\nlr.docker.environment.data.directory=${hostPath}")
}
}
tasks.register("printWebserverConfig") {
onlyIf("using a webserver") {
config.useWebserver
}
doFirst {
println waitForCommand("docker exec ${config.namespace}-webserver nginx -T")
}
}
tasks.register("importContainerData") {
dependsOn ":buildDockerImage"
doFirst {
List<String> previousVolumeNames = getExistingVolumeNames()
waitForCommand("docker compose build")
waitForCommand("docker compose create")
List<String> currentVolumeNames = getExistingVolumeNames()
project.file(config.dataDirectory).listFiles().each {
File backupFile ->
if (backupFile.isFile() && !backupFile.name.endsWith(".tar")) {
return
}
String volumeName = "${config.namespace}_${backupFile.name}"
if (backupFile.isFile()) {
volumeName = volumeName.substring(0, volumeName.length() - 4)
}
if (!currentVolumeNames.contains(volumeName)) {
return
}
if (previousVolumeNames.contains(volumeName)) {
return
}
println "Restoring backup of volume ${volumeName} using ${backupFile.absolutePath}"
if (backupFile.isFile()) {
waitForCommand("docker run --rm -v ${volumeName}:/target -v ${backupFile.absolutePath}:/source.tar busybox:latest tar --extract --file=/source.tar --directory=/target/")
}
else {
waitForCommand("docker run --rm -v ${volumeName}:/target -v ${backupFile.absolutePath}:/source busybox:latest sh -c 'cp --update --recursive /source/* /target/'")
}
["liferay": 1000, "sqlserver": 10001 ].each {
entry ->
int port = entry.value
String serviceName = entry.key
if (volumeName.endsWith("_${serviceName}")) {
println "Setting volume permissions for service ${serviceName} to user/group ${port}"
waitForCommand("docker run --rm -v ${volumeName}:/target busybox:latest sh -c 'chown -R ${port}:${port} /target'")
}
}
println waitForCommand("docker run --rm -v ${volumeName}:/${volumeName} busybox:latest du -sh /${volumeName}/")
}
}
}
tasks.register("importDocumentLibraryStructure") {
doLast {
project.fileTree(project.getProperty("sourceDir")).visit {
if (it.isDirectory()) {
return
}
File newFile = project.file("configs/common/data/document_library/${it.relativePath}")
if (!newFile.parentFile.exists()) {
newFile.parentFile.mkdirs()
}
if (!newFile.exists()) {
newFile.createNewFile()
}
}
}
}
tasks.register("shareWorkspace7z") {
doLast {
if (!isProgramInstalled("7z")) {
throw new GradleException("The 7z CLI must be installed in order to share workspaces. Follow the install instructions at https://7-zip.org/download.html.")
}
String fileListFileName = "shared_workspaces/workspace_${config.namespace}_${timestamp}.txt"
String archiveFileName = "shared_workspaces/workspace_${config.namespace}_${timestamp}.7z"
File fileListFile = file(fileListFileName)
fileListFile.parentFile.mkdirs()
fileListFile.text = fileTree('.') {
exclude ".gitkeep"
exclude ".gitignore"
exclude ".git"
exclude ".gradle"
exclude "binds"
exclude "buildSrc/build"
exclude "buildSrc/.gradle"
exclude "dumps/*"
exclude "shared_workspaces"
exclude {
FileTreeElement fileTreeElement ->
fileTreeElement.relativePath.pathString.startsWith("exported_data/") &&
!fileTreeElement.relativePath.pathString.startsWith(config.dataDirectory)
}
include "${config.dataDirectory}/**"
include "**/*"
}.files.collect {
File file ->
project.relativePath(file)
}.join("\n")
try {
waitForCommand("7z a -m0=lzma2 -mx=1 -bsp2 ${archiveFileName} -i@${fileListFileName}")
}
finally {
fileListFile.delete()
}
println "New workspace archive file: ${archiveFileName}"
}
}
tasks.register("shareWorkspaceZip", Zip) {
archiveFileName = provider {
"workspace_${config.namespace}_${timestamp}.zip"
}
destinationDirectory = file 'shared_workspaces'
doLast {
logger.lifecycle "\nWorkspace zip: ${archiveFile.get()}\n"
}
exclude ".gitkeep"
exclude ".gitignore"
exclude ".git"
exclude ".gradle"
exclude "binds"
exclude "buildSrc/build"
exclude "buildSrc/.gradle"
exclude "dumps/*"
exclude "shared_workspaces"
exclude {
FileTreeElement fileTreeElement ->
fileTreeElement.relativePath.pathString.startsWith("exported_data/") &&
!fileTreeElement.relativePath.pathString.startsWith(config.dataDirectory)
}
from '.'
include "${config.dataDirectory}/**"
include "**/*"
outputs.upToDateWhen {
false
}
zip64 = true
}
tasks.register("shareWorkspace") {
if (isProgramInstalled("7z")) {
dependsOn ":shareWorkspace7z"
}
else {
dependsOn ":shareWorkspaceZip"
}
}
tasks.register("restart") {
dependsOn ":start"
dependsOn ":stop"
}
tasks.register("start") {
dependsOn ":composeUp"
mustRunAfter ":stop"
}
tasks.register("stop") {
dependsOn ":composeDown"
}
buildDockerImage {
doFirst {
waitForCommand("docker pull ${gradle.liferayWorkspace.dockerImageLiferay}", null, System.out)
}
onlyIf("using the Liferay service") {
config.useLiferay
}
dependsOn ":checkForLiferayLicense"
dependsOn ":prepareJDBCDriver"
dependsOn ":prepareSAXParser"
mustRunAfter ":importDatabaseDumps"
}
clean {
dependsOn ":cleanPrepareKeycloakSelfSignedCert"
dependsOn ":cleanPrepareLiferayKeystoreFile"
dependsOn ":cleanPrepareJDBCDriver"
dependsOn ":cleanPrepareHotfixes"
dependsOn ":cleanPrepareSAXParser"
dependsOn ":cleanPrepareXugglerJar"
dependsOn ":cleanDownloadYourKitAgentZip"
dependsOn ":cleanPrepareYourKitAgent"
}
dockerDeploy {
dependsOn ":prepareJDBCDriver"
dependsOn ":prepareHotfixes"
dependsOn ":prepareSAXParser"
dependsOn ":prepareXugglerJar"
dependsOn ":prepareYourKitAgent"
}
composeBuild {
dependsOn ":prepareLiferayKeystoreFile"
}
composeUp {
onlyIf("there are Compose files") {
!config.composeFiles.isEmpty()
}
dependsOn ":buildDockerImage"
dependsOn ":importContainerData"
dependsOn ":importDatabaseDumps"
doFirst {
println "Using config:\n\n${config}\n\n"
}
finalizedBy ":listAdminUsers"
finalizedBy ":printBundleInfo"
finalizedBy ":printWebserverConfig"
}
Map<String, String> environmentMap = [:]
environmentMap.put "DATA_DIRECTORY", config.dataDirectory
environmentMap.put "DATABASE_NAME", config.databaseName
environmentMap.put "DATABASE_PASSWORD", config.databasePassword
environmentMap.put "DATABASE_USER", config.databaseUser
environmentMap.put "NAMESPACE", config.namespace
if (config.useClustering) {
environmentMap.put "LIFERAY_CLUSTER_NODES", config.clusterNodes
}
if (config.useLiferay) {
environmentMap.put "LIFERAY_IMAGE_NAME", config.liferayDockerImageId
}
environmentMap.put("COMPOSE_FILE", config.composeFiles.join(File.pathSeparator))
environmentMap.put("COMPOSE_PROJECT_NAME", config.namespace)
String validDLStoreTypes = "advanced,db,s3,simple"
if (!validDLStoreTypes.contains(config.dlStore)) {
throw new GradleException("Invalid DL store type provided. Please see gradle.properties file for valid store types.")
}
if (config.dlStore == "advanced") {
environmentMap.put("DL_STORE_PATH", config.dlStorePath)
}
if (config.dlStore == "s3") {
environmentMap.put("S3_ACCESS_KEY", config.s3AccessKey)
environmentMap.put("S3_BUCKET_NAME", config.s3BucketName)
environmentMap.put("S3_REGION", config.s3Region)
environmentMap.put("S3_SECRET_KEY", config.s3SecretKey)
}
environmentMap.put("DL_STORE_CLASS", config.dlStoreClass)
environmentMap.put("MEDIA_PREVIEW_ENABLED", config.mediaPreviewEnabled)
file("ports.env").withInputStream {
portsFile ->
Properties ports = new Properties()
ports.load(portsFile)
if (config.useClustering) {
environmentMap.putAll ports
return
}
Set<Integer> projectPorts = getProjectBoundHostPorts()
environmentMap.putAll ports.collectEntries {
key, value ->
if (!value.contains("-")) {
return [key, value]
}
String[] parts = value.split("-")
Integer portLowest = parts[0] as Integer
Integer portHighest = parts[1] as Integer
Integer availablePort = getFirstAvailablePort(portLowest, portHighest, projectPorts)
if (availablePort == null) {
throw new GradleException("No free port found in range: ${value}. Please shut down other projects, or expand the port range in the ports.env file.")
}
return [key, availablePort.toString()]
}
}
if (config.useWebserver) {
environmentMap.put("WEBSERVER_HOSTNAMES", config.webserverHostnames)
environmentMap.put("WEBSERVER_MODSECURITY_ENABLED", config.modSecurityEnabled)
environmentMap.put("WEBSERVER_PROTOCOL", config.webserverProtocol)
environmentMap.put("WEBSERVER_PROTOCOL_UPPERCASE", config.webserverProtocol.toUpperCase())
if (config.webserverProtocol == "http") {
environmentMap.put("WEBSERVER_CONTAINER_PORT", "8080")
environmentMap.put("LIFERAY_CONTAINER_PORT", "80")
environmentMap.put("WEBSERVER_HOST_PORT", environmentMap["WEBSERVER_HTTP_PORT"])
}
if (config.webserverProtocol == "https") {
environmentMap.put("WEBSERVER_CONTAINER_PORT", "8443")
environmentMap.put("LIFERAY_CONTAINER_PORT", "443")
environmentMap.put("WEBSERVER_HOST_PORT", environmentMap["WEBSERVER_HTTPS_PORT"])
}
}
if (config.useKeycloak) {
if (environmentMap["LIFERAY_PORT"].contains("-")) {
throw new GradleException("Detected port range for Liferay. Please provide a single port for Liferay when using keycloak.")
}
if (environmentMap["KEYCLOAK_PORT"].contains("-")) {
throw new GradleException("Detected port range for Keycloak. Please provide a single port for Keycloak.")
}
}
config.serviceVersions.each {
String name, String version ->
if (config.services.contains(name)) {
environmentMap.put("${name.toUpperCase()}_VERSION", version)
}
}
if (config.services.contains("elasticsearch")) {
environmentMap.put("ELASTICSEARCH_MAJOR_VERSION", config.elasticsearchMajorVersion)
}
file('.env').withOutputStream {
BufferedOutputStream envFileOutputStream ->
environmentMap.forEach {
key, value ->
envFileOutputStream << key << "=" << value << "\n"
}
}
dockerCompose {
captureContainersOutput = true
environment.putAll environmentMap
projectName = config.namespace
removeVolumes = config.clearVolumeData
useComposeFiles = config.composeFiles
waitForTcpPorts = false
// DEBUG: Set to true if container startup is failing
retainContainersOnStartupFailure = false
}