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

Added functionality to fetch Node metrics from the node #5

Open
wants to merge 2 commits into
base: main
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
16 changes: 16 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,22 @@ task casperJar(type: Jar) {
with jar
}

task casperFatJar(type: Jar) {
archiveBaseName = 'casper-java-sdk'
archiveVersion = '0.3.0'
manifest.from jar.manifest
archiveClassifier = 'all'
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} {
exclude "META-INF/*.SF"
exclude "META-INF/*.DSA"
exclude "META-INF/*.RSA"
}
with jar
}


test {
useJUnitPlatform()
}
5 changes: 5 additions & 0 deletions src/main/java/com/casper/sdk/Properties.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ public class Properties {
public static String STATE_GET_AUCTION_INFO = "state_get_auction_info";
public static String INFO_GET_PEERS = "info_get_peers";
public static String INFO_GET_STATUS = "info_get_status";
public static String INFO_GET_DEPLOY = "info_get_deploy";
public static String CHAIN_GET_BLOCK = "chain_get_block";
public static String CHAIN_GET_BLOCK_TRANSFERS = "chain_get_block_transfers";
public static String CHAIN_GET_ERA_INFO_BY_SWITCH_BLOCK = "chain_get_era_info_by_switch_block";
public static String RPC_DISCOVER = "rpc.discover";

public static Map<String, String> properties = new HashMap<>();

Expand Down
26 changes: 26 additions & 0 deletions src/main/java/com/casper/sdk/controller/CasperSdk.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.casper.sdk.controller;

import com.casper.sdk.service.MetricsService;
import org.apache.commons.codec.DecoderException;
import com.casper.sdk.Properties;
import com.casper.sdk.service.HashService;
Expand All @@ -14,11 +15,13 @@
public class CasperSdk {

private final QueryService queryService;
private final MetricsService metricsService;

public CasperSdk(final String url, final String port) {
Properties.properties.put("node-url", url);
Properties.properties.put("node-port", port);
this.queryService = new QueryService();
this.metricsService = new MetricsService();
}

public String getAccountInfo(final String accountKey) throws Throwable {
Expand Down Expand Up @@ -53,4 +56,27 @@ public String getNodePeers() throws Throwable {
return queryService.getNodePeers();
}

public String getBlock() throws Throwable {
return queryService.getBlock();
}

public String getBlockTransfers() throws Throwable {
return queryService.getBlockTransfers();
}

public String getDeployInfo(final String deployHash) throws Throwable {
return queryService.getDeployInfo(deployHash);
}

public String getEraInfoBySwitchBlock() throws Throwable {
return queryService.getEraInfoBySwitchBlock();
}

public String getRpcSchema() throws Throwable {
return queryService.getRpcSchema();
}

public String getNodeMetrics() throws Throwable {
return metricsService.getMetrics();
}
}
55 changes: 55 additions & 0 deletions src/main/java/com/casper/sdk/service/MethodEnums.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public enum MethodEnums {
@Override
public String getValue(final String result) throws ValueNotFoundException {
try{
System.out.println(result);
final JsonNode node = new ObjectMapper().readTree(result);
return node.get("result").get("state_root_hash").textValue();
} catch (Exception e){
Expand Down Expand Up @@ -78,6 +79,60 @@ public String getValue(final String result) throws ValueNotFoundException {
throw new ValueNotFoundException("result not found");
}
}
},
CHAIN_GET_BLOCK{
@Override
public String getValue(final String result) throws ValueNotFoundException {
try{
final JsonNode node = new ObjectMapper().readTree(result);
return node.get("result").toPrettyString();
} catch (Exception e){
throw new ValueNotFoundException("result not found");
}
}
},CHAIN_GET_BLOCK_TRANSFERS{
@Override
public String getValue(final String result) throws ValueNotFoundException {
try{
final JsonNode node = new ObjectMapper().readTree(result);
return node.get("result").toPrettyString();
} catch (Exception e){
throw new ValueNotFoundException("result not found");
}
}
},INFO_GET_DEPLOY{
@Override
public String getValue(final String result) throws ValueNotFoundException {
try{
System.out.println(result);
final JsonNode node = new ObjectMapper().readTree(result);
return node.get("result").toPrettyString();
} catch (Exception e){
throw new ValueNotFoundException("result not found");
}
}
},CHAIN_GET_ERA_INFO_BY_SWITCH_BLOCK{
@Override
public String getValue(final String result) throws ValueNotFoundException {
try{
System.out.println(result);
final JsonNode node = new ObjectMapper().readTree(result);
return node.get("result").toPrettyString();
} catch (Exception e){
throw new ValueNotFoundException("result not found");
}
}
},RPC_DISCOVER {
@Override
public String getValue(final String result) throws ValueNotFoundException {
try {
System.out.println(result);
final JsonNode node = new ObjectMapper().readTree(result);
return node.get("result").toPrettyString();
} catch (Exception e) {
throw new ValueNotFoundException("result not found");
}
}
};

private static final List<String> MAP = new ArrayList<>();
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/com/casper/sdk/service/MetricsService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.casper.sdk.service;

import com.casper.sdk.service.http.rest.RestMethods;

import java.util.Optional;

public class MetricsService {

RestMethods restMethods;

public MetricsService(){
restMethods = new RestMethods();
}

public String getMetrics() throws Throwable {

Optional<String> result = restMethods.restCallGetMethod("metrics");
return (result.isEmpty()) ? null : result.get();

}
}
59 changes: 56 additions & 3 deletions src/main/java/com/casper/sdk/service/QueryService.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package com.casper.sdk.service;

import static com.casper.sdk.Properties.*;

import com.casper.sdk.service.http.rpc.HttpMethods;
import com.casper.sdk.service.http.rpc.Method;

import java.util.Collections;
import java.util.HashMap;
import java.util.Optional;

import static com.casper.sdk.Properties.*;

/**
* Service to query the chain
* Methods call the HTTP methods with an instantiated method object
Expand Down Expand Up @@ -62,7 +62,8 @@ public String getAccountBalance(final String accountKey) throws Throwable {
public String getAccountMainPurseURef(final String accountKey) throws Throwable {

final Optional<String> result = httpMethods.rpcCallMethod(new Method(STATE_GET_ITEM,
new HashMap<>() { {
new HashMap<>() {
{
put("state_root_hash", getStateRootHash());
put("key", "account-hash-" + HashService.getAccountHash(accountKey));
put("path", Collections.emptyList());
Expand Down Expand Up @@ -104,5 +105,57 @@ public String getNodeStatus() throws Throwable {

}

public String getBlock() throws Throwable {

final Optional<String> result = httpMethods.rpcCallMethod(new Method(CHAIN_GET_BLOCK,
new HashMap<>()));

return (result.isEmpty()) ? null
: MethodEnums.CHAIN_GET_BLOCK.getValue(result.get());

}

public String getBlockTransfers() throws Throwable {

final Optional<String> result = httpMethods.rpcCallMethod(new Method(CHAIN_GET_BLOCK_TRANSFERS,
new HashMap<>()));

return (result.isEmpty()) ? null
: MethodEnums.CHAIN_GET_BLOCK_TRANSFERS.getValue(result.get());

}

public String getDeployInfo(String deployHash) throws Throwable {

final Optional<String> result = httpMethods.rpcCallMethod(new Method(INFO_GET_DEPLOY,
new HashMap<>() {
{
put("deploy_hash", deployHash);
}
}));

return (result.isEmpty()) ? null
: MethodEnums.INFO_GET_DEPLOY.getValue(result.get());

}

public String getEraInfoBySwitchBlock() throws Throwable {

final Optional<String> result = httpMethods.rpcCallMethod(new Method(CHAIN_GET_ERA_INFO_BY_SWITCH_BLOCK,
new HashMap<>()));

return (result.isEmpty()) ? null
: MethodEnums.CHAIN_GET_ERA_INFO_BY_SWITCH_BLOCK.getValue(result.get());

}

public String getRpcSchema() throws Throwable {

final Optional<String> result = httpMethods.rpcCallMethod(new Method(RPC_DISCOVER,
new HashMap<>()));

return (result.isEmpty()) ? null
: MethodEnums.RPC_DISCOVER.getValue(result.get());

}
}
38 changes: 38 additions & 0 deletions src/main/java/com/casper/sdk/service/http/rest/RestMethods.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.casper.sdk.service.http.rest;

import com.casper.sdk.Properties;
import com.casper.sdk.exceptions.HttpException;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Optional;

public class RestMethods {

public Optional<String> restCallGetMethod(final String url) throws HttpException {

try{
final HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(
new StringBuilder().append(Properties.properties.get("node-url")).append(":")
.append(Properties.properties.get("node-port")).append("/").append(url).toString()))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.GET()
.build();

final HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, HttpResponse.BodyHandlers.ofString());

return Optional.ofNullable(response.body());

} catch (Exception e) {
throw new HttpException(e.getMessage());
}

}

}
82 changes: 82 additions & 0 deletions src/test/java/com/casper/sdk/TestMetricsService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.casper.sdk;

import com.casper.sdk.service.MetricsService;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;

import static org.junit.jupiter.api.Assertions.assertNotNull;

public class TestMetricsService {

private final static String url = "http://localhost";

private static MockWebServer mockBackEnd;
private final MetricsService metricsService = new MetricsService();

@BeforeAll
static void init() throws IOException {
mockBackEnd = new MockWebServer();
mockBackEnd.start();
}

@Test
public void testStateRootOk() throws Throwable {

Properties.properties.put("node-url", url);
Properties.properties.put("node-port", String.valueOf(mockBackEnd.getPort()));

mockBackEnd.setDispatcher(
new MethodDispatcher());

String nodeMetrics = metricsService.getMetrics();

assertNotNull(nodeMetrics);

}

private static final class MethodDispatcher extends Dispatcher {

private final ClassLoader classLoader = getClass().getClassLoader();
private String responseBodyFile;

public MethodDispatcher() {}

@NotNull
@Override
public MockResponse dispatch(RecordedRequest request) {

if (request.getRequestUrl().toString().contains("metrics")) {
responseBodyFile = "method-json/node-metrics.txt";
}

if ( responseBodyFile != null ) {
return new MockResponse().setResponseCode(200)
.addHeader("Content-Type", "application/text")
.setBody(loadResponse(responseBodyFile));
} else {
return new MockResponse().setResponseCode(404);
}
}

private String loadResponse(final String fileName) {
try {
return String.join("", Files.readAllLines(Paths.get(classLoader.getResource(fileName).toURI())));
} catch (final IOException | NullPointerException | URISyntaxException e) {
throw new IllegalStateException("Unable to load mock response from file", e);
}
}

}


}
Loading