feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,201 @@
/*
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.internal.dcmd;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import jdk.jfr.FlightRecorder;
import jdk.jfr.Recording;
import jdk.jfr.internal.JVM;
import jdk.jfr.internal.SecuritySupport;
import jdk.jfr.internal.SecuritySupport.SafePath;
import jdk.jfr.internal.Utils;
/**
* Base class for JFR diagnostic commands
*
*/
abstract class AbstractDCmd {
private final StringWriter result;
private final PrintWriter log;
protected AbstractDCmd() {
result = new StringWriter();
log = new PrintWriter(result);
}
protected final FlightRecorder getFlightRecorder() {
return FlightRecorder.getFlightRecorder();
}
public final String getResult() {
return result.toString();
}
public String getPid() {
// Invoking ProcessHandle.current().pid() would require loading more
// classes during startup so instead JVM.getJVM().getPid() is used.
// The pid will not be exposed to running Java application, only when starting
// JFR from command line (-XX:StartFlightRecordin) or jcmd (JFR.start and JFR.check)
return JVM.getJVM().getPid();
}
protected final SafePath resolvePath(Recording recording, String filename) throws InvalidPathException {
if (filename == null) {
return makeGenerated(recording, Paths.get("."));
}
Path path = Paths.get(filename);
if (Files.isDirectory(path)) {
return makeGenerated(recording, path);
}
return new SafePath(path.toAbsolutePath().normalize());
}
private SafePath makeGenerated(Recording recording, Path directory) {
return new SafePath(directory.toAbsolutePath().resolve(Utils.makeFilename(recording)).normalize());
}
protected final Recording findRecording(String name) throws DCmdException {
try {
return findRecordingById(Integer.parseInt(name));
} catch (NumberFormatException nfe) {
// User specified a name, not an id.
return findRecordingByName(name);
}
}
protected final void reportOperationComplete(String actionPrefix, String name, SafePath file) {
print(actionPrefix);
print(" recording");
if (name != null) {
print(" \"" + name + "\"");
}
if (file != null) {
print(",");
try {
print(" ");
long bytes = SecuritySupport.getFileSize(file);
printBytes(bytes);
} catch (IOException e) {
// Ignore, not essential
}
println(" written to:");
println();
printPath(file);
} else {
println(".");
}
}
protected final List<Recording> getRecordings() {
List<Recording> list = new ArrayList<>(getFlightRecorder().getRecordings());
Collections.sort(list, Comparator.comparing(Recording::getId));
return list;
}
static String quoteIfNeeded(String text) {
if (text.contains(" ")) {
return "\\\"" + text + "\\\"";
} else {
return text;
}
}
protected final void println() {
log.println();
}
protected final void print(String s) {
log.print(s);
}
protected final void print(String s, Object... args) {
log.printf(s, args);
}
protected final void println(String s, Object... args) {
print(s, args);
println();
}
protected final void printBytes(long bytes) {
print(Utils.formatBytes(bytes));
}
protected final void printTimespan(Duration timespan, String separator) {
print(Utils.formatTimespan(timespan, separator));
}
protected final void printPath(SafePath path) {
if (path == null) {
print("N/A");
return;
}
try {
printPath(SecuritySupport.getAbsolutePath(path).toPath());
} catch (IOException ioe) {
printPath(path.toPath());
}
}
protected final void printPath(Path path) {
try {
println(path.toAbsolutePath().toString());
} catch (SecurityException e) {
// fall back on filename
println(path.toString());
}
}
private Recording findRecordingById(int id) throws DCmdException {
for (Recording r : getFlightRecorder().getRecordings()) {
if (r.getId() == id) {
return r;
}
}
throw new DCmdException("Could not find %d.\n\nUse JFR.check without options to see list of all available recordings.", id);
}
private Recording findRecordingByName(String name) throws DCmdException {
for (Recording recording : getFlightRecorder().getRecordings()) {
if (name.equals(recording.getName())) {
return recording;
}
}
throw new DCmdException("Could not find %s.\n\nUse JFR.check without options to see list of all available recordings.", name);
}
}

View File

