Skip to content

Commit

Permalink
feat(api): implement GET /recordings/:id for streaming files
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewazores committed Aug 14, 2023
1 parent 82002e8 commit 3df2ec1
Showing 1 changed file with 42 additions and 5 deletions.
47 changes: 42 additions & 5 deletions src/main/java/io/cryostat/agent/remote/RecordingsContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.cryostat.agent.remote;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -60,9 +61,9 @@

class RecordingsContext implements RemoteContext {

private static final String PATH = "/recordings";
private static final String PATH = "/recordings/";
private static final Pattern PATH_ID_PATTERN =
Pattern.compile("^" + PATH + "/(\\d+)$", Pattern.MULTILINE);
Pattern.compile("^" + PATH + "(\\d+)$", Pattern.MULTILINE);

private final Logger log = LoggerFactory.getLogger(getClass());
private final SmallRyeConfig config;
Expand Down Expand Up @@ -98,11 +99,10 @@ public void handle(HttpExchange exchange) throws IOException {
switch (mtd) {
case "GET":
id = extractId(exchange);
if (id == Integer.MIN_VALUE) {
if (id == Long.MIN_VALUE) {
handleGetList(exchange);
} else {
exchange.sendResponseHeaders(
HttpStatus.SC_NOT_IMPLEMENTED, BODY_LENGTH_NONE);
handleGetRecording(exchange, id);
}
break;
case "POST":
Expand Down Expand Up @@ -153,6 +153,43 @@ private void handleGetList(HttpExchange exchange) {
}
}

private void handleGetRecording(HttpExchange exchange, long id) {
FlightRecorder.getFlightRecorder().getRecordings().stream()
.filter(r -> r.getId() == id)
.findFirst()
.ifPresentOrElse(
r -> {
Recording copy = r.copy(true);
try (InputStream stream = copy.getStream(null, null);
BufferedInputStream bis = new BufferedInputStream(stream);
OutputStream response = exchange.getResponseBody()) {
if (stream == null) {
exchange.sendResponseHeaders(HttpStatus.SC_NO_CONTENT, -1);
} else {
exchange.sendResponseHeaders(HttpStatus.SC_OK, 0);
bis.transferTo(response);
}
} catch (IOException ioe) {
log.error("I/O error", ioe);
try {
exchange.sendResponseHeaders(
HttpStatus.SC_INTERNAL_SERVER_ERROR, -1);
} catch (IOException ioe2) {
log.error("Failed to write response", ioe2);
}
} finally {
copy.close();
}
},
() -> {
try {
exchange.sendResponseHeaders(HttpStatus.SC_NOT_FOUND, -1);
} catch (IOException e) {
log.error("Failed to write response", e);
}
});
}

private void handleStart(HttpExchange exchange) throws IOException {
try (InputStream body = exchange.getRequestBody()) {
StartRecordingRequest req = mapper.readValue(body, StartRecordingRequest.class);
Expand Down

0 comments on commit 3df2ec1

Please sign in to comment.