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

Use Spring Jafu (again) #390

Merged
merged 3 commits into from
Aug 5, 2020
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
2 changes: 1 addition & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ dependencies {
compile project(":protocol")

compile 'org.springframework.boot:spring-boot-starter-webflux'
compile 'org.springframework.fu:spring-fu-autoconfigure-adapter'
compile 'org.springframework.fu:spring-fu-jafu'

compile 'org.pf4j:pf4j'

Expand Down
122 changes: 49 additions & 73 deletions app/src/main/java/com/github/bsideup/liiklus/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,14 @@
import com.github.bsideup.liiklus.plugins.LiiklusPluginManager;
import lombok.extern.slf4j.Slf4j;
import org.pf4j.PluginManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerInitializer;
import org.springframework.boot.autoconfigure.web.reactive.ResourceCodecInitializer;
import org.springframework.boot.autoconfigure.web.reactive.StringCodecInitializer;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxProperties;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.fu.jafu.Jafu;
import org.springframework.fu.jafu.webflux.WebFluxServerDsl;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
Expand Down Expand Up @@ -49,70 +39,56 @@ public static void main(String[] args) throws Exception {
start(args);
}

public static ConfigurableApplicationContext start(String[] args) {
return createSpringApplication(args).run(args);
}

public static SpringApplication createSpringApplication(String[] args) {
var environment = new StandardEnvironment();
environment.setDefaultProfiles("exporter", "gateway");
environment.getPropertySources().addFirst(new SimpleCommandLinePropertySource(args));

var pluginsDir = environment.getProperty("plugins.dir", String.class, "./plugins");
var pathMatcher = environment.getProperty("plugins.pathMatcher", String.class, "*.jar");

var pluginsRoot = Paths.get(pluginsDir).toAbsolutePath().normalize();
log.info("Loading plugins from '{}' with matcher: '{}'", pluginsRoot, pathMatcher);

var pluginManager = new LiiklusPluginManager(pluginsRoot, pathMatcher);

pluginManager.loadPlugins();
pluginManager.startPlugins();

var binder = Binder.get(environment);
var application = new SpringApplication(Application.class) {
@Override
protected void load(ApplicationContext context, Object[] sources) {
// We don't want the annotation bean definition reader
@SafeVarargs
public static ConfigurableApplicationContext start(
String[] args,
ApplicationContextInitializer<GenericApplicationContext>... additionalInitializers
) {
return Jafu.reactiveWebApplication(app -> {
var environment = app.env();

var pluginsDir = environment.getProperty("plugins.dir", String.class, "./plugins");
var pathMatcher = environment.getProperty("plugins.pathMatcher", String.class, "*.jar");

var pluginsRoot = Paths.get(pluginsDir).toAbsolutePath().normalize();
log.info("Loading plugins from '{}' with matcher: '{}'", pluginsRoot, pathMatcher);

var pluginManager = new LiiklusPluginManager(pluginsRoot, pathMatcher);

pluginManager.loadPlugins();
pluginManager.startPlugins();

app.enable(new GatewayConfiguration());
app.beans(beans -> {
beans.bean("health", RouterFunction.class, () -> {
return RouterFunctions.route()
.GET("/health", __ -> ServerResponse.ok().bodyValue("OK"))
.build();
});
beans.bean(PluginManager.class, () -> pluginManager);
});

for (var initializerClass : pluginManager.getExtensionClasses(ApplicationContextInitializer.class)) {
try {
app.enable(initializerClass.getDeclaredConstructor().newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
application.setWebApplicationType(WebApplicationType.REACTIVE);
application.setApplicationContextClass(ReactiveWebServerApplicationContext.class);
application.setEnvironment(environment);

application.addInitializers(
new StringCodecInitializer(false, true),
new ResourceCodecInitializer(false),
new ReactiveWebServerInitializer(
binder.bind("server", ServerProperties.class).orElseGet(ServerProperties::new),
binder.bind("spring.resources", ResourceProperties.class).orElseGet(ResourceProperties::new),
binder.bind("spring.webflux", WebFluxProperties.class).orElseGet(WebFluxProperties::new),
new NettyReactiveWebServerFactory()
),
new GatewayConfiguration(),
(GenericApplicationContext applicationContext) -> {
applicationContext.registerBean("health", RouterFunction.class, () -> {
return RouterFunctions.route()
.GET("/health", __ -> ServerResponse.ok().bodyValue("OK"))
.build();
});
for (var initializer : additionalInitializers) {
app.enable(initializer);
}

applicationContext.registerBean(PluginManager.class, () -> pluginManager);
app.enable(WebFluxServerDsl.webFlux(dsl -> {
try {
var serverPropertiesField = WebFluxServerDsl.class.getDeclaredField("serverProperties");
serverPropertiesField.setAccessible(true);
serverPropertiesField.set(dsl, Binder.get(app.env()).bindOrCreate("server", ServerProperties.class));
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
);

application.addInitializers(
pluginManager.getExtensionClasses(ApplicationContextInitializer.class).stream()
.map(it -> {
try {
return it.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.toArray(ApplicationContextInitializer[]::new)
);

return application;
}));
}).run(args);
}
}
4 changes: 4 additions & 0 deletions app/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
spring:
profiles:
active: exporter,gateway

# Liiklus config defaults
grpc:
port: 6565
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ public class ProfilesTest extends AbstractIntegrationTest {
"storage.positions.type=MEMORY"
);

Set<String> commonArgs = Sets.newHashSet();
Set<String> commonArgs = Sets.newHashSet(Set.of(
"server.port=0"
));

ConfigurableApplicationContext lastApplicationContext;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,16 @@ public static int getPartitionByKey(String key) {
"server.port=0"
).stream().map(it -> "--" + it).toArray(String[]::new);

var springApplication = Application.createSpringApplication(args);
springApplication.addInitializers(applicationContext -> {
((GenericApplicationContext) applicationContext).registerBean(
"processorPluginMock",
ProcessorPluginMock.class,
() -> processorPluginMock
);
});
applicationContext = springApplication.run(args);
applicationContext = Application.start(
args,
applicationContext -> {
applicationContext.registerBean(
"processorPluginMock",
ProcessorPluginMock.class,
() -> processorPluginMock
);
}
);
var pluginManager = applicationContext.getBean(PluginManager.class);

boolean useGrpc = false;
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ configure(subprojects.findAll { !it.name.startsWith("examples/") }) {
entry 'rsocket-rpc-protobuf'
}

dependency 'org.springframework.fu:spring-fu-autoconfigure-adapter:0.2.1'
dependency 'org.springframework.fu:spring-fu-jafu:0.3.2'

dependency 'com.google.protobuf:protoc:3.10.1'

Expand Down
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ include 'plugins:schema'

file('plugins').eachDir { dir ->
def projectName = dir.name
if (findProject(":plugins:${projectName}") == null) {
if (projectName != "build" && findProject(":plugins:${projectName}") == null) {
throw new GradleException("Plugin /plugins/${projectName} was not included into the build. Check settings.gradle for details.")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.loader.JarLauncher;
import org.springframework.boot.loader.LaunchedURLClassLoader;
import org.springframework.boot.loader.archive.JarFileArchive;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.File;
Expand All @@ -15,6 +15,7 @@
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class ApplicationRunner {
Expand Down Expand Up @@ -72,18 +73,27 @@ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundE
};

var currentClassLoader = Thread.currentThread().getContextClassLoader();
var oldProperties = new Properties(System.getProperties());
try {
var appClassLoader = launcher.createClassLoader();
Thread.currentThread().setContextClassLoader(appClassLoader);

var applicationClass = appClassLoader.loadClass("com.github.bsideup.liiklus.Application");
System.getProperties().putAll(properties);

var createSpringApplicationMethod = applicationClass.getDeclaredMethod("createSpringApplication", String[].class);
var applicationClass = appClassLoader.loadClass("com.github.bsideup.liiklus.Application");

var application = (SpringApplication) createSpringApplicationMethod.invoke(null, (Object) new String[0]);
application.setDefaultProperties(properties);
return application.run();
var createSpringApplicationMethod = applicationClass.getDeclaredMethod(
"start",
String[].class,
ApplicationContextInitializer[].class
);
return (ConfigurableApplicationContext) createSpringApplicationMethod.invoke(
null,
new String[0],
new ApplicationContextInitializer[0]
);
} finally {
System.setProperties(oldProperties);
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
Expand Down