@@ -0,0 +1,164 @@
/*
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.internal.dcmd;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import jdk.jfr.EventType;
import jdk.jfr.Recording;
import jdk.jfr.SettingDescriptor;
import jdk.jfr.internal.LogLevel;
import jdk.jfr.internal.LogTag;
import jdk.jfr.internal.Logger;
import jdk.jfr.internal.Utils;
/**
* JFR.check - invoked from native
*
*/
final class DCmdCheck extends AbstractDCmd {
/**
* Execute JFR.check
*
* @param recordingText name or id of the recording to check, or
* <code>null</code> to show a list of all recordings.
*
* @param verbose if event settings should be included.
*
* @return result output
*
* @throws DCmdException if the check could not be completed.
*/
public String execute(String recordingText, Boolean verbose) throws DCmdException {
executeInternal(recordingText, verbose);
return getResult();
}
private void executeInternal(String name, Boolean verbose) throws DCmdException {
if (Logger.shouldLog(LogTag.JFR_DCMD, LogLevel.DEBUG)) {
Logger.log(LogTag.JFR_DCMD, LogLevel.DEBUG, "Executing DCmdCheck: name=" + name + ", verbose=" + verbose);
}
if (verbose == null) {
verbose = Boolean.FALSE;
}
if (name != null) {
printRecording(findRecording(name), verbose);
return;
}
List<Recording> recordings = getRecordings();
if (!verbose && recordings.isEmpty()) {
println("No available recordings.");
println();
println("Use jcmd " + getPid() + " JFR.start to start a recording.");
return;
}
boolean first = true;
for (Recording recording : recordings) {
// Print separation between recordings,
if (!first) {
println();
if (Boolean.TRUE.equals(verbose)) {
println();
}
}
first = false;
printRecording(recording, verbose);
}
}
private void printRecording(Recording recording, boolean verbose) {
printGeneral(recording);
if (verbose) {
println();
printSetttings(recording);
}
}
private void printGeneral(Recording recording) {
print("Recording " + recording.getId() + ": name=" + recording.getName());
Duration duration = recording.getDuration();
if (duration != null) {
print(" duration=");
printTimespan(duration, "");
}
long maxSize = recording.getMaxSize();
if (maxSize != 0) {
print(" maxsize=");
print(Utils.formatBytesCompact(maxSize));
}
Duration maxAge = recording.getMaxAge();
if (maxAge != null) {
print(" maxage=");
printTimespan(maxAge, "");
}
print(" (" + recording.getState().toString().toLowerCase() + ")");
println();
}
private void printSetttings(Recording recording) {
Map<String, String> settings = recording.getSettings();
for (EventType eventType : sortByEventPath(getFlightRecorder().getEventTypes())) {
StringJoiner sj = new StringJoiner(",", "[", "]");
sj.setEmptyValue("");
for (SettingDescriptor s : eventType.getSettingDescriptors()) {
String settingsPath = eventType.getName() + "#" + s.getName();
if (settings.containsKey(settingsPath)) {
sj.add(s.getName() + "=" + settings.get(settingsPath));
}
}
String settingsText = sj.toString();
if (!settingsText.isEmpty()) {
print(" %s (%s)", eventType.getLabel(), eventType.getName());
println();
println(" " + settingsText);
}
}
}
private static List<EventType> sortByEventPath(Collection<EventType> events) {
List<EventType> sorted = new ArrayList<>();
sorted.addAll(events);
Collections.sort(sorted, new Comparator<EventType>() {
@Override
public int compare(EventType e1, EventType e2) {
return e1.getName().compareTo(e2.getName());
}
});
return sorted;
}
}

View File

