Skip to content

Commit 8ffdeb4

Browse files
committed
Refactor RD processes
1 parent a884f5c commit 8ffdeb4

File tree

12 files changed

+58
-117
lines changed

12 files changed

+58
-117
lines changed

utbot-framework-api/src/main/kotlin/org/utbot/framework/process/CommonProcessArgs.kt

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,17 @@ package org.utbot.framework.process
22

33
import org.utbot.common.osSpecificJavaExecutable
44
import org.utbot.framework.plugin.services.JdkInfoService
5-
import org.utbot.rd.rdPortArgument
65
import java.io.File
76
import java.nio.file.Path
87
import kotlin.io.path.pathString
98

109
private val javaExecutablePathString: Path
1110
get() = JdkInfoService.jdkInfoProvider.info.path.resolve("bin${File.separatorChar}${osSpecificJavaExecutable()}")
1211

13-
// TODO use it in EngineProcess and InstrumentedProcess
14-
fun withCommonProcessCommandLineArgs(
15-
processSpecificArgs: List<String>,
12+
fun obtainCommonProcessCommandLineArgs(
1613
debugPort: Int,
1714
runWithDebug: Boolean,
1815
suspendExecutionInDebugMode: Boolean,
19-
rdPort: Int
2016
): List<String> = buildList {
2117
val suspendValue = if (suspendExecutionInDebugMode) "y" else "n"
2218
val debugArgument = "-agentlib:jdwp=transport=dt_socket,server=n,suspend=${suspendValue},quiet=y,address=$debugPort"
@@ -28,6 +24,4 @@ fun withCommonProcessCommandLineArgs(
2824
addAll(javaVersionSpecificArgs)
2925
}
3026
debugArgument?.let { add(it) }
31-
addAll(processSpecificArgs)
32-
add(rdPortArgument(rdPort))
3327
}

utbot-framework/build.gradle

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
configurations {
2+
fetchSpringAnalyzerJar
3+
}
4+
15
dependencies {
26

37
api project(':utbot-fuzzers')
@@ -36,4 +40,12 @@ dependencies {
3640

3741
implementation group: 'com.github.UnitTestBot.ksmt', name: 'ksmt-core', version: ksmtVersion
3842
implementation group: 'com.github.UnitTestBot.ksmt', name: 'ksmt-z3', version: ksmtVersion
43+
44+
fetchSpringAnalyzerJar project(path: ':utbot-spring-analyzer', configuration: 'springAnalyzerJar')
45+
}
46+
47+
processResources {
48+
from(configurations.fetchSpringAnalyzerJar) {
49+
into "lib"
50+
}
3951
}

utbot-framework/src/main/kotlin/org/utbot/framework/codegen/domain/Domain.kt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package org.utbot.framework.codegen.domain
33
import org.utbot.framework.DEFAULT_EXECUTION_TIMEOUT_IN_INSTRUMENTED_PROCESS_MS
44
import org.utbot.framework.codegen.domain.builtin.mockitoClassId
55
import org.utbot.framework.codegen.domain.builtin.ongoingStubbingClassId
6-
import org.utbot.framework.codegen.domain.context.CgContext
76
import org.utbot.framework.codegen.domain.models.CgClassId
87
import org.utbot.framework.codegen.tree.argumentsClassId
98
import org.utbot.framework.plugin.api.BuiltinClassId
@@ -751,7 +750,7 @@ sealed class TypeReplacementApproach {
751750
*
752751
* Currently used in Spring applications only.
753752
*/
754-
class ReplaceIfPossible(val configFqn: String) : TypeReplacementApproach()
753+
class ReplaceIfPossible(val config: String) : TypeReplacementApproach()
755754
}
756755

757756
abstract class DependencyInjectionFramework(

utbot-framework/src/main/kotlin/org/utbot/framework/process/SpringAnalyzerProcess.kt

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import org.utbot.rd.generated.synchronizationModel
1515
import org.utbot.rd.loggers.UtRdKLogger
1616
import org.utbot.rd.loggers.setupRdLogger
1717
import org.utbot.rd.onSchedulerBlocking
18+
import org.utbot.rd.rdPortArgument
1819
import org.utbot.rd.startBlocking
1920
import org.utbot.rd.startUtProcessWithRdServer
2021
import org.utbot.rd.terminateOnException
@@ -35,7 +36,7 @@ class SpringAnalyzerProcess private constructor(
3536
) : ProcessWithRdServer by rdProcess {
3637

3738
companion object {
38-
private fun obtainProcessSpecificCommandLineArgs(): List<String> {
39+
private fun obtainProcessSpecificCommandLineArgs(port: Int): List<String> {
3940
val jarFile =
4041
Files.createDirectories(utBotTempDirectory.toFile().resolve("spring-analyzer").toPath())
4142
.toFile().resolve(SPRING_ANALYZER_JAR_FILENAME)
@@ -46,21 +47,20 @@ class SpringAnalyzerProcess private constructor(
4647
return listOf(
4748
"-Dorg.apache.commons.logging.LogFactory=org.utbot.rd.loggers.RDApacheCommonsLogFactory",
4849
"-jar",
49-
jarFile.path
50+
jarFile.path,
51+
rdPortArgument(port)
5052
)
5153
}
5254

5355
fun createBlocking() = runBlocking { SpringAnalyzerProcess() }
5456

5557
suspend operator fun invoke(): SpringAnalyzerProcess = LifetimeDefinition().terminateOnException { lifetime ->
5658
val rdProcess = startUtProcessWithRdServer(lifetime) { port ->
57-
val cmd = withCommonProcessCommandLineArgs(
58-
obtainProcessSpecificCommandLineArgs(),
59+
val cmd = obtainCommonProcessCommandLineArgs(
5960
debugPort = UtSettings.springAnalyzerProcessDebugPort,
6061
runWithDebug = UtSettings.runSpringAnalyzerProcessWithDebug,
6162
suspendExecutionInDebugMode = UtSettings.suspendSpringAnalyzerProcessExecutionInDebugMode,
62-
rdPort = port
63-
)
63+
) + obtainProcessSpecificCommandLineArgs(port)
6464
val process = ProcessBuilder(cmd)
6565
.directory(Files.createTempDirectory(utBotTempDirectory, "spring-analyzer").toFile())
6666
.start()

utbot-instrumentation/src/main/kotlin/org/utbot/instrumentation/process/InstrumentedProcessMain.kt

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,6 @@ import org.utbot.rd.generated.settingsModel
2424
import org.utbot.rd.generated.synchronizationModel
2525
import org.utbot.rd.loggers.UtRdRemoteLoggerFactory
2626
import java.io.File
27-
import java.io.IOException
28-
import java.io.OutputStream
29-
import java.io.PrintStream
3027
import java.net.URLClassLoader
3128
import java.security.AllPermission
3229
import kotlin.time.Duration
@@ -62,23 +59,6 @@ const val DISABLE_SANDBOX_OPTION = "--disable-sandbox"
6259
private val logger = getLogger<InstrumentedProcessMain>()
6360
private val messageFromMainTimeout: Duration = 120.seconds
6461

65-
private fun closeStandardStreams() {
66-
// we should change out/err streams as not to spend time on user output
67-
// and also because rd default logging system writes some initial values to stdout, polluting it as well
68-
val tmpStream = PrintStream(object : OutputStream() {
69-
override fun write(b: Int) {}
70-
})
71-
val prevOut = System.out
72-
val prevError = System.err
73-
System.setOut(tmpStream)
74-
System.setErr(tmpStream)
75-
// stdin/stderr should be closed as not to leave hanging descriptors
76-
// and we cannot log any exceptions here as rd remote logging is still not configured
77-
// so we pass any exceptions
78-
silent { prevOut.close() }
79-
silent { prevError.close() }
80-
}
81-
8262
interface DummyForMockitoWarmup {
8363
fun method1()
8464
}

utbot-instrumentation/src/main/kotlin/org/utbot/instrumentation/process/InstrumentedProcessRunner.kt

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ import mu.KotlinLogging
44
import org.utbot.common.*
55
import org.utbot.common.scanForResourcesContaining
66
import org.utbot.common.utBotTempDirectory
7-
import org.utbot.framework.plugin.services.JdkInfoService
87
import org.utbot.framework.UtSettings
98
import org.utbot.framework.plugin.services.WorkingDirService
10-
import org.utbot.framework.process.OpenModulesContainer
9+
import org.utbot.framework.process.obtainCommonProcessCommandLineArgs
1110
import org.utbot.instrumentation.agent.DynamicClassTransformer
1211
import org.utbot.rd.rdPortArgument
1312
import java.io.File
@@ -16,14 +15,11 @@ private val logger = KotlinLogging.logger {}
1615

1716
class InstrumentedProcessRunner {
1817
private val cmds: List<String> by lazy {
19-
val debugCmd = listOfNotNull(DEBUG_RUN_CMD.takeIf { UtSettings.runInstrumentedProcessWithDebug })
20-
val javaVersionSpecificArguments = OpenModulesContainer.javaVersionSpecificArguments
21-
val pathToJava = JdkInfoService.provide().path
22-
23-
listOf(pathToJava.resolve("bin${File.separatorChar}${osSpecificJavaExecutable()}").toString()) +
24-
debugCmd +
25-
javaVersionSpecificArguments +
26-
listOf("-javaagent:$jarFile", "-ea", "-jar", "$jarFile")
18+
obtainCommonProcessCommandLineArgs(
19+
debugPort = UtSettings.instrumentedProcessDebugPort,
20+
runWithDebug = UtSettings.runInstrumentedProcessWithDebug,
21+
suspendExecutionInDebugMode = UtSettings.suspendInstrumentedProcessExecutionInDebugMode
22+
) + listOf("-javaagent:$jarFile", "-ea", "-jar", "$jarFile")
2723
}
2824

2925
fun start(rdPort: Int): Process {
@@ -53,13 +49,9 @@ class InstrumentedProcessRunner {
5349
}
5450

5551
companion object {
56-
private fun suspendValue(): String = if (UtSettings.suspendInstrumentedProcessExecutionInDebugMode) "y" else "n"
57-
5852
private const val UTBOT_INSTRUMENTATION = "utbot-instrumentation"
5953
private const val INSTRUMENTATION_LIB = "lib"
6054

61-
private val DEBUG_RUN_CMD = "-agentlib:jdwp=transport=dt_socket,server=n,suspend=${suspendValue()},quiet=y,address=${UtSettings.instrumentedProcessDebugPort}"
62-
6355
private val NULL_FILE_PATH: String = if (System.getProperty("os.name").startsWith("Windows")) {
6456
"NUL"
6557
} else {

utbot-instrumentation/src/main/kotlin/org/utbot/instrumentation/rd/InstrumentedProcess.kt

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import org.utbot.rd.generated.loggerModel
1717
import org.utbot.rd.generated.synchronizationModel
1818
import org.utbot.rd.loggers.UtRdKLogger
1919
import org.utbot.rd.loggers.UtRdRemoteLogger
20+
import org.utbot.rd.loggers.setupRdLogger
2021
import org.utbot.rd.onSchedulerBlocking
2122
import org.utbot.rd.startUtProcessWithRdServer
2223
import org.utbot.rd.terminateOnException
@@ -63,21 +64,7 @@ class InstrumentedProcess private constructor(
6364
logger.trace("rd process started")
6465

6566
val proc = InstrumentedProcess(classLoader, rdProcess)
66-
67-
// currently we do not specify log level for different categories in instrumented process
68-
// though it is possible with some additional map on categories -> consider performance
69-
proc.loggerModel.getCategoryMinimalLogLevel.set { _ ->
70-
// this logLevel is obtained from KotlinLogger
71-
rdLogger.logLevel.ordinal
72-
}
73-
74-
proc.loggerModel.log.advise(proc.lifetime) {
75-
val logLevel = UtRdRemoteLogger.logLevelValues[it.logLevelOrdinal]
76-
// assume throwable already in message
77-
rdLogger.log(logLevel, it.message, null)
78-
}
79-
80-
rdProcess.protocol.synchronizationModel.initRemoteLogging.fire(Unit)
67+
setupRdLogger(rdProcess, proc.loggerModel, rdLogger)
8168

8269
proc.lifetime.onTermination {
8370
logger.trace { "process is terminating" }

utbot-intellij/build.gradle.kts

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -133,11 +133,6 @@ repositories {
133133
maven("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies")
134134
}
135135

136-
val fetchSpringAnalyzerJar: Configuration by configurations.creating {
137-
isCanBeResolved = true
138-
isCanBeConsumed = false
139-
}
140-
141136
dependencies {
142137
implementation(group ="com.jetbrains.rd", name = "rd-framework", version = rdVersion)
143138
implementation(group ="com.jetbrains.rd", name = "rd-core", version = rdVersion)
@@ -173,8 +168,6 @@ dependencies {
173168

174169
implementation(project(":utbot-android-studio"))
175170

176-
fetchSpringAnalyzerJar(project(":utbot-spring-analyzer", "springAnalyzerJar"))
177-
178171
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
179172
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
180173

@@ -191,9 +184,3 @@ dependencies {
191184
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$junit5Version")
192185
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:$junit5Version")
193186
}
194-
195-
tasks.processResources {
196-
from(fetchSpringAnalyzerJar) {
197-
into("lib")
198-
}
199-
}

utbot-intellij/src/main/kotlin/org/utbot/intellij/plugin/generator/UtTestsDialogProcessor.kt

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ import org.utbot.framework.plugin.api.util.LockFile
5555
import org.utbot.framework.plugin.api.util.withStaticsSubstitutionRequired
5656
import org.utbot.framework.plugin.services.JdkInfoService
5757
import org.utbot.framework.plugin.services.WorkingDirService
58-
import org.utbot.framework.process.generated.GetSpringBeanQualifiedNamesParams
5958
import org.utbot.intellij.plugin.generator.CodeGenerationController.generateTests
6059
import org.utbot.intellij.plugin.models.GenerateTestsModel
6160
import org.utbot.intellij.plugin.models.packageName
@@ -162,7 +161,7 @@ object UtTestsDialogProcessor {
162161
val springConfigClass = when (val approach = model.typeReplacementApproach) {
163162
TypeReplacementApproach.DoNotReplace -> null
164163
is TypeReplacementApproach.ReplaceIfPossible ->
165-
approach.configFqn.takeUnless { it.endsWith(".xml") }?.let {
164+
approach.config.takeUnless { it.endsWith(".xml") }?.let {
166165
JavaPsiFacade.getInstance(project).findClass(it, GlobalSearchScope.projectScope(project)) ?:
167166
error("Can't find configuration class $it")
168167
}
@@ -223,11 +222,10 @@ object UtTestsDialogProcessor {
223222
if (!model.useSpringAnalyzer) emptyList()
224223
else when (val approach = model.typeReplacementApproach) {
225224
TypeReplacementApproach.DoNotReplace -> emptyList()
226-
is TypeReplacementApproach.ReplaceIfPossible -> process.getSpringBeanQualifiedNames(
227-
GetSpringBeanQualifiedNamesParams(
228-
(buildDirs + classpathList).toTypedArray(),
229-
approach.configFqn
230-
)
225+
is TypeReplacementApproach.ReplaceIfPossible ->
226+
process.getSpringBeanQualifiedNames(
227+
buildDirs + classpathList,
228+
approach.config
231229
).also { logger.info { "Detected Spring Beans: $it" } }
232230
}
233231

utbot-intellij/src/main/kotlin/org/utbot/intellij/plugin/process/EngineProcess.kt

Lines changed: 18 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,10 @@ import org.utbot.framework.codegen.domain.*
1919
import org.utbot.framework.codegen.tree.ututils.UtilClassKind
2020
import org.utbot.framework.plugin.api.*
2121
import org.utbot.framework.plugin.services.JdkInfo
22-
import org.utbot.framework.plugin.services.JdkInfoService
2322
import org.utbot.framework.plugin.services.WorkingDirService
24-
import org.utbot.framework.process.OpenModulesContainer
2523
import org.utbot.framework.process.generated.*
2624
import org.utbot.framework.process.generated.MethodDescription
25+
import org.utbot.framework.process.obtainCommonProcessCommandLineArgs
2726
import org.utbot.framework.util.Conflict
2827
import org.utbot.framework.util.ConflictTriggers
2928
import org.utbot.instrumentation.util.KryoHelper
@@ -94,15 +93,6 @@ class EngineProcess private constructor(val project: Project, private val classN
9493

9594
private val log4j2ConfigSwitch = "-Dlog4j2.configurationFile=${log4j2ConfigFile.canonicalPath}"
9695

97-
private fun suspendValue(): String = if (UtSettings.suspendEngineProcessExecutionInDebugMode) "y" else "n"
98-
99-
private val debugArgument: String?
100-
get() = "-agentlib:jdwp=transport=dt_socket,server=n,suspend=${suspendValue()},quiet=y,address=${UtSettings.engineProcessDebugPort}"
101-
.takeIf { UtSettings.runEngineProcessWithDebug }
102-
103-
private val javaExecutablePathString: Path
104-
get() = JdkInfoService.jdkInfoProvider.info.path.resolve("bin${File.separatorChar}${osSpecificJavaExecutable()}")
105-
10696
private val pluginClasspath: String
10797
get() = (this.javaClass.classLoader as PluginClassLoader).classPath.baseUrls.joinToString(
10898
separator = File.pathSeparator,
@@ -112,27 +102,25 @@ class EngineProcess private constructor(val project: Project, private val classN
112102

113103
private const val startFileName = "org.utbot.framework.process.EngineProcessMainKt"
114104

115-
private fun obtainEngineProcessCommandLine(port: Int) = buildList {
116-
add(javaExecutablePathString.pathString)
117-
add("-ea")
118-
val javaVersionSpecificArgs = OpenModulesContainer.javaVersionSpecificArguments
119-
if (javaVersionSpecificArgs.isNotEmpty()) {
120-
addAll(javaVersionSpecificArgs)
121-
}
122-
debugArgument?.let { add(it) }
123-
add(log4j2ConfigSwitch)
124-
add("-cp")
125-
add(pluginClasspath)
126-
add(startFileName)
127-
add(rdPortArgument(port))
128-
}
105+
private fun obtainProcessSpecificCommandLineArgs(port: Int) = listOf(
106+
"-ea",
107+
log4j2ConfigSwitch,
108+
"-cp",
109+
pluginClasspath,
110+
startFileName,
111+
rdPortArgument(port)
112+
)
129113

130114
fun createBlocking(project: Project, classNameToPath: Map<String, String?>): EngineProcess = runBlocking { EngineProcess(project, classNameToPath) }
131115

132116
suspend operator fun invoke(project: Project, classNameToPath: Map<String, String?>): EngineProcess =
133117
LifetimeDefinition().terminateOnException { lifetime ->
134118
val rdProcess = startUtProcessWithRdServer(lifetime) { port ->
135-
val cmd = obtainEngineProcessCommandLine(port)
119+
val cmd = obtainCommonProcessCommandLineArgs(
120+
debugPort = UtSettings.engineProcessDebugPort,
121+
runWithDebug = UtSettings.runEngineProcessWithDebug,
122+
suspendExecutionInDebugMode = UtSettings.suspendEngineProcessExecutionInDebugMode,
123+
) + obtainProcessSpecificCommandLineArgs(port)
136124
val directory = WorkingDirService.provide().toFile()
137125
val builder = ProcessBuilder(cmd).directory(directory)
138126
val process = builder.start()
@@ -167,9 +155,11 @@ class EngineProcess private constructor(val project: Project, private val classN
167155
engineModel.setupUtContext.startBlocking(SetupContextParams(classpathForUrlsClassloader))
168156
}
169157

170-
fun getSpringBeanQualifiedNames(params: GetSpringBeanQualifiedNamesParams): List<String> {
158+
fun getSpringBeanQualifiedNames(classpathList: List<String>, config: String): List<String> {
171159
assertReadAccessNotAllowed()
172-
return engineModel.getSpringBeanQualifiedNames.startBlocking(params).toList()
160+
return engineModel.getSpringBeanQualifiedNames.startBlocking(
161+
GetSpringBeanQualifiedNamesParams(classpathList.toTypedArray(), config)
162+
).toList()
173163
}
174164

175165
private fun computeSourceFileByClass(params: ComputeSourceFileByClassArguments): String =

utbot-rd/src/main/kotlin/org/utbot/rd/loggers/UtRdLogUtil.kt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ fun overrideDefaultRdLoggerFactoryWithKLogger(logger: KLogger) {
2929
}
3030
}
3131

32-
// TODO use in instrumented process
3332
fun setupRdLogger(rdProcess: ProcessWithRdServer, loggerModel: LoggerModel, rdLogger: UtRdKLogger) {
3433
// currently we do not specify log level for different categories
3534
// though it is possible with some additional map on categories -> consider performance

0 commit comments

Comments
 (0)