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(agent): implement HTTP-based readonly queries to -agents #1415

Merged
merged 6 commits into from
Mar 17, 2023
Merged
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
185 changes: 185 additions & 0 deletions src/main/java/io/cryostat/net/AgentClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.cryostat.net;

import java.net.URI;
import java.time.Duration;

import javax.script.ScriptException;

import io.cryostat.configuration.CredentialsManager;
import io.cryostat.core.log.Logger;
import io.cryostat.core.net.Credentials;
import io.cryostat.core.net.MBeanMetrics;
import io.cryostat.util.HttpStatusCodeIdentifier;

import com.google.gson.Gson;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.auth.authentication.UsernamePasswordCredentials;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.codec.BodyCodec;
import org.apache.commons.lang3.exception.ExceptionUtils;

class AgentClient {

private final Vertx vertx;
private final Gson gson;
private final long httpTimeout;
private final WebClient webClient;
private final CredentialsManager credentialsManager;
private final URI agentUri;
private final Logger logger;

AgentClient(
Vertx vertx,
Gson gson,
long httpTimeout,
WebClient webClient,
CredentialsManager credentialsManager,
URI agentUri,
Logger logger) {
this.vertx = vertx;
this.gson = gson;
this.httpTimeout = httpTimeout;
this.webClient = webClient;
this.credentialsManager = credentialsManager;
this.agentUri = agentUri;
this.logger = logger;
}

URI getUri() {
return agentUri;
}

Future<Boolean> ping() {
Future<HttpResponse<Void>> f = invoke(HttpMethod.GET, "/", BodyCodec.none());
return f.map(HttpResponse::statusCode).map(HttpStatusCodeIdentifier::isSuccessCode);
}

Future<MBeanMetrics> mbeanMetrics() {
Future<HttpResponse<String>> f =
invoke(HttpMethod.GET, "/mbean-metrics", BodyCodec.string());
return f.map(HttpResponse::body)
// uses Gson rather than Vertx's Jackson because Gson is able to handle MBeanMetrics
// with no additional fuss. Jackson complains about private final fields.
.map(s -> gson.fromJson(s, MBeanMetrics.class));
}

private <T> Future<HttpResponse<T>> invoke(HttpMethod mtd, String path, BodyCodec<T> codec) {
return vertx.executeBlocking(
promise -> {
logger.info("{} {} {}", mtd, agentUri, path);
HttpRequest<T> req =
webClient
.request(mtd, agentUri.getPort(), agentUri.getHost(), path)
.ssl("https".equals(agentUri.getScheme()))
.timeout(Duration.ofSeconds(httpTimeout).toMillis())
.followRedirects(true)
.as(codec);
try {
Credentials credentials =
credentialsManager.getCredentialsByTargetId(agentUri.toString());
req =
req.authentication(
new UsernamePasswordCredentials(
credentials.getUsername(),
credentials.getPassword()));
} catch (ScriptException se) {
promise.fail(se);
return;
}

req.send()
.onComplete(
ar -> {
if (ar.failed()) {
logger.warn(
"{} {}{} failed: {}",
mtd,
agentUri,
path,
ExceptionUtils.getStackTrace(ar.cause()));
promise.fail(ar.cause());
return;
}
logger.trace(
"{} {}{} status {}: {}",
mtd,
agentUri,
path,
ar.result().statusCode(),
ar.result().statusMessage());
promise.complete(ar.result());
});
});
}

static class Factory {

private final Vertx vertx;
private final Gson gson;
private final long httpTimeout;
private final WebClient webClient;
private final CredentialsManager credentialsManager;
private final Logger logger;

Factory(
Vertx vertx,
Gson gson,
long httpTimeout,
WebClient webClient,
CredentialsManager credentialsManager,
Logger logger) {
this.vertx = vertx;
this.gson = gson;
this.httpTimeout = httpTimeout;
this.webClient = webClient;
this.credentialsManager = credentialsManager;
this.logger = logger;
}

AgentClient create(URI agentUri) {
return new AgentClient(
vertx, gson, httpTimeout, webClient, credentialsManager, agentUri, logger);
}
}
}
91 changes: 51 additions & 40 deletions src/main/java/io/cryostat/net/AgentConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@

import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
Expand All @@ -56,92 +57,93 @@
import org.openjdk.jmc.rjmx.services.jfr.IFlightRecorderService;