@@ -0,0 +1,217 @@
/*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.internal.dcmd;
import jdk.jfr.internal.LogLevel;
import jdk.jfr.internal.LogTag;
import jdk.jfr.internal.Logger;
import jdk.jfr.internal.Options;
import jdk.jfr.internal.Repository;
import jdk.jfr.internal.SecuritySupport.SafePath;
/**
* JFR.configure - invoked from native
*
*/
//Instantiated by native
final class DCmdConfigure extends AbstractDCmd {
/**
* Execute JFR.configure.
*
* @param repositoryPath the path
* @param dumpPath path to dump to on fatal error (oom)
* @param stackDepth depth of stack traces
* @param globalBufferCount number of global buffers
* @param globalBufferSize size of global buffers
* @param threadBufferSize size of thread buffer for events
* @param maxChunkSize threshold at which a new chunk is created in the disk repository
* @param sampleThreads if thread sampling should be enabled
*
* @return result
* @throws DCmdException
* if the dump could not be completed
*/
public String execute
(
String repositoryPath,
String dumpPath,
Integer stackDepth,
Long globalBufferCount,
Long globalBufferSize,
Long threadBufferSize,
Long memorySize,
Long maxChunkSize,
Boolean sampleThreads
) throws DCmdException {
if (Logger.shouldLog(LogTag.JFR_DCMD, LogLevel.DEBUG)) {
Logger.log(LogTag.JFR_DCMD, LogLevel.DEBUG, "Executing DCmdConfigure: repositorypath=" + repositoryPath +
", dumppath=" + dumpPath +
", stackdepth=" + stackDepth +
", globalbuffercount=" + globalBufferCount +
", globalbuffersize=" + globalBufferSize +
", thread_buffer_size" + threadBufferSize +
", memorysize" + memorySize +
", maxchunksize=" + maxChunkSize +
", samplethreads" + sampleThreads);
}
boolean updated = false;
if (repositoryPath != null) {
try {
SafePath s = new SafePath(repositoryPath);
Repository.getRepository().setBasePath(s);
Logger.log(LogTag.JFR, LogLevel.INFO, "Base repository path set to " + repositoryPath);
} catch (Exception e) {
throw new DCmdException("Could not use " + repositoryPath + " as repository. " + e.getMessage(), e);
}
printRepositoryPath();
updated = true;
}
if (dumpPath != null) {
Options.setDumpPath(new SafePath(dumpPath));
Logger.log(LogTag.JFR, LogLevel.INFO, "Emergency dump path set to " + dumpPath);
printDumpPath();
updated = true;
}
if (stackDepth != null) {
Options.setStackDepth(stackDepth);
Logger.log(LogTag.JFR, LogLevel.INFO, "Stack depth set to " + stackDepth);
printStackDepth();
updated = true;
}
if (globalBufferCount != null) {
Options.setGlobalBufferCount(globalBufferCount);
Logger.log(LogTag.JFR, LogLevel.INFO, "Global buffer count set to " + globalBufferCount);
printGlobalBufferCount();
updated = true;
}
if (globalBufferSize != null) {
Options.setGlobalBufferSize(globalBufferSize);
Logger.log(LogTag.JFR, LogLevel.INFO, "Global buffer size set to " + globalBufferSize);
printGlobalBufferSize();
updated = true;
}
if (threadBufferSize != null) {
Options.setThreadBufferSize(threadBufferSize);
Logger.log(LogTag.JFR, LogLevel.INFO, "Thread buffer size set to " + threadBufferSize);
printThreadBufferSize();
updated = true;
}
if (memorySize != null) {
Options.setMemorySize(memorySize);
Logger.log(LogTag.JFR, LogLevel.INFO, "Memory size set to " + memorySize);
printMemorySize();
updated = true;
}
if (maxChunkSize != null) {
Options.setMaxChunkSize(maxChunkSize);
Logger.log(LogTag.JFR, LogLevel.INFO, "Max chunk size set to " + maxChunkSize);
printMaxChunkSize();
updated = true;
}
if (sampleThreads != null) {
Options.setSampleThreads(sampleThreads);
Logger.log(LogTag.JFR, LogLevel.INFO, "Sample threads set to " + sampleThreads);
printSampleThreads();
updated = true;
}
if (!updated) {
println("Current configuration:");
println();
printRepositoryPath();
printStackDepth();
printGlobalBufferCount();
printGlobalBufferSize();
printThreadBufferSize();
printMemorySize();
printMaxChunkSize();
printSampleThreads();
}
return getResult();
}
private void printRepositoryPath() {
print("Repository path: ");
printPath(Repository.getRepository().getRepositoryPath());
println();
}
private void printDumpPath() {
print("Dump path: ");
printPath(Options.getDumpPath());
println();
}
private void printSampleThreads() {
println("Sample threads: " + Options.getSampleThreads());
}
private void printStackDepth() {
println("Stack depth: " + Options.getStackDepth());
}
private void printGlobalBufferCount() {
println("Global buffer count: " + Options.getGlobalBufferCount());
}
private void printGlobalBufferSize() {
print("Global buffer size: ");
printBytes(Options.getGlobalBufferSize());
println();
}
private void printThreadBufferSize() {
print("Thread buffer size: ");
printBytes(Options.getThreadBufferSize());
println();
}
private void printMemorySize() {
print("Memory size: ");
printBytes(Options.getMemorySize());
println();
}
private void printMaxChunkSize() {
print("Max chunk size: ");
printBytes(Options.getMaxChunkSize());
println();
}
}

