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

implementation to get dynamic config during runtime #7

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
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
Prev Previous commit
Next Next commit
adding test
shashank11p committed Apr 15, 2021
commit e8867743f6cedbf6f9f80bd0238b42a07c720df1
2 changes: 2 additions & 0 deletions javaagent-core/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -53,4 +53,6 @@ dependencies {
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.11.3")

api("com.blogspot.mydailyjava:weak-lock-free:0.17")

runtimeOnly("io.grpc:grpc-netty-shaded:1.37.0")
}
Original file line number Diff line number Diff line change
@@ -48,7 +48,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** {@link HypertraceConfig} loads a yaml config from file. */
/**
* {@link HypertraceConfig} loads a yaml config from file and gets dynamic config if dynamic config
* service url is set in env vars or system properties.
*/
public class HypertraceConfig {

private HypertraceConfig() {}
@@ -76,7 +79,14 @@ public static AgentConfig get() {
DynamicConfigFetcher dynamicConfigFetcher = null;
if (dynamicConfigServiceUrl != null) {
dynamicConfigFetcher = new DynamicConfigFetcher(dynamicConfigServiceUrl);
Executors.newScheduledThreadPool(1)
Executors.newScheduledThreadPool(
1,
runnable -> {
Thread thread = new Thread(runnable, "dynamic_agent_config_fetcher");
thread.setDaemon(true);
// thread.setContextClassLoader(null);
return thread;
})
.scheduleAtFixedRate(dynamicConfigFetcher, 60, 30, TimeUnit.SECONDS);
}
synchronized (HypertraceConfig.class) {
@@ -145,7 +155,8 @@ public static void reset() {
}
}

private static AgentConfig load(DynamicConfigFetcher dynamicConfigFetcher) throws IOException {
@VisibleForTesting
static AgentConfig load(DynamicConfigFetcher dynamicConfigFetcher) throws IOException {
String configFile = EnvironmentConfig.getProperty(EnvironmentConfig.CONFIG_FILE_PROPERTY);
if (configFile == null) {
AgentConfig.Builder configBuilder = AgentConfig.newBuilder();
@@ -263,22 +274,23 @@ public static class DynamicConfigFetcher implements Runnable {

private final ConfigurationServiceGrpc.ConfigurationServiceBlockingStub blockingStub;

private static Int64Value configTimestamp;
private static Int64Value configUpdatedTimestamp;

private DynamicConfigFetcher(String dynamicConfigServiceUrl) {
Channel channel = ManagedChannelBuilder.forTarget(dynamicConfigServiceUrl).build();
Channel channel =
ManagedChannelBuilder.forTarget(dynamicConfigServiceUrl).usePlaintext().build();
blockingStub = ConfigurationServiceGrpc.newBlockingStub(channel);
configTimestamp = Int64Value.newBuilder().setValue(System.currentTimeMillis()).build();
configUpdatedTimestamp = Int64Value.newBuilder().setValue(System.currentTimeMillis()).build();
}

@Override
public void run() {
Service.UpdateConfigurationResponse response =
blockingStub.updateConfiguration(
Service.UpdateConfigurationRequest.newBuilder()
.setTimestamp(configTimestamp)
.setTimestamp(configUpdatedTimestamp)
.build());
configTimestamp = response.getTimestamp();
configUpdatedTimestamp = response.getTimestamp();
AgentConfig.Builder configBuilder = HypertraceConfig.get().toBuilder();
configBuilder.setEnabled(response.getEnabled());
configBuilder.setDataCapture(response.getDataCapture());
@@ -290,7 +302,7 @@ private AgentConfig initializeConfig() {
Service.InitialConfigurationResponse response =
blockingStub.initialConfiguration(
Service.InitialConfigurationRequest.newBuilder().build());
configTimestamp = response.getTimestamp();
configUpdatedTimestamp = response.getTimestamp();
return response.getAgentConfig();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Copyright The Hypertrace Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.hypertrace.agent.core.config;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.hypertrace.agent.config.ConfigurationServiceGrpc;
import org.hypertrace.agent.config.Service;

public class DynamicConfigServer {

private final Server server;
private Service.InitialConfigurationResponse initialConfigurationResponse;
private Service.UpdateConfigurationResponse updateConfigurationResponse;

public DynamicConfigServer(int port) {
server = ServerBuilder.forPort(port).addService(new DynamicConfigService()).build();
}

/** Start serving requests. */
public void start() throws IOException {
server.start();
Runtime.getRuntime()
.addShutdownHook(
new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
try {
DynamicConfigServer.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("*** server shut down");
}
});
}

/** Stop serving requests and shutdown resources. */
public void stop() throws InterruptedException {
if (server != null) {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
}
}

/** Await termination on the main thread since the grpc library uses daemon threads. */
public void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}

public Service.InitialConfigurationResponse getInitialConfigurationResponse() {
return initialConfigurationResponse;
}

public void setInitialConfigurationResponse(
Service.InitialConfigurationResponse initialConfigurationResponse) {
this.initialConfigurationResponse = initialConfigurationResponse;
}

public Service.UpdateConfigurationResponse getUpdateConfigurationResponse() {
return updateConfigurationResponse;
}

public void setUpdateConfigurationResponse(
Service.UpdateConfigurationResponse updateConfigurationResponse) {
this.updateConfigurationResponse = updateConfigurationResponse;
}

/** Main method. This comment makes the linter happy. */
public static void main(String[] args) throws Exception {
DynamicConfigServer server = new DynamicConfigServer(8980);
server.start();
server.blockUntilShutdown();
}

private class DynamicConfigService extends ConfigurationServiceGrpc.ConfigurationServiceImplBase {
@Override
public void initialConfiguration(
org.hypertrace.agent.config.Service.InitialConfigurationRequest request,
io.grpc.stub.StreamObserver<
org.hypertrace.agent.config.Service.InitialConfigurationResponse>
responseObserver) {

responseObserver.onNext(initialConfigurationResponse);
responseObserver.onCompleted();
}

@Override
public void updateConfiguration(
org.hypertrace.agent.config.Service.UpdateConfigurationRequest request,
io.grpc.stub.StreamObserver<org.hypertrace.agent.config.Service.UpdateConfigurationResponse>
responseObserver) {
responseObserver.onNext(updateConfigurationResponse);
responseObserver.onCompleted();
}
}
}
Original file line number Diff line number Diff line change
@@ -16,27 +16,61 @@

package org.hypertrace.agent.core.config;

import com.google.protobuf.BoolValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.StringValue;
import com.google.protobuf.util.JsonFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import org.hypertrace.agent.config.Config;
import org.hypertrace.agent.config.Config.AgentConfig;
import org.hypertrace.agent.config.Config.PropagationFormat;
import org.hypertrace.agent.config.Config.TraceReporterType;
import org.hypertrace.agent.config.Service;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junitpioneer.jupiter.ClearSystemProperty;

public class HypertraceConfigTest {

private static DynamicConfigServer server;

@BeforeAll
public static void setup() throws Exception {
server = new DynamicConfigServer(1234);
Thread thread =
new Thread(
() -> {
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
}
try {
server.blockUntilShutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
}

@AfterAll
public static void cleanup() throws InterruptedException {
server.stop();
}

@Test
public void defaultValues() throws IOException {
URL resource = getClass().getClassLoader().getResource("emptyconfig.yaml");
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath());
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath(), null);
Assertions.assertTrue(agentConfig.getEnabled().getValue());
Assertions.assertEquals("unknown", agentConfig.getServiceName().getValue());
Assertions.assertEquals(
@@ -79,22 +113,42 @@ public void defaultValues() throws IOException {
@Test
public void config() throws IOException {
URL resource = getClass().getClassLoader().getResource("config.yaml");
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath());
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath(), null);
assertConfig(agentConfig);
}

@Test
public void jsonConfig(@TempDir File tempFolder) throws IOException {
URL resource = getClass().getClassLoader().getResource("config.yaml");
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath());
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath(), null);

String jsonConfig = JsonFormat.printer().print(agentConfig);
Assertions.assertTrue(!jsonConfig.contains("value"));
File jsonFile = new File(tempFolder, "config.jSon");
FileOutputStream fileOutputStream = new FileOutputStream(jsonFile);
fileOutputStream.write(jsonConfig.getBytes());

agentConfig = HypertraceConfig.load(jsonFile.getAbsolutePath());
agentConfig = HypertraceConfig.load(jsonFile.getAbsolutePath(), null);
assertConfig(agentConfig);
}

@Test
@ClearSystemProperty(key = EnvironmentConfig.DYNAMIC_CONFIG_SERVICE_URL)
@ClearSystemProperty(key = EnvironmentConfig.CONFIG_FILE_PROPERTY)
public void dynamicInitialConfig() throws IOException {
URL resource = getClass().getClassLoader().getResource("config.yaml");
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath(), null);
Service.InitialConfigurationResponse initialConfigurationResponse =
Service.InitialConfigurationResponse.newBuilder()
.setTimestamp(Int64Value.newBuilder().setValue(System.currentTimeMillis()).build())
.setAgentConfig(agentConfig)
.build();

server.setInitialConfigurationResponse(initialConfigurationResponse);
server.setUpdateConfigurationResponse(getUpdateConfigurationResponse());

System.setProperty(EnvironmentConfig.DYNAMIC_CONFIG_SERVICE_URL, "localhost:1234");
agentConfig = HypertraceConfig.get();
assertConfig(agentConfig);
}

@@ -136,9 +190,29 @@ public void configWithSystemProps() throws IOException {
System.setProperty(EnvironmentConfig.REPORTING_ENDPOINT, "http://nowhere.here");

URL resource = getClass().getClassLoader().getResource("config.yaml");
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath());
AgentConfig agentConfig = HypertraceConfig.load(resource.getPath(), null);
Assertions.assertEquals(
"http://nowhere.here", agentConfig.getReporting().getEndpoint().getValue());
Assertions.assertEquals("service", agentConfig.getServiceName().getValue());
}

private Service.UpdateConfigurationResponse getUpdateConfigurationResponse() {
Config.DataCapture dataCapture =
Config.DataCapture.newBuilder()
.setBodyMaxSizeBytes(Int32Value.newBuilder().setValue(12).build())
.setHttpHeaders(
Config.Message.newBuilder()
.setResponse(BoolValue.newBuilder().setValue(false).build())
.build())
.build();
return Service.UpdateConfigurationResponse.newBuilder()
.setDataCapture(dataCapture)
.setEnabled(BoolValue.newBuilder().setValue(false).build())
.setTimestamp(Int64Value.newBuilder().setValue(System.currentTimeMillis()).build())
.setJavaAgent(
Config.JavaAgent.newBuilder()
.addFilterJarPaths(StringValue.newBuilder().setValue("random").build())
.build())
.build();
}
}