Make application use monitors in config, try handle gracefull shutdown

This commit is contained in:
Mans Ziesel 2024-02-04 18:16:44 +01:00
parent bec9ff0895
commit 431ad8f92d
9 changed files with 185 additions and 87 deletions

View File

@ -4,12 +4,16 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="99a808b4-b8c5-4c6a-8a7b-960f11e07db3" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/src/main/java/nl/mziesel/JmonitConfig.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/resources/JmonitConfigTemplate.pkl" afterDir="false" />
<list default="true" id="99a808b4-b8c5-4c6a-8a7b-960f11e07db3" name="Changes" comment="Make PKL work, use config in application">
<change afterPath="$PROJECT_DIR$/src/main/resources/JmonitConfig.pkl" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/build.gradle.kts" beforeDir="false" afterPath="$PROJECT_DIR$/build.gradle.kts" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/nl/mziesel/BaseMonitor.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/nl/mziesel/BaseMonitor.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/nl/mziesel/HttpMonitor.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/nl/mziesel/HttpMonitor.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/nl/mziesel/IcmpMonitor.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/nl/mziesel/IcmpMonitor.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/nl/mziesel/JmonitConfig.java" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/nl/mziesel/Main.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/nl/mziesel/Main.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/resources/JmonitConfigTemplate.pkl" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/resources/JmonitConfigTemplate.pkl" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -45,6 +49,12 @@
<item name="Tasks" type="e4a08cd1:TasksNode" />
<item name="build" type="c8890929:TasksNode$1" />
</path>
<path>
<item name="" type="6a2764b6:ExternalProjectsStructure$RootNode" />
<item name="jmonit" type="f1a62948:ProjectNode" />
<item name="Tasks" type="e4a08cd1:TasksNode" />
<item name="other" type="c8890929:TasksNode$1" />
</path>
</expand>
<select />
</tree_state>
@ -57,6 +67,7 @@
<list>
<option value="Class" />
<option value="Pkl File" />
<option value="Pkl Template" />
</list>
</option>
</component>
@ -77,9 +88,13 @@
"Gradle.jmonit [:JmonitConfig.main()].executor": "Run",
"Gradle.jmonit [:Main.main()].executor": "Run",
"Gradle.jmonit [build].executor": "Run",
"Gradle.jmonit [clean].executor": "Run",
"Gradle.jmonit [configClasses].executor": "Run",
"Gradle.jmonit [jar].executor": "Run",
"Gradle.jmonit [testPklConfig].executor": "Run",
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"git-widget-placeholder": "gradle",
"kotlin-language-version-configured": "true",
"node.js.detected.package.eslint": "true",
@ -114,6 +129,50 @@
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
<configuration name="jmonit [clean]" type="GradleRunConfiguration" factoryName="Gradle" temporary="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="clean" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
<configuration name="jmonit [configClasses]" type="GradleRunConfiguration" factoryName="Gradle" temporary="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="configClasses" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
<configuration name="jmonit [jar]" type="GradleRunConfiguration" factoryName="Gradle" temporary="true">
<ExternalSystemSettings>
<option name="executionName" />
@ -136,8 +195,33 @@
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
<configuration name="jmonit [testPklConfig]" type="GradleRunConfiguration" factoryName="Gradle" temporary="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="testPklConfig" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
<recent_temporary>
<list>
<item itemvalue="Gradle.jmonit [testPklConfig]" />
<item itemvalue="Gradle.jmonit [configClasses]" />
<item itemvalue="Gradle.jmonit [clean]" />
<item itemvalue="Gradle.jmonit [jar]" />
<item itemvalue="Gradle.jmonit [build]" />
</list>
@ -158,13 +242,27 @@
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1707061517834</updated>
<workItem from="1707061518829" duration="1106000" />
<workItem from="1707061518829" duration="4346000" />
</task>
<task id="LOCAL-00001" summary="Add PKL lib, add test config, create initial jmonit config template">
<option name="closed" value="true" />
<created>1707062676829</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1707062676829</updated>
</task>
<option name="localTasksCounter" value="2" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="Add PKL lib, add test config, create initial jmonit config template" />
<MESSAGE value="Make PKL work, use config in application" />
<option name="LAST_COMMIT_MESSAGE" value="Make PKL work, use config in application" />
</component>
<component name="XSLT-Support.FileAssociations.UIState">
<expand />
<select />

