Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load config from file command #48

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ tasks.runIde {
jvmArgs("-ea")

// Copy over some JVM args from IntelliJ.
jvmArgs("-XX:ReservedCodeCacheSize=240m")
jvmArgs("-XX:ReservedCodeCacheSize=512m")
jvmArgs("-XX:+UseConcMarkSweepGC")
jvmArgs("-XX:SoftRefLRUPolicyMSPerMB=50")
jvmArgs("-XX:CICompilerCount=2")
Expand Down
6 changes: 6 additions & 0 deletions docs/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ slightly more experimental than the main method tracer.

<!-- TODO: Further explain these tracers and their subcommands. -->

Config and stacktrace loaders
---
There are two new commands which could be used from a `Config` tab or with an absolute file path:
* `load` loads commands such as `trace`/`untrace` in the same format as the tracer
* `stacktrace` loads functions from a given stacktrace in plain text form

FAQ
---

Expand Down
8 changes: 6 additions & 2 deletions src/main/java/com/google/idea/perf/tracer/TracerCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package com.google.idea.perf.tracer

import com.google.idea.perf.tracer.TraceOption.COUNT_AND_WALL_TIME
import com.google.idea.perf.tracer.TraceOption.COUNT_ONLY
import com.google.idea.perf.tracer.TraceOption.UNTRACE

/** A tracer CLI command */
sealed class TracerCommand {
Expand Down Expand Up @@ -56,7 +57,8 @@ sealed class TracerCommand {
/** Represents what to trace */
enum class TraceOption {
COUNT_AND_WALL_TIME,
COUNT_ONLY;
COUNT_ONLY,
UNTRACE;
}

/** A set of methods that the tracer will trace. */
Expand All @@ -68,7 +70,9 @@ sealed class TraceTarget {
data class Method(
val className: String,
val methodName: String?,
val parameterIndexes: List<Int>? = emptyList()
val parameterIndexes: List<Int>? = emptyList(),
// a redundant option to support user config tab
var traceOption: TraceOption = COUNT_AND_WALL_TIME
): TraceTarget()

val errors: List<String>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,14 @@ class TracerCompletionProvider : TextCompletionProvider, DumbAware {
when (tokenIndex) {
0 -> {
// We want all commands to be shown regardless of the prefix (for discoverability).
val allCommands = setOf("clear", "reset", "trace", "untrace")
val allCommands = setOf("clear", "load", "reset", "stacktrace", "trace", "untrace")
val prefixMatcher = LenientPrefixMatcher(result.prefixMatcher, allCommands)
result = result.withPrefixMatcher(prefixMatcher)

result.addElement(LookupElementBuilder.create("clear"))
result.addElement(LookupElementBuilder.create("load"))
result.addElement(LookupElementBuilder.create("reset"))
result.addElement(LookupElementBuilder.create("stacktrace"))
result.addElement(
LookupElementBuilder.create("trace")
.withTailText(" <method>")
Expand Down
92 changes: 81 additions & 11 deletions src/main/java/com/google/idea/perf/tracer/TracerController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,68 @@ class TracerController(
// Special case: handle this command while we're still on the EDT.
val path = cmd.substringAfter("save").trim()
savePngFromEdt(path)
}
else {
} else if (cmd.startsWith("load")) {
val path = cmd.substringAfter("load").trim()
// TODO(baskakov): handle file not found error
executor.execute { handleLoadConfig(path) }
} else if (cmd.startsWith("stacktrace")) {
val path = cmd.substringAfter("stacktrace").trim()
// TODO(baskakov): handle file not found error
executor.execute { handleLoadStacktrace(path) }
} else {
executor.execute { handleCommand(cmd) }
}
}

private fun handleLoadConfig(path: String) {
val lines = linesFromPathOrConfig(path)
if (lines.isEmpty()) {
displayWarning("config is empty")
return
}
handleCommand("reset")
lines.forEach {
displayInfo("processing: $it")
handleCommand(it)
}
}

private fun linesFromPathOrConfig(path: String): List<String> {
return if (path.isBlank()) {
view.configView.text.split("\n")
} else {
val file = File(path)
if (!file.isFile) {
displayWarning("File not found: $path")
return emptyList()
}
file.readLines()
}
.filter { it.isNotBlank() }
}

private fun handleLoadStacktrace(path: String) {
val lines = linesFromPathOrConfig(path)
if (lines.isEmpty()) {
displayWarning("stacktrace is empty")
return
}
handleCommand("reset")
for (line in lines) {
val oneTraceLine = line.trim().substringAfter("at ", "")
if (oneTraceLine.isBlank()) continue
val classAndMethod = oneTraceLine
.substringAfter("/")
.substringBefore("(")
val fqClassName = classAndMethod.substringBeforeLast(".")
val functionName = classAndMethod.substringAfterLast(".")
// TODO(baskakov): add unit test for:
// at org.jetbrains.kotlin.types.StarProjectionImpl$_type$2.invoke(StarProjectionImpl.kt:35)
val commandString = "trace ${fqClassName}#${functionName}"
handleCommand(commandString)
}
}

private fun handleCommand(commandString: String) {
val command = parseMethodTracerCommand(commandString)
val errors = command.errors
Expand All @@ -100,7 +156,6 @@ class TracerController(
displayWarning(errors.joinToString("\n"))
return
}

handleCommand(command)
}

Expand All @@ -109,25 +164,34 @@ class TracerController(
is TracerCommand.Clear -> {
CallTreeManager.clearCallTrees()
}

is TracerCommand.Reset -> {
TracerUserConfig.resetAll()
runWithProgress { progress ->
val oldRequests = TracerConfig.clearAllRequests()
val affectedClasses = TracerConfigUtil.getAffectedClasses(oldRequests)
retransformClasses(affectedClasses, progress)
CallTreeManager.clearCallTrees()
}
}

is TracerCommand.Trace -> {
val countOnly = command.traceOption == TraceOption.COUNT_ONLY

when (command.target) {
is TraceTarget.All -> {
when {
command.enable -> displayWarning("Cannot trace all classes")
else -> handleCommand(TracerCommand.Reset)
}
}

is TraceTarget.Method -> {
if (command.enable) {
TracerUserConfig.addUserTraceRequest(command.target)
} else {
command.target.traceOption = TraceOption.UNTRACE
TracerUserConfig.addUserUntraceRequest(command.target)
}
runWithProgress { progress ->
val clazz = command.target.className
val method = command.target.methodName ?: "*"
Expand All @@ -138,13 +202,15 @@ class TracerController(
tracedParams = command.target.parameterIndexes!!
)
val request = TracerConfigUtil.appendTraceRequest(methodPattern, config)
val affectedClasses = TracerConfigUtil.getAffectedClasses(listOf(request))
val affectedClasses =
TracerConfigUtil.getAffectedClasses(listOf(request))
retransformClasses(affectedClasses, progress)
CallTreeManager.clearCallTrees()
}
}
}
}

else -> {
displayWarning("Command not implemented")
}
Expand All @@ -165,11 +231,9 @@ class TracerController(
progress.checkCanceled()
try {
instrumentation.retransformClasses(clazz)
}
catch (e: UnmodifiableClassException) {
} catch (e: UnmodifiableClassException) {
LOG.info("Cannot instrument non-modifiable class: ${clazz.name}")
}
catch (e: Throwable) {
} catch (e: Throwable) {
LOG.error("Failed to retransform class: ${clazz.name}", e)
}
if (!progress.isIndeterminate) {
Expand All @@ -195,8 +259,7 @@ class TracerController(
getApplication().executeOnPooledThread {
try {
ImageIO.write(img, "png", file)
}
catch (e: IOException) {
} catch (e: IOException) {
displayWarning("Failed to write png to $path", e)
}
}
Expand All @@ -209,6 +272,13 @@ class TracerController(
}
}

private fun displayInfo(infoString: String, e: Throwable? = null) {
LOG.info(infoString, e)
invokeLater {
view.showCommandLinePopup(infoString, MessageType.INFO)
}
}

private fun <T> runWithProgress(action: (ProgressIndicator) -> T): T {
val indicator = view.createProgressIndicator()
val computable = Computable { action(indicator) }
Expand Down
60 changes: 60 additions & 0 deletions src/main/java/com/google/idea/perf/tracer/TracerUserConfig.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.idea.perf.tracer

import java.util.*

/**
* [TracerUserConfig] keeps track of which methods should be traced and `untrace`d.
* When a user `untrace`s some request, it will be removed if it was created before.
*/
object TracerUserConfig {

private val userTraceRequests = LinkedHashMap<String, TraceTarget.Method>()

@Synchronized
fun cloneUserTraceRequests(): List<TraceTarget.Method> {
return userTraceRequests.values.toList()
}

@Synchronized
fun addUserTraceRequest(entry: TraceTarget.Method) {
val plainTextKey = concatClassAndMethod(entry)
userTraceRequests[plainTextKey] = entry
}

@Synchronized
fun addUserUntraceRequest(entry: TraceTarget.Method) {
val classAndMethod = concatClassAndMethod(entry)
val oldValue = userTraceRequests[classAndMethod]
if (oldValue != null && oldValue.traceOption != TraceOption.UNTRACE) {
userTraceRequests.remove(classAndMethod)
} else {
userTraceRequests[classAndMethod] = entry
}
}

@Synchronized
fun resetAll() {
userTraceRequests.clear()
}

private fun concatClassAndMethod(entry: TraceTarget.Method): String {
return "${entry.className}#${entry.methodName ?: ""}"
}

}
55 changes: 55 additions & 0 deletions src/main/java/com/google/idea/perf/tracer/ui/TracerConfigTab.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.idea.perf.tracer.ui

import com.google.idea.perf.tracer.TraceOption
import com.google.idea.perf.tracer.TraceTarget
import com.intellij.ui.components.JBTextArea

/** Displays a list of trace/untrace commands as plain text. */
class TracerConfigTab : JBTextArea() {

private var previousCommandsList: List<TraceTarget.Method> = emptyList()

fun setTracingConfig(newStats: List<TraceTarget.Method>) {
if (previousCommandsList == newStats) {
return
}
previousCommandsList = newStats
document.remove(0, document.length)
val tmp = newStats.joinToString(
separator = "\n",
transform = TracerConfigTab::methodToString
)
append(tmp)
}

companion object {
private fun methodToString(method: TraceTarget.Method): String {
val option = when (method.traceOption) {
TraceOption.COUNT_AND_WALL_TIME -> "trace"
TraceOption.COUNT_ONLY -> "trace count"
TraceOption.UNTRACE -> "untrace"
}
if (method.methodName == "*") {
return "$option ${method.className}"
} else {
return "$option ${method.className}::${method.methodName}"
}
}
}
}
Loading