View File

@@ -0,0 +1,218 @@
/*
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.internal.dcmd;
import java.io.IOException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import jdk.jfr.FlightRecorder;
import jdk.jfr.Recording;
import jdk.jfr.internal.LogLevel;
import jdk.jfr.internal.LogTag;
import jdk.jfr.internal.Logger;
import jdk.jfr.internal.PlatformRecorder;
import jdk.jfr.internal.PlatformRecording;
import jdk.jfr.internal.PrivateAccess;
import jdk.jfr.internal.SecuritySupport.SafePath;
import jdk.jfr.internal.Utils;
import jdk.jfr.internal.WriteableUserPath;
/**
* JFR.dump
*
*/
// Instantiated by native
final class DCmdDump extends AbstractDCmd {
/**
* Execute JFR.dump.
*
* @param name name or id of the recording to dump, or <code>null</code> to dump everything
*
* @param filename file path where recording should be written, not null
* @param maxAge how far back in time to dump, may be null
* @param maxSize how far back in size to dump data from, may be null
* @param begin point in time to dump data from, may be null
* @param end point in time to dump data to, may be null
* @param pathToGcRoots if Java heap should be swept for reference chains
*
* @return result output
*
* @throws DCmdException if the dump could not be completed
*/
public String execute(String name, String filename, Long maxAge, Long maxSize, String begin, String end, Boolean pathToGcRoots) throws DCmdException {
if (Logger.shouldLog(LogTag.JFR_DCMD, LogLevel.DEBUG)) {
Logger.log(LogTag.JFR_DCMD, LogLevel.DEBUG,
"Executing DCmdDump: name=" + name +
", filename=" + filename +
", maxage=" + maxAge +
", maxsize=" + maxSize +
", begin=" + begin +
", end" + end +
", path-to-gc-roots=" + pathToGcRoots);
}
if (FlightRecorder.getFlightRecorder().getRecordings().isEmpty()) {
throw new DCmdException("No recordings to dump from. Use JFR.start to start a recording.");
}
if (maxAge != null) {
if (end != null || begin != null) {
throw new DCmdException("Dump failed, maxage can't be combined with begin or end.");
}
if (maxAge < 0) {
throw new DCmdException("Dump failed, maxage can't be negative.");
}
if (maxAge == 0) {
maxAge = Long.MAX_VALUE / 2; // a high value that won't overflow
}
}
if (maxSize!= null) {
if (maxSize < 0) {
throw new DCmdException("Dump failed, maxsize can't be negative.");
}
if (maxSize == 0) {
maxSize = Long.MAX_VALUE / 2; // a high value that won't overflow
}
}
Instant beginTime = parseTime(begin, "begin");
Instant endTime = parseTime(end, "end");
if (beginTime != null && endTime != null) {
if (endTime.isBefore(beginTime)) {
throw new DCmdException("Dump failed, begin must preceed end.");
}
}
Duration duration = null;
if (maxAge != null) {
duration = Duration.ofNanos(maxAge);
beginTime = Instant.now().minus(duration);
}
Recording recording = null;
if (name != null) {
recording = findRecording(name);
}
PlatformRecorder recorder = PrivateAccess.getInstance().getPlatformRecorder();
try {
synchronized (recorder) {
dump(recorder, recording, name, filename, maxSize, pathToGcRoots, beginTime, endTime);
}
} catch (IOException | InvalidPathException e) {
throw new DCmdException("Dump failed. Could not copy recording data. %s", e.getMessage());
}
return getResult();
}
public void dump(PlatformRecorder recorder, Recording recording, String name, String filename, Long maxSize, Boolean pathToGcRoots, Instant beginTime, Instant endTime) throws DCmdException, IOException {
try (PlatformRecording r = newSnapShot(recorder, recording, pathToGcRoots)) {
r.filter(beginTime, endTime, maxSize);
if (r.getChunks().isEmpty()) {
throw new DCmdException("Dump failed. No data found in the specified interval.");
}
// If a filename exist, use it
// if a filename doesn't exist, use destination set earlier
// if destination doesn't exist, generate a filename
WriteableUserPath wup = null;
if (recording != null) {
PlatformRecording pRecording = PrivateAccess.getInstance().getPlatformRecording(recording);
wup = pRecording.getDestination();
}
if (filename != null || (filename == null && wup == null) ) {
SafePath safe = resolvePath(recording, filename);
wup = new WriteableUserPath(safe.toPath());
}
r.dumpStopped(wup);
reportOperationComplete("Dumped", name, new SafePath(wup.getRealPathText()));
}
}
private Instant parseTime(String time, String parameter) throws DCmdException {
if (time == null) {
return null;
}
try {
return Instant.parse(time);
} catch (DateTimeParseException dtp) {
// fall through
}
try {
LocalDateTime ldt = LocalDateTime.parse(time);
return ZonedDateTime.of(ldt, ZoneId.systemDefault()).toInstant();
} catch (DateTimeParseException dtp) {
// fall through
}
try {
LocalTime lt = LocalTime.parse(time);
LocalDate ld = LocalDate.now();
Instant instant = ZonedDateTime.of(ld, lt, ZoneId.systemDefault()).toInstant();
Instant now = Instant.now();
if (instant.isAfter(now) && !instant.isBefore(now.plusSeconds(3600))) {
// User must have meant previous day
ld = ld.minusDays(1);
}
return ZonedDateTime.of(ld, lt, ZoneId.systemDefault()).toInstant();
} catch (DateTimeParseException dtp) {
// fall through
}
if (time.startsWith("-")) {
try {
long durationNanos = Utils.parseTimespan(time.substring(1));
Duration duration = Duration.ofNanos(durationNanos);
return Instant.now().minus(duration);
} catch (NumberFormatException nfe) {
// fall through
}
}
throw new DCmdException("Dump failed, not a valid %s time.", parameter);
}
private PlatformRecording newSnapShot(PlatformRecorder recorder, Recording recording, Boolean pathToGcRoots) throws DCmdException, IOException {
if (recording == null) {
// Operate on all recordings
PlatformRecording snapshot = recorder.newTemporaryRecording();
recorder.fillWithRecordedData(snapshot, pathToGcRoots);
return snapshot;
}
PlatformRecording pr = PrivateAccess.getInstance().getPlatformRecording(recording);
return pr.newSnapshotClone("Dumped by user", pathToGcRoots);
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.internal.dcmd;
import java.util.Formatter;
/**
* Thrown to indicate that a diagnostic command could not be executed
* successfully.
*/
final class DCmdException extends Exception {
private static final long serialVersionUID = -3792411099340016465L;
/**
* Constructs a new exception with message derived from a format string.
*
* @param format format string as described in {@link Formatter} class.
*
* @param args arguments referenced by the format specifiers in the format
* string.
*
*/
public DCmdException(String format, Object... args) {
super(format(format, args));
}
/**
* Constructs a new exception with message derived from a format string.
*
* @param cause exception that stopped the diagnostic command to complete.
*
* @param format format string as described in {@link Formatter} class.
*
* @param args arguments referenced by the format specifiers in the format
* string.
*
*/
public DCmdException(Throwable cause, String format, Object... args) {
super(format(format, args), cause);
}
private static String format(String message, Object... args) {
try (Formatter formatter = new Formatter()) {
return formatter.format(message, args).toString();
}
}
}

View File

@@ -0,0 +1,259 @@
/*
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.internal.dcmd;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import jdk.jfr.FlightRecorder;
import jdk.jfr.Recording;
import jdk.jfr.internal.JVM;
import jdk.jfr.internal.LogLevel;
import jdk.jfr.internal.LogTag;
import jdk.jfr.internal.Logger;
import jdk.jfr.internal.OldObjectSample;
import jdk.jfr.internal.PrivateAccess;
import jdk.jfr.internal.SecuritySupport.SafePath;
import jdk.jfr.internal.Type;
import jdk.jfr.internal.jfc.JFC;
/**
* JFR.start
*
*/
//Instantiated by native
final class DCmdStart extends AbstractDCmd {
/**
* Execute JFR.start.
*
* @param name optional name that can be used to identify recording.
* @param settings names of settings files to use, i.e. "default" or
* "default.jfc".
* @param delay delay before recording is started, in nanoseconds. Must be
* at least 1 second.
* @param duration duration of the recording, in nanoseconds. Must be at
* least 1 second.
* @param disk if recording should be persisted to disk
* @param path file path where recording data should be written
* @param maxAge how long recording data should be kept in the disk
* repository, or <code>0</code> if no limit should be set.
*
* @param maxSize the minimum amount data to keep in the disk repository
* before it is discarded, or <code>0</code> if no limit should be
* set.
*
* @param dumpOnExit if recording should dump on exit
*
* @return result output
*
* @throws DCmdException if recording could not be started
*/
@SuppressWarnings("resource")
public String execute(String name, String[] settings, Long delay, Long duration, Boolean disk, String path, Long maxAge, Long maxSize, Boolean dumpOnExit, Boolean pathToGcRoots) throws DCmdException {
if (Logger.shouldLog(LogTag.JFR_DCMD, LogLevel.DEBUG)) {
Logger.log(LogTag.JFR_DCMD, LogLevel.DEBUG, "Executing DCmdStart: name=" + name +
", settings=" + (settings != null ? Arrays.asList(settings) : "(none)") +
", delay=" + delay +
", duration=" + duration +
", disk=" + disk+
", filename=" + path +
", maxage=" + maxAge +
", maxsize=" + maxSize +
", dumponexit =" + dumpOnExit +
", path-to-gc-roots=" + pathToGcRoots);
}
if (name != null) {
try {
Integer.parseInt(name);
throw new DCmdException("Name of recording can't be numeric");
} catch (NumberFormatException nfe) {
// ok, can't be mixed up with name
}
}
if (duration == null && Boolean.FALSE.equals(dumpOnExit) && path != null) {
throw new DCmdException("Filename can only be set for a time bound recording or if dumponexit=true. Set duration/dumponexit or omit filename.");
}
if (settings.length == 1 && settings[0].length() == 0) {
throw new DCmdException("No settings specified. Use settings=none to start without any settings");
}
Map<String, String> s = new HashMap<>();
for (String configName : settings) {
try {
s.putAll(JFC.createKnown(configName).getSettings());
} catch(FileNotFoundException e) {
throw new DCmdException("Could not find settings file'" + configName + "'", e);
} catch (IOException | ParseException e) {
throw new DCmdException("Could not parse settings file '" + settings[0] + "'", e);
}
}
OldObjectSample.updateSettingPathToGcRoots(s, pathToGcRoots);
if (duration != null) {
if (duration < 1000L * 1000L * 1000L) {
// to avoid typo, duration below 1s makes no sense
throw new DCmdException("Could not start recording, duration must be at least 1 second.");
}
}
if (delay != null) {
if (delay < 1000L * 1000L * 1000) {
// to avoid typo, delay shorter than 1s makes no sense.
throw new DCmdException("Could not start recording, delay must be at least 1 second.");
}
}
if (!FlightRecorder.isInitialized() && delay == null) {
initializeWithForcedInstrumentation(s);
}
Recording recording = new Recording();
if (name != null) {
recording.setName(name);
}
if (disk != null) {
recording.setToDisk(disk.booleanValue());
}
recording.setSettings(s);
SafePath safePath = null;
if (path != null) {
try {
if (dumpOnExit == null) {
// default to dumponexit=true if user specified filename
dumpOnExit = Boolean.TRUE;
}
Path p = Paths.get(path);
if (Files.isDirectory(p) && Boolean.TRUE.equals(dumpOnExit)) {
// Decide destination filename at dump time
// Purposely avoid generating filename in Recording#setDestination due to
// security concerns
PrivateAccess.getInstance().getPlatformRecording(recording).setDumpOnExitDirectory(new SafePath(p));
} else {
safePath = resolvePath(recording, path);
recording.setDestination(safePath.toPath());
}
} catch (IOException | InvalidPathException e) {
recording.close();
throw new DCmdException("Could not start recording, not able to write to file %s. %s ", path, e.getMessage());
}
}
if (maxAge != null) {
recording.setMaxAge(Duration.ofNanos(maxAge));
}
if (maxSize != null) {
recording.setMaxSize(maxSize);
}
if (duration != null) {
recording.setDuration(Duration.ofNanos(duration));
}
if (dumpOnExit != null) {
recording.setDumpOnExit(dumpOnExit);
}
if (delay != null) {
Duration dDelay = Duration.ofNanos(delay);
recording.scheduleStart(dDelay);
print("Recording " + recording.getId() + " scheduled to start in ");
printTimespan(dDelay, " ");
print(".");
} else {
recording.start();
print("Started recording " + recording.getId() + ".");
}
if (recording.isToDisk() && duration == null && maxAge == null && maxSize == null) {
print(" No limit specified, using maxsize=250MB as default.");
recording.setMaxSize(250*1024L*1024L);
}
if (safePath != null && duration != null) {
println(" The result will be written to:");
println();
printPath(safePath);
} else {
println();
println();
String cmd = duration == null ? "dump" : "stop";
String fileOption = path == null ? "filename=FILEPATH " : "";
String recordingspecifier = "name=" + recording.getId();
// if user supplied a name, use it.
if (name != null) {
recordingspecifier = "name=" + quoteIfNeeded(name);
}
print("Use jcmd " + getPid() + " JFR." + cmd + " " + recordingspecifier + " " + fileOption + "to copy recording data to file.");
println();
}
return getResult();
}
// Instruments JDK-events on class load to reduce startup time
private void initializeWithForcedInstrumentation(Map<String, String> settings) {
if (!hasJDKEvents(settings)) {
return;
}
JVM jvm = JVM.getJVM();
try {
jvm.setForceInstrumentation(true);
FlightRecorder.getFlightRecorder();
} finally {
jvm.setForceInstrumentation(false);
}
}
private boolean hasJDKEvents(Map<String, String> settings) {
String[] eventNames = new String[7];
eventNames[0] = "FileRead";
eventNames[1] = "FileWrite";
eventNames[2] = "SocketRead";
eventNames[3] = "SocketWrite";
eventNames[4] = "JavaErrorThrow";
eventNames[5] = "JavaExceptionThrow";
eventNames[6] = "FileForce";
for (String eventName : eventNames) {
if ("true".equals(settings.get(Type.EVENT_NAME_PREFIX + eventName + "#enabled"))) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.internal.dcmd;
import java.io.IOException;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import jdk.jfr.Recording;
import jdk.jfr.internal.LogLevel;
import jdk.jfr.internal.LogTag;
import jdk.jfr.internal.Logger;
import jdk.jfr.internal.SecuritySupport.SafePath;
/**
* JFR.stop
*
*/
// Instantiated by native
final class DCmdStop extends AbstractDCmd {
/**
* Execute JFR.stop
*
* Requires that either <code>name or <code>id</code> is set.
*
* @param name name or id of the recording to stop.
*
* @param filename file path where data should be written after recording has
* been stopped, or <code>null</code> if recording shouldn't be written
* to disk.
* @return result text
*
* @throws DCmdException if recording could not be stopped
*/
public String execute(String name, String filename) throws DCmdException {
if (Logger.shouldLog(LogTag.JFR_DCMD, LogLevel.DEBUG)) {
Logger.log(LogTag.JFR_DCMD, LogLevel.DEBUG, "Executing DCmdStart: name=" + name + ", filename=" + filename);
}
try {
SafePath safePath = null;
Recording recording = findRecording(name);
if (filename != null) {
try {
// Ensure path is valid. Don't generate safePath if filename == null, as a user may
// want to stop recording without a dump
safePath = resolvePath(null, filename);
recording.setDestination(Paths.get(filename));
} catch (IOException | InvalidPathException e) {
throw new DCmdException("Failed to stop %s. Could not set destination for \"%s\" to file %s", recording.getName(), filename, e.getMessage());
}
}
recording.stop();
reportOperationComplete("Stopped", recording.getName(), safePath);
recording.close();
return getResult();
} catch (InvalidPathException | DCmdException e) {
if (filename != null) {
throw new DCmdException("Could not write recording \"%s\" to file. %s", name, e.getMessage());
}
throw new DCmdException(e, "Could not stop recording \"%s\".", name, e.getMessage());
}
}
}