import io.cryostat.core.FlightRecorderException;
import io.cryostat.core.log.Logger;
import io.cryostat.core.net.IDException;
import io.cryostat.core.net.JFRConnection;
import io.cryostat.core.net.MBeanMetrics;
import io.cryostat.core.net.MemoryMetrics;
import io.cryostat.core.net.OperatingSystemMetrics;
import io.cryostat.core.net.RuntimeMetrics;
import io.cryostat.core.net.ThreadMetrics;
import io.cryostat.core.sys.Clock;
import io.cryostat.core.templates.Template;
import io.cryostat.core.templates.TemplateService;
import io.cryostat.core.templates.TemplateType;
import io.cryostat.recordings.JvmIdHelper;

import io.vertx.ext.web.client.WebClient;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jsoup.nodes.Document;

class AgentConnection implements JFRConnection {
public class AgentConnection implements JFRConnection {

private final URI agentUri;
private final long httpTimeout;
private final WebClient webClient;
private final Clock clock;
private final AgentClient client;
private final JvmIdHelper idHelper;
private final Logger logger;

AgentConnection(
URI agentUri,
long httpTimeoutSeconds,
WebClient webClient,
Clock clock,
JvmIdHelper idHelper) {
this.agentUri = agentUri;
this.httpTimeout = httpTimeoutSeconds;
this.webClient = webClient;
this.clock = clock;
AgentConnection(AgentClient client, JvmIdHelper idHelper, Logger logger) {
this.client = client;
this.idHelper = idHelper;
this.logger = logger;
}

@Override
public void close() throws Exception {}

@Override
public void connect() throws ConnectionException {
// TODO test connection by pinging agent callback
try {
CompletableFuture<Boolean> f = client.ping().toCompletionStage().toCompletableFuture();
Boolean resp = f.get();
if (!Boolean.TRUE.equals(resp)) {
throw new ConnectionException("Connection failed");
}
} catch (ExecutionException | InterruptedException e) {
throw new ConnectionException(ExceptionUtils.getMessage(e));
}
}

@Override
public void disconnect() {}

public URI getUri() {
return client.getUri();
}

@Override
public long getApproximateServerTime(Clock arg0) {
public long getApproximateServerTime(Clock clock) {
return clock.now().toEpochMilli();
}

@Override
public IConnectionHandle getHandle() throws ConnectionException, IOException {
// TODO Auto-generated method stub
return null;
throw new UnsupportedOperationException();
}

@Override
public String getHost() {
return agentUri.getHost();
return getUri().getHost();
}

@Override
public JMXServiceURL getJMXURL() throws IOException {
// TODO Auto-generated method stub
return null;
if (getUri().getScheme().startsWith("http")) {
throw new UnsupportedOperationException();
}
return new JMXServiceURL(getUri().toString());
}

@Override
public String getJvmId() throws IDException, IOException {
// this should have already been populated when the agent published itself to the Discovery
// API. If not, then this will fail, but we were in a bad state to begin with.
return idHelper.getJvmId(agentUri.toString());
return idHelper.getJvmId(getUri().toString());
}

@Override
public int getPort() {
return agentUri.getPort();
return getUri().getPort();
}

@Override
public IFlightRecorderService getService()
throws ConnectionException, IOException, ServiceNotAvailableException {
return new AgentJFRService(httpTimeout, webClient);
return new AgentJFRService(client);
}

@Override
Expand Down Expand Up @@ -169,24 +171,33 @@ public Optional<Document> getXml(String name, TemplateType type)

@Override
public boolean isConnected() {
// TODO Auto-generated method stub
return true;
}

@Override
public MBeanMetrics getMBeanMetrics()
throws ConnectionException, IOException, InstanceNotFoundException,
IntrospectionException, ReflectionException {
if (!isConnected()) {
connect();
try {
return client.mbeanMetrics().toCompletionStage().toCompletableFuture().get();
} catch (ExecutionException | InterruptedException e) {
throw new IOException(e);
}
}

public static class Factory {
private final AgentClient.Factory clientFactory;
private final JvmIdHelper idHelper;
private final Logger logger;

// TODO: implement http requests to agent to get metrics
RuntimeMetrics runtime = new RuntimeMetrics(Collections.emptyMap());
MemoryMetrics memory = new MemoryMetrics(Collections.emptyMap());
ThreadMetrics threads = new ThreadMetrics(Collections.emptyMap());
OperatingSystemMetrics os = new OperatingSystemMetrics(Collections.emptyMap());
Factory(AgentClient.Factory clientFactory, JvmIdHelper idHelper, Logger logger) {
this.clientFactory = clientFactory;
this.idHelper = idHelper;
this.logger = logger;
}

return new MBeanMetrics(runtime, memory, threads, os, null);
AgentConnection createConnection(URI agentUri) {
return new AgentConnection(clientFactory.create(agentUri), idHelper, logger);
}
}
}
Loading