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

feat(api): enable JFR Snapshot #186

Merged
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
141 changes: 136 additions & 5 deletions src/main/java/io/cryostat/agent/remote/RecordingsContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Consumer;
import java.util.regex.Matcher;
Expand All @@ -37,6 +40,7 @@
import org.openjdk.jmc.flightrecorder.configuration.recording.RecordingOptionsBuilder;
import org.openjdk.jmc.rjmx.ServiceNotAvailableException;
import org.openjdk.jmc.rjmx.services.jfr.IFlightRecorderService;
import org.openjdk.jmc.rjmx.services.jfr.IRecordingDescriptor;

import io.cryostat.agent.StringUtils;
import io.cryostat.core.FlightRecorderException;
Expand All @@ -50,6 +54,7 @@
import io.cryostat.core.templates.Template;
import io.cryostat.core.templates.TemplateType;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import io.smallrye.config.SmallRyeConfig;
Expand Down Expand Up @@ -106,12 +111,12 @@ public void handle(HttpExchange exchange) throws IOException {
}
break;
case "POST":
handleStart(exchange);
handleStartRecordingOrSnapshot(exchange);
break;
case "PATCH":
id = extractId(exchange);
if (id >= 0) {
handleStop(exchange, id);
handleStopOrUpdate(exchange, id);
} else {
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, BODY_LENGTH_NONE);
}
Expand Down Expand Up @@ -193,9 +198,23 @@ private void handleGetRecording(HttpExchange exchange, long id) {
});
}

private void handleStart(HttpExchange exchange) throws IOException {
private void handleStartRecordingOrSnapshot(HttpExchange exchange) throws IOException {
try (InputStream body = exchange.getRequestBody()) {
StartRecordingRequest req = mapper.readValue(body, StartRecordingRequest.class);
if (req.requestSnapshot()) {
try {
SerializableRecordingDescriptor snapshot = startSnapshot(req, exchange);
exchange.sendResponseHeaders(HttpStatus.SC_CREATED, BODY_LENGTH_UNKNOWN);
try (OutputStream response = exchange.getResponseBody()) {
mapper.writeValue(response, snapshot);
}
} catch (IOException e) {
log.error("Failed to start snapshot", e);
exchange.sendResponseHeaders(
HttpStatus.SC_SERVICE_UNAVAILABLE, BODY_LENGTH_NONE);
}
andrewazores marked this conversation as resolved.
Show resolved Hide resolved
return;
}
if (!req.isValid()) {
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, BODY_LENGTH_NONE);
return;
Expand All @@ -217,6 +236,94 @@ private void handleStart(HttpExchange exchange) throws IOException {
}
}

private void handleStopOrUpdate(HttpExchange exchange, long id) throws IOException {
try {
JFRConnection conn =
jfrConnectionToolkit.connect(
jfrConnectionToolkit.createServiceURL("localhost", 0));
IFlightRecorderService svc = conn.getService();
IRecordingDescriptor dsc =
svc.getAvailableRecordings().stream()
.filter(r -> r.getId() == id)
.findFirst()
.get();
RecordingOptionsBuilder builder = new RecordingOptionsBuilder(conn.getService());

InputStream body = exchange.getRequestBody();
JsonNode jsonMap = mapper.readTree(body);
Iterator<Entry<String, JsonNode>> fields = jsonMap.fields();

while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();

switch (field.getKey()) {
case "state":
if ("STOPPED".equals(field.getValue().textValue())) {
handleStop(exchange, id);
break;
} else {
exchange.sendResponseHeaders(
HttpStatus.SC_BAD_REQUEST, BODY_LENGTH_NONE);
}
break;
case "name":
builder = builder.name(field.getValue().textValue());
break;
case "duration":
if (field.getValue().canConvertToLong()) {
builder = builder.duration(field.getValue().asLong());
break;
}
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, BODY_LENGTH_NONE);
break;
case "maxSize":
if (field.getValue().canConvertToLong()) {
builder = builder.maxSize(field.getValue().asLong());
break;
}
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, BODY_LENGTH_NONE);
break;
case "maxAge":
if (field.getValue().canConvertToLong()) {
builder = builder.maxAge(field.getValue().asLong());
break;
}
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, BODY_LENGTH_NONE);
break;
case "toDisk":
if (field.getValue().isBoolean()) {
builder = builder.toDisk(field.getValue().asBoolean());
break;
}
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, BODY_LENGTH_NONE);
break;
default:
log.warn("Unknown recording option {}", field.getKey());
exchange.sendResponseHeaders(
HttpStatus.SC_METHOD_NOT_ALLOWED, BODY_LENGTH_NONE);
break;
}
}
svc.updateRecordingOptions(dsc, builder.build());
exchange.sendResponseHeaders(HttpStatus.SC_OK, BODY_LENGTH_UNKNOWN);

