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" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="99a808b4-b8c5-4c6a-8a7b-960f11e07db3" name="Changes" comment=""> <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/java/nl/mziesel/JmonitConfig.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/main/resources/JmonitConfig.pkl" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/resources/JmonitConfigTemplate.pkl" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" 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$/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/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> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -45,6 +49,12 @@
<item name="Tasks" type="e4a08cd1:TasksNode" /> <item name="Tasks" type="e4a08cd1:TasksNode" />
<item name="build" type="c8890929:TasksNode$1" /> <item name="build" type="c8890929:TasksNode$1" />
</path> </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> </expand>
<select /> <select />
</tree_state> </tree_state>
@ -57,6 +67,7 @@
<list> <list>
<option value="Class" /> <option value="Class" />
<option value="Pkl File" /> <option value="Pkl File" />
<option value="Pkl Template" />
</list> </list>
</option> </option>
</component> </component>
@ -77,9 +88,13 @@
"Gradle.jmonit [:JmonitConfig.main()].executor": "Run", "Gradle.jmonit [:JmonitConfig.main()].executor": "Run",
"Gradle.jmonit [:Main.main()].executor": "Run", "Gradle.jmonit [:Main.main()].executor": "Run",
"Gradle.jmonit [build].executor": "Run", "Gradle.jmonit [build].executor": "Run",
"Gradle.jmonit [clean].executor": "Run",
"Gradle.jmonit [configClasses].executor": "Run",
"Gradle.jmonit [jar].executor": "Run", "Gradle.jmonit [jar].executor": "Run",
"Gradle.jmonit [testPklConfig].executor": "Run",
"RunOnceActivity.OpenProjectViewOnStart": "true", "RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true", "RunOnceActivity.ShowReadmeOnStart": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"git-widget-placeholder": "gradle", "git-widget-placeholder": "gradle",
"kotlin-language-version-configured": "true", "kotlin-language-version-configured": "true",
"node.js.detected.package.eslint": "true", "node.js.detected.package.eslint": "true",
@ -114,6 +129,50 @@
<RunAsTest>false</RunAsTest> <RunAsTest>false</RunAsTest>
<method v="2" /> <method v="2" />
</configuration> </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"> <configuration name="jmonit [jar]" type="GradleRunConfiguration" factoryName="Gradle" temporary="true">
<ExternalSystemSettings> <ExternalSystemSettings>
<option name="executionName" /> <option name="executionName" />
@ -136,8 +195,33 @@
<RunAsTest>false</RunAsTest> <RunAsTest>false</RunAsTest>
<method v="2" /> <method v="2" />
</configuration> </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> <recent_temporary>
<list> <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 [jar]" />
<item itemvalue="Gradle.jmonit [build]" /> <item itemvalue="Gradle.jmonit [build]" />
</list> </list>
@ -158,13 +242,27 @@
<option name="number" value="Default" /> <option name="number" value="Default" />
<option name="presentableId" value="Default" /> <option name="presentableId" value="Default" />
<updated>1707061517834</updated> <updated>1707061517834</updated>
<workItem from="1707061518829" duration="1106000" /> <workItem from="1707061518829" duration="4346000" />
</task> </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 /> <servers />
</component> </component>
<component name="TypeScriptGeneratedFilesManager"> <component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" /> <option name="version" value="3" />
</component> </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"> <component name="XSLT-Support.FileAssociations.UIState">
<expand /> <expand />
<select /> <select />

View File

@ -2,6 +2,7 @@ plugins {
idea idea
`java-library` `java-library`
id("java") id("java")
id("org.pkl-lang") version("0.25.1")
} }
group = "nl.mziesel" group = "nl.mziesel"
@ -17,6 +18,27 @@ dependencies {
implementation("org.pkl-lang:pkl-config-java:0.25.1") 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 { tasks.test {
useJUnitPlatform() useJUnitPlatform()
} }

View File

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

View File

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

View File

@ -2,14 +2,16 @@ package nl.mziesel;
import java.io.IOException; import java.io.IOException;
public class IcmpMonitor extends BaseMonitor { public class IcmpMonitor extends BaseMonitor {
public IcmpMonitor(String name, String target) { public IcmpMonitor(JmonitConfig.Monitor monitor) {
super(name, target); super(monitor);
} }
@Override @Override
public MonitorStatus check() throws IOException, InterruptedException { public MonitorStatus check() throws IOException, InterruptedException {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 " + this.getTarget()); // Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 " + this.getTarget());
int returnVal = p1.waitFor(); // int returnVal = p1.waitFor();
return (returnVal == 0) ? MonitorStatus.ONLINE : MonitorStatus.OFFLINE; // 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; package nl.mziesel;
import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.pkl.config.java.Config; import org.pkl.config.java.Config;
import org.pkl.config.java.ConfigEvaluator; import org.pkl.config.java.ConfigEvaluator;
import org.pkl.config.java.JavaType;
import org.pkl.core.ModuleSource; import org.pkl.core.ModuleSource;
public class Main { public class Main {
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
Config config; Config config;
try (var evaluator = ConfigEvaluator.preconfigured()){ var evaluator = ConfigEvaluator.preconfigured();
config = evaluator.evaluate(ModuleSource.modulePath("jmonitconfig.pkl")); 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);
}
}
} }
System.out.println(config); // Register a shutdown hook to handle graceful shutdown
Runtime.getRuntime().addShutdownHook(new Thread(executorService::shutdown));
// ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor(); // keep running if not shutdown
while (!executorService.isTerminated()) {
Thread.sleep(100);
}
// HttpMonitor mzieselHttpMonit = new HttpMonitor("Website van Mans", "https://mziesel.nl/"); try {
// HttpMonitor testHttpMonit = new HttpMonitor("Test website", "https://whoami.mzsl.nl/"); // Wait for the tasks to complete before exiting
// HttpMonitor mcaHttpMonit = new HttpMonitor("Microcenter website", "https://microcenter.nl/"); if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {
// System.err.println("Some tasks did not complete within the timeout.");
// executorService.execute(mzieselHttpMonit); }
// executorService.execute(testHttpMonit); } catch (InterruptedException e) {
// executorService.execute(mcaHttpMonit); Thread.currentThread().interrupt();
}
// 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" typealias MonitorType = "http"|"https"|"icmp"
const defaultTimeout: Int = 5000 const defaultTimeout: Int = 5000
const defaultInterval: Int = 60 const defaultInterval: Int = 60
class Monitor { class Monitor {
monitorType: MonitorType
friendlyName: String friendlyName: String
target: String target: String
timeout: Int = defaultTimeout timeout: Int = defaultTimeout