View File

@ -2,6 +2,7 @@ plugins {
idea
`java-library`
id("java")
id("org.pkl-lang") version("0.25.1")
}
group = "nl.mziesel"
@ -17,6 +18,27 @@ dependencies {
implementation("org.pkl-lang:pkl-config-java:0.25.1")
}
pkl {
javaCodeGenerators {
register("configClasses") {
sourceModules.set(files("src/main/resources/JmonitConfigTemplate.pkl"))
generateJavadoc.set(true)
}
}
evaluators {
// Create an evaluator that evaluates the application's runtime configuration.
// This creates an equally named task called "testPklConfig".
//
// This task is registered as a dependency to `check`, so that Pkl modules are checked for
// correctness as part of a project's tests.
register("testPklConfig") {
sourceModules.set(files("src/main/resources/JmonitConfig.pkl"))
modulePath.from(sourceSets.main.get().runtimeClasspath)
outputFile.set(file("${layout.buildDirectory.get()}/testPklConfig/config"))
}
}
}
tasks.test {
useJUnitPlatform()
}

View File

@ -14,11 +14,11 @@ public abstract class BaseMonitor implements Runnable {
OFFLINE,
UNKNOWN
}
public BaseMonitor(String name, String target) {
this.friendlyName = name;
this.target = target;
this.interval = 5000;
this.timeout = 15000;
public BaseMonitor(JmonitConfig.Monitor monitor) {
this.friendlyName = monitor.friendlyName;
this.target = monitor.target;
this.interval = (int) monitor.interval;
this.timeout = (int) monitor.timeout;
this.prevCheckStatus = MonitorStatus.UNKNOWN;
}

View File

@ -5,8 +5,8 @@ import java.io.IOException;
import java.net.URI;
public class HttpMonitor extends BaseMonitor{
public HttpMonitor(String name, String target) {
super(name, target);
public HttpMonitor(JmonitConfig.Monitor monitor) {
super(monitor);
}
@Override

View File

@ -2,14 +2,16 @@ package nl.mziesel;
import java.io.IOException;
public class IcmpMonitor extends BaseMonitor {
public IcmpMonitor(String name, String target) {
super(name, target);
public IcmpMonitor(JmonitConfig.Monitor monitor) {
super(monitor);
}
@Override
public MonitorStatus check() throws IOException, InterruptedException {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 " + this.getTarget());
int returnVal = p1.waitFor();
return (returnVal == 0) ? MonitorStatus.ONLINE : MonitorStatus.OFFLINE;
// Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 " + this.getTarget());
// int returnVal = p1.waitFor();
// return (returnVal == 0) ? MonitorStatus.ONLINE : MonitorStatus.OFFLINE;
// *Temp fix*
return MonitorStatus.ONLINE;
}
}

View File

@ -1,55 +0,0 @@
package nl.mziesel;
import org.pkl.config.java.Config;
import org.pkl.config.java.ConfigEvaluator;
import org.pkl.config.java.JavaType;
import org.pkl.core.ModuleSource;
public class JmonitConfig {
public static void main(String[] args) {
// Configuration is represented as a tree of `Config` objects.
Config config;
// To evaluate a Pkl module to a `Config` tree,
// create a `ConfigEvaluator` and call its `evaluate()` method.
//
// There are two ways to create a `ConfigEvaluator`:
// * `ConfigEvaluator.preconfigured()`
// * `ConfigEvaluatorBuilder`
//
// `ConfigEvaluator.preconfigured()` behaves much the same as the CLI.
// For example, it allows evaluating modules over HTTPS, which isn't always desirable.
// `ConfigEvaluatorBuilder` gives more control over a `ConfigEvaluator`'s behavior.
//
// It's important to close an evaluator after the last `evaluate()` call.
// Previously returned `Config` objects remain valid.
try (var evaluator = ConfigEvaluator.preconfigured()) {
config = evaluator.evaluate(ModuleSource.text("""
parrot {
name = "Polly";
age = 31;
favoriteFoods = new Listing {
apples";
"crackers"
}
}
"""
));
}
// To descend the `Config` tree, use the `get()` method,
// which returns another `Config` object.
var parrot = config.get("parrot");
// To access a `Config` object's value,
// call `as()` and pass the Java type to convert the value to.
// The conversion is performed by `ConfigEvaluator.getValueMapper()`,
// which can be customized via `ConfigEvaluatorBuilder`.
var age = parrot.get("age").as(int.class);
System.out.println(age);
// The `as()` method also accepts parameterized types such as `List<String>`.
var favoriteFoods = parrot.get("favoriteFoods").as(JavaType.listOf(String.class));
System.out.println(favoriteFoods);
}
}

View File

@ -1,34 +1,52 @@
package nl.mziesel;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.pkl.config.java.Config;
import org.pkl.config.java.ConfigEvaluator;
import org.pkl.config.java.JavaType;
import org.pkl.core.ModuleSource;
public class Main {
public static void main(String[] args) throws InterruptedException {
Config config;
try (var evaluator = ConfigEvaluator.preconfigured()){
config = evaluator.evaluate(ModuleSource.modulePath("jmonitconfig.pkl"));
var evaluator = ConfigEvaluator.preconfigured();
config = evaluator.evaluate(ModuleSource.modulePath("/JmonitConfig.pkl"));
List<JmonitConfig.Monitor> monitors = config.as(JmonitConfig.class).monitors;
ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
for (JmonitConfig.Monitor mon: monitors) {
switch (mon.monitorType) {
case JmonitConfig.MonitorType.HTTPS -> {
HttpMonitor httpMonitor = new HttpMonitor(mon);
executorService.execute(httpMonitor);
}
case JmonitConfig.MonitorType.ICMP -> {
IcmpMonitor icmpMonitor = new IcmpMonitor(mon);
executorService.execute(icmpMonitor);
}
}
}
// Register a shutdown hook to handle graceful shutdown
Runtime.getRuntime().addShutdownHook(new Thread(executorService::shutdown));
// keep running if not shutdown
while (!executorService.isTerminated()) {
Thread.sleep(100);
}
try {
// Wait for the tasks to complete before exiting
if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {
System.err.println("Some tasks did not complete within the timeout.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(config);
// ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
// HttpMonitor mzieselHttpMonit = new HttpMonitor("Website van Mans", "https://mziesel.nl/");
// HttpMonitor testHttpMonit = new HttpMonitor("Test website", "https://whoami.mzsl.nl/");
// HttpMonitor mcaHttpMonit = new HttpMonitor("Microcenter website", "https://microcenter.nl/");
//
// executorService.execute(mzieselHttpMonit);
// executorService.execute(testHttpMonit);
// executorService.execute(mcaHttpMonit);
// while (!executorService.isTerminated()) {
// Thread.sleep(1000);
// }
}
}

View File

@ -0,0 +1,9 @@
amends "./JmonitConfigTemplate.pkl"
monitors {
new {
monitorType = "https"
friendlyName = "Website Mans"
target = "https://mziesel.nl/"
}
}

View File

@ -1,9 +1,13 @@
@ModuleInfo { minPklVersion = "0.25.1" }
module nl.mziesel.JmonitConfig
typealias MonitorType = "http"|"https"|"icmp"
const defaultTimeout: Int = 5000
const defaultInterval: Int = 60
class Monitor {
monitorType: MonitorType
friendlyName: String
target: String
timeout: Int = defaultTimeout