try (OutputStream response = exchange.getResponseBody()) {
if (response == null) {
exchange.sendResponseHeaders(HttpStatus.SC_NO_CONTENT, BODY_LENGTH_NONE);
} else {
mapper.writeValue(response, dsc);
}
}
} catch (ServiceNotAvailableException
| org.openjdk.jmc.rjmx.services.jfr.FlightRecorderException
| QuantityConversionException e) {
log.error("Failed to update recording", e);
exchange.sendResponseHeaders(HttpStatus.SC_INTERNAL_SERVER_ERROR, BODY_LENGTH_NONE);
} finally {
exchange.close();
}
}

private void handleStop(HttpExchange exchange, long id) throws IOException {
invokeOnRecording(
exchange,
Expand Down Expand Up @@ -285,7 +392,8 @@ private SerializableRecordingDescriptor startRecording(StartRecordingRequest req
throws QuantityConversionException, ServiceNotAvailableException,
FlightRecorderException,
org.openjdk.jmc.rjmx.services.jfr.FlightRecorderException,
InvalidEventTemplateException, InvalidXmlException, IOException {
InvalidEventTemplateException, InvalidXmlException, IOException,
FlightRecorderException {
Runnable cleanup = () -> {};
try {
JFRConnection conn =
Expand Down Expand Up @@ -329,6 +437,21 @@ private SerializableRecordingDescriptor startRecording(StartRecordingRequest req
}
}

private SerializableRecordingDescriptor startSnapshot(
StartRecordingRequest req, HttpExchange exchange) throws IOException {
Runnable cleanup = () -> {};
try {
Recording snapshot = FlightRecorder.getFlightRecorder().takeSnapshot();
if (snapshot.getSize() == 0) {
log.warn("No active recordings");
exchange.sendResponseHeaders(HttpStatus.SC_SERVICE_UNAVAILABLE, BODY_LENGTH_NONE);
}
return new SerializableRecordingDescriptor(snapshot);
} finally {
cleanup.run();
}
}

static class StartRecordingRequest {

public String name;
Expand All @@ -346,12 +469,20 @@ boolean requestsBundledTemplate() {
return !StringUtils.isBlank(localTemplateName);
}

boolean requestSnapshot() {
boolean snapshotName = name.equals("snapshot");
boolean snapshotTemplate =
StringUtils.isBlank(template) && StringUtils.isBlank(localTemplateName);
boolean snapshotFeatures = duration == 0 && maxSize == 0 && maxAge == 0;
return snapshotName && snapshotTemplate && snapshotFeatures;
}

boolean isValid() {
boolean requestsCustomTemplate = requestsCustomTemplate();
boolean requestsBundledTemplate = requestsBundledTemplate();
boolean requestsEither = requestsCustomTemplate || requestsBundledTemplate;
boolean requestsBoth = requestsCustomTemplate && requestsBundledTemplate;
return requestsEither && !requestsBoth;
return (requestsEither && !requestsBoth) || requestSnapshot();
}
}
}