From 64b0152f73ceae7efe6c14fef7bc09c4c647f70f Mon Sep 17 00:00:00 2001 From: IlyaMuravjov Date: Thu, 24 Aug 2023 15:26:20 +0300 Subject: [PATCH] Make jar extraction multi-process safe --- .../main/kotlin/org/utbot/common/JarUtils.kt | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/utbot-core/src/main/kotlin/org/utbot/common/JarUtils.kt b/utbot-core/src/main/kotlin/org/utbot/common/JarUtils.kt index ac7a9e630c..765d520514 100644 --- a/utbot-core/src/main/kotlin/org/utbot/common/JarUtils.kt +++ b/utbot-core/src/main/kotlin/org/utbot/common/JarUtils.kt @@ -4,18 +4,29 @@ import java.io.File import java.net.URL import java.nio.file.Files import java.nio.file.StandardCopyOption +import java.util.* object JarUtils { private const val UNKNOWN_MODIFICATION_TIME = 0L fun extractJarFileFromResources(jarFileName: String, jarResourcePath: String, targetDirectoryName: String): File { - val targetDirectory = - Files.createDirectories(utBotTempDirectory.toFile().resolve(targetDirectoryName).toPath()).toFile() - return targetDirectory.resolve(jarFileName).also { jarFile -> - val resource = this::class.java.classLoader.getResource(jarResourcePath) - ?: error("Unable to find \"$jarResourcePath\" in resources, make sure it's on the classpath") - updateJarIfRequired(jarFile, resource) + val resource = this::class.java.classLoader.getResource(jarResourcePath) + ?: error("Unable to find \"$jarResourcePath\" in resources, make sure it's on the classpath") + + val targetDirectory = utBotTempDirectory.toFile().resolve(targetDirectoryName).toPath() + fun extractToSubDir(subDir: String) = + Files.createDirectories(targetDirectory.resolve(subDir)).toFile().resolve(jarFileName).also { jarFile -> + updateJarIfRequired(jarFile, resource) + } + + // We attempt to always extract jars to same locations, to avoid eating up drive space with + // every UtBot launch, but we may fail to do so if multiple processes are running in parallel. + repeat(10) { i -> + runCatching { + return extractToSubDir(i.toString()) + } } + return extractToSubDir(UUID.randomUUID().toString()) } private fun updateJarIfRequired(jarFile: File, resource: URL) {