commit 7f98db8a0f462066695a8eb6750dce3225942701 Author: Mark Nellemann Date: Sun Apr 25 15:25:20 2021 +0200 Initial commit, work in progress diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..00a51af --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0e13346 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# Ignore Gradle project-specific cache directory +.gradle +.idea + +# Ignore Gradle build output directory +build diff --git a/README.md b/README.md new file mode 100644 index 0000000..1cfbbd7 --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +# System Monitor + +... or some better name. + + +## Agent + +Runs on your host and collects metrics. Metrics are aggregated and sent to central *collector*. + +Metrics are currently processor, memory and disk usage statistics. + + +## TODO: Collector + +Receives aggregated measurements from agents and saves metrics info InfluxDB. \ No newline at end of file diff --git a/agent/build.gradle b/agent/build.gradle new file mode 100644 index 0000000..f084856 --- /dev/null +++ b/agent/build.gradle @@ -0,0 +1,47 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This generated file contains a sample Java application project to get you started. + * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle + * User Manual available at https://docs.gradle.org/7.0/userguide/building_java_projects.html + */ + +plugins { + id 'groovy' + id 'application' +} + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + testImplementation 'org.codehaus.groovy:groovy:3.0.7' + testImplementation 'org.spockframework:spock-core:2.0-M4-groovy-3.0' + testImplementation 'junit:junit:4.13.1' + testImplementation 'org.slf4j:slf4j-api:1.7.30' + testImplementation project(':shared') + + implementation project(':shared') + implementation 'org.slf4j:slf4j-api:1.7.30' + implementation 'org.slf4j:slf4j-simple:1.7.30' + + // https://mvnrepository.com/artifact/org.apache.camel/camel-core + implementation group: 'org.apache.camel', name: 'camel-core', version: '3.7.3' + implementation group: 'org.apache.camel', name: 'camel-main', version: '3.7.3' + implementation group: 'org.apache.camel', name: 'camel-bean', version: '3.7.3' + implementation group: 'org.apache.camel', name: 'camel-timer', version: '3.7.3' + implementation group: 'org.apache.camel', name: 'camel-stream', version: '3.7.3' + +} + +application { + // Define the main class for the application. + mainClass = 'org.sysmon.agent.Application' +} + +tasks.named('test') { + // Use junit platform for unit tests. + useJUnitPlatform() +} diff --git a/agent/src/main/java/org/sysmon/agent/Application.java b/agent/src/main/java/org/sysmon/agent/Application.java new file mode 100644 index 0000000..949bf05 --- /dev/null +++ b/agent/src/main/java/org/sysmon/agent/Application.java @@ -0,0 +1,26 @@ +/* + * This Java source file was generated by the Gradle 'init' task. + */ +package org.sysmon.agent; + +import org.apache.camel.main.Main; + +public class Application { + + public static void main(String[] args) { + + // use Camels Main class + Main main = new Main(); + + // and add the routes (you can specify multiple classes) + main.configure().addRoutesBuilder(MyRouteBuilder.class); + + // now keep the application running until the JVM is terminated (ctrl + c or sigterm) + try { + main.run(args); + } catch(Exception e) { + System.err.println(e.getMessage()); + } + + } +} diff --git a/agent/src/main/java/org/sysmon/agent/MetricProcessor.java b/agent/src/main/java/org/sysmon/agent/MetricProcessor.java new file mode 100644 index 0000000..069c9e2 --- /dev/null +++ b/agent/src/main/java/org/sysmon/agent/MetricProcessor.java @@ -0,0 +1,26 @@ +package org.sysmon.agent; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sysmon.shared.MetricResult; + +public class MetricProcessor implements Processor { + + private final static Logger log = LoggerFactory.getLogger(MetricProcessor.class); + + + public void process(Exchange exchange) throws Exception { + + MetricResult payload = exchange.getIn().getBody(MetricResult.class); + log.info(payload.toString()); + + // do something with the payload and/or exchange here + //exchange.getIn().setBody("Changed body"); + + // do something... + } + + +} diff --git a/agent/src/main/java/org/sysmon/agent/MyRouteBuilder.java b/agent/src/main/java/org/sysmon/agent/MyRouteBuilder.java new file mode 100644 index 0000000..3a67ab9 --- /dev/null +++ b/agent/src/main/java/org/sysmon/agent/MyRouteBuilder.java @@ -0,0 +1,31 @@ +package org.sysmon.agent; + +import org.apache.camel.builder.RouteBuilder; + +public class MyRouteBuilder extends RouteBuilder { + + @Override + public void configure() throws Exception { + + // Setup metrics measurement beans + // TODO: Discover beans on classpath and setup accordingly + from("timer:collect?period=5000") + .bean("memoryBean", "getMetrics") + .to("seda:metrics"); + from("timer:collect?period=5000") + .bean("processorBean", "getMetrics") + .to("seda:metrics"); + from("timer:collect?period=5000") + .bean("diskBean", "getMetrics") + .to("seda:metrics"); + + // TODO: Somehow combine all results in a format suitable for sending to REST endpoint + from("seda:metrics").process("metricProcessor"); + + // Could we store the last n results from each bean, and send mean value to the REST endpoint? + + + } + +} + diff --git a/agent/src/main/java/org/sysmon/agent/beans/DiskBean.java b/agent/src/main/java/org/sysmon/agent/beans/DiskBean.java new file mode 100644 index 0000000..9973b68 --- /dev/null +++ b/agent/src/main/java/org/sysmon/agent/beans/DiskBean.java @@ -0,0 +1,204 @@ +package org.sysmon.agent.beans; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.spi.Configurer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sysmon.shared.MetricBean; +import org.sysmon.shared.MetricMeasurement; +import org.sysmon.shared.MetricResult; + +@Configurer +public class DiskBean implements MetricBean { + + private final static Logger log = LoggerFactory.getLogger(DiskBean.class); + + private List currentDiskStats; + private List previousDiskStats; + + + @Override + public MetricResult getMetrics() { + + MetricResult result = new MetricResult("disk"); + try { + copyCurrentValues(); + readProcFile(); + result.setMeasurementList(calculate()); + } catch (IOException e) { + e.printStackTrace(); + } + + return result; + } + + + + private void readProcFile() throws IOException { + + currentDiskStats = new ArrayList<>(); + List allLines = Files.readAllLines(Paths.get("/proc/diskstats"), StandardCharsets.UTF_8); + for(String line : allLines) { + currentDiskStats.add(new LinuxDiskStat(line)); + } + + } + + + private void copyCurrentValues() { + + if(currentDiskStats != null && currentDiskStats.size() > 0) { + previousDiskStats = new ArrayList<>(currentDiskStats); + } + + } + + + private List calculate() { + + List measurementList = new ArrayList<>(); + + if(previousDiskStats == null || previousDiskStats.size() != currentDiskStats.size()) { + return measurementList; + } + + + for(int i = 0; i < currentDiskStats.size(); i++) { + + LinuxDiskStat curStat = currentDiskStats.get(i); + LinuxDiskStat preStat = previousDiskStats.get(i); + + if(curStat.device.startsWith("loop")) { + continue; + } + + // TODO: Calculate differences for wanted disk io stats + measurementList.add(new MetricMeasurement(curStat.getDevice(), 0)); + + } + + return measurementList; + } + + + public static class LinuxDiskStat { + /* + == =================================== + 1 major number + 2 minor mumber + 3 device name + 4 reads completed successfully + 5 reads merged + 6 sectors read + 7 time spent reading (ms) + 8 writes completed + 9 writes merged + 10 sectors written + 11 time spent writing (ms) + 12 I/Os currently in progress + 13 time spent doing I/Os (ms) + 14 weighted time spent doing I/Os (ms) + == =================================== + + Kernel 4.18+ appends four more fields for discard + tracking putting the total at 18: + + == =================================== + 15 discards completed successfully + 16 discards merged + 17 sectors discarded + 18 time spent discarding + == =================================== + + Kernel 5.5+ appends two more fields for flush requests: + + == ===================================== + 19 flush requests completed successfully + 20 time spent flushing + == ===================================== + */ + + private final int major; + private final int minor; + private final String device; // device name + private final Long readsCompleted; // successfully + private final Long readsMerged; + private final Long sectorsRead; // 512 bytes pr. sector + private final Long timeSpentReading; // ms + private final Long writesCompleted; // successfully + private final Long writesMerged; + private final Long sectorsWritten; // 512 bytes pr. sector + private final Long timeSpentWriting; // ms + private final Long ioInProgress; + private final Long timeSpentOnIo; // ms + private final Long timeSpentOnIoWeighted; + + private final Long discardsCompleted; // successfully + private final Long discardsMerged; + private final Long sectorsDiscarded; // 512 bytes pr. sector + private final Long timeSpentDiscarding; // ms + + private final Long flushRequestsCompleted; + private final Long timeSpentFlushing; // ms + + + LinuxDiskStat(String procString) { + + String[] splitStr = procString.trim().split("\\s+"); + if(splitStr.length < 14) { + throw new UnsupportedOperationException("Linux proc DISK string error: " + procString); + } + + this.major = Integer.parseInt(splitStr[0]); + this.minor = Integer.parseInt(splitStr[1]); + this.device = splitStr[2]; + this.readsCompleted = Long.parseLong(splitStr[3]); + this.readsMerged = Long.parseLong(splitStr[4]); + this.sectorsRead = Long.parseLong(splitStr[5]); + this.timeSpentReading = Long.parseLong(splitStr[6]); + this.writesCompleted = Long.parseLong(splitStr[7]); + this.writesMerged = Long.parseLong(splitStr[8]); + this.sectorsWritten = Long.parseLong(splitStr[9]); + this.timeSpentWriting = Long.parseLong(splitStr[10]); + this.ioInProgress = Long.parseLong(splitStr[11]); + this.timeSpentOnIo = Long.parseLong(splitStr[12]); + this.timeSpentOnIoWeighted = Long.parseLong(splitStr[13]); + + if(splitStr.length >= 18) { + this.discardsCompleted = Long.parseLong(splitStr[10]); + this.discardsMerged = Long.parseLong(splitStr[11]); + this.sectorsDiscarded = Long.parseLong(splitStr[12]); + this.timeSpentDiscarding = Long.parseLong(splitStr[13]); + } else { + this.discardsCompleted = null; + this.discardsMerged = null; + this.sectorsDiscarded = null; + this.timeSpentDiscarding = null; + } + + if(splitStr.length == 20) { + this.flushRequestsCompleted = Long.parseLong(splitStr[14]); + this.timeSpentFlushing = Long.parseLong(splitStr[15]); + } else { + this.flushRequestsCompleted = null; + this.timeSpentFlushing = null; + } + + } + + public String getDevice() { + return device; + } + + + } + +} + + diff --git a/agent/src/main/java/org/sysmon/agent/beans/MemoryBean.java b/agent/src/main/java/org/sysmon/agent/beans/MemoryBean.java new file mode 100644 index 0000000..ec17c3e --- /dev/null +++ b/agent/src/main/java/org/sysmon/agent/beans/MemoryBean.java @@ -0,0 +1,59 @@ +package org.sysmon.agent.beans; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.camel.spi.Configurer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sysmon.shared.MetricBean; +import org.sysmon.shared.MetricMeasurement; +import org.sysmon.shared.MetricResult; + +@Configurer +public class MemoryBean implements MetricBean { + + private final static Logger log = LoggerFactory.getLogger(MemoryBean.class); + private final Pattern pattern = Pattern.compile("^([a-zA-Z]+):\\s+(\\d+)\\s+"); + + + @Override + public MetricResult getMetrics() { + + MetricResult result = new MetricResult("memory"); + try { + result.setMeasurementList(readProcFile()); + } catch (IOException e) { + e.printStackTrace(); + } + + return result; + } + + + + private List readProcFile() throws IOException { + + List measurementList = new ArrayList<>(); + + List allLines = Files.readAllLines(Paths.get("/proc/meminfo"), StandardCharsets.UTF_8); + for(String line : allLines) { + + if(line.startsWith("Mem")) { + Matcher matcher = pattern.matcher(line); + if(matcher.find() && matcher.groupCount() == 2) { + measurementList.add(new MetricMeasurement(matcher.group(1), matcher.group(2))); + } + } + } + + return measurementList; + } + +} \ No newline at end of file diff --git a/agent/src/main/java/org/sysmon/agent/beans/ProcessorBean.java b/agent/src/main/java/org/sysmon/agent/beans/ProcessorBean.java new file mode 100644 index 0000000..fe990b9 --- /dev/null +++ b/agent/src/main/java/org/sysmon/agent/beans/ProcessorBean.java @@ -0,0 +1,188 @@ +package org.sysmon.agent.beans; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.spi.Configurer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sysmon.shared.MetricBean; +import org.sysmon.shared.MetricMeasurement; +import org.sysmon.shared.MetricResult; + +@Configurer +public class ProcessorBean implements MetricBean { + + private final static Logger log = LoggerFactory.getLogger(ProcessorBean.class); + + private List currentProcessorStats; + private List previousProcessorStats; + + + @Override + public MetricResult getMetrics() { + + MetricResult result = new MetricResult("processor"); + try { + copyCurrentValues(); + readProcFile(); + result.setMeasurementList(calculate()); + } catch (IOException e) { + e.printStackTrace(); + } + + return result; + } + + + private void readProcFile() throws IOException { + + currentProcessorStats = new ArrayList<>(); + List allLines = Files.readAllLines(Paths.get("/proc/stat"), StandardCharsets.UTF_8); + for(String line : allLines) { + if(line.startsWith("cpu")) { + log.debug(line); + currentProcessorStats.add(new LinuxProcessorStat(line)); + } + } + + } + + + private void copyCurrentValues() { + + if(currentProcessorStats != null && currentProcessorStats.size() > 0) { + previousProcessorStats = new ArrayList<>(currentProcessorStats); + } + + } + + + private List calculate() { + + List measurementList = new ArrayList<>(); + + if(previousProcessorStats == null || previousProcessorStats.size() != currentProcessorStats.size()) { + return measurementList; + } + + for(int i = 0; i < currentProcessorStats.size(); i++) { + + LinuxProcessorStat curStat = currentProcessorStats.get(i); + LinuxProcessorStat preStat = previousProcessorStats.get(i); + + long workTimeDiff = curStat.getCombinedTime() - preStat.getCombinedTime(); + long idleTimeDiff = curStat.getCombinedIdleTime() - preStat.getCombinedIdleTime(); + float percentUsage = (float) (workTimeDiff - idleTimeDiff) / workTimeDiff; + + Integer pct = (int) (percentUsage * 100); + measurementList.add(new MetricMeasurement(curStat.getCpuName(), pct)); + + } + + return measurementList; + + } + + + public static class LinuxProcessorStat { + + private final String cpuName; + private final Long userTime; + private final Long niceTime; + private final Long systemTime; + private final Long idleTime; + private final Long ioWaitTime; + private final Long irqTime; + private final Long softIrqTime; + private final Long stealTime; + private final Long guestTime; + private final Long guestNiceTime; + + + LinuxProcessorStat(String procString) { + + String[] splitStr = procString.trim().split("\\s+"); + if(splitStr.length != 11) { + throw new UnsupportedOperationException("Linux proc CPU string error: " + procString); + } + + this.cpuName = splitStr[0]; + this.userTime = Long.parseLong(splitStr[1]); + this.niceTime = Long.parseLong(splitStr[2]); + this.systemTime = Long.parseLong(splitStr[3]); + this.idleTime = Long.parseLong(splitStr[4]); + this.ioWaitTime = Long.parseLong(splitStr[5]); + this.irqTime = Long.parseLong(splitStr[6]); + this.softIrqTime = Long.parseLong(splitStr[7]); + this.stealTime = Long.parseLong(splitStr[8]); + this.guestTime = Long.parseLong(splitStr[9]); + this.guestNiceTime = Long.parseLong(splitStr[10]); + + } + + public String getCpuName() { + return cpuName; + } + + public Long getUserTime() { + return userTime; + } + + public Long getNiceTime() { + return niceTime; + } + + public Long getSystemTime() { + return systemTime; + } + + public Long getIdleTime() { + return idleTime; + } + + public Long getIoWaitTime() { + return ioWaitTime; + } + + public Long getIrqTime() { + return irqTime; + } + + public Long getSoftIrqTime() { + return softIrqTime; + } + + public Long getStealTime() { + return stealTime; + } + + public Long getGuestTime() { + return guestTime; + } + + public Long getGuestNiceTime() { + return guestNiceTime; + } + + public Long getCombinedIdleTime() { + return idleTime + ioWaitTime; + } + + public Long getCombinedWorkTime() { + return userTime + niceTime + systemTime + irqTime + softIrqTime + stealTime + guestTime + guestNiceTime; + } + + public Long getCombinedTime() { + return getCombinedIdleTime() + getCombinedWorkTime(); + } + + } + +} + + diff --git a/agent/src/main/resources/application.properties b/agent/src/main/resources/application.properties new file mode 100644 index 0000000..a23a07f --- /dev/null +++ b/agent/src/main/resources/application.properties @@ -0,0 +1,45 @@ +## --------------------------------------------------------------------------- +## Licensed to the Apache Software Foundation (ASF) under one or more +## contributor license agreements. See the NOTICE file distributed with +## this work for additional information regarding copyright ownership. +## The ASF licenses this file to You 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. +## --------------------------------------------------------------------------- + +# to configure camel main +# here you can configure options on camel main (see MainConfigurationProperties class) +camel.main.name = SysMonAgent + +# enable tracing +### camel.main.tracing = true + +# bean introspection to log reflection based configuration +camel.main.beanIntrospectionExtendedStatistics=true +camel.main.beanIntrospectionLoggingLevel=INFO + +# run in lightweight mode to be tiny as possible +camel.main.lightweight = true +# and eager load classes +#camel.main.eager-classloading = true + +# use object pooling to reduce JVM garbage collection +#camel.main.exchange-factory = pooled +#camel.main.exchange-factory-statistics-enabled = true + +# can be used to not start the route +# camel.main.auto-startup = false + +# configure beans +camel.beans.metricProcessor = #class:org.sysmon.agent.MetricProcessor +camel.beans.diskBean = #class:org.sysmon.agent.beans.DiskBean +camel.beans.memoryBean = #class:org.sysmon.agent.beans.MemoryBean +camel.beans.processorBean = #class:org.sysmon.agent.beans.ProcessorBean diff --git a/agent/src/test/groovy/org/sysmon/test/AppTest.groovy b/agent/src/test/groovy/org/sysmon/test/AppTest.groovy new file mode 100644 index 0000000..8bc2515 --- /dev/null +++ b/agent/src/test/groovy/org/sysmon/test/AppTest.groovy @@ -0,0 +1,12 @@ +/* + * This Spock specification was generated by the Gradle 'init' task. + */ +package org.sysmon.test + +import spock.lang.Specification + +class AppTest extends Specification { + + + +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..f371643 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or 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 +# +# https://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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..20c03b4 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,11 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/7.0/userguide/multi_project_builds.html + */ + +rootProject.name = 'sysmon' +include('shared', 'agent') diff --git a/shared/build.gradle b/shared/build.gradle new file mode 100644 index 0000000..8e35184 --- /dev/null +++ b/shared/build.gradle @@ -0,0 +1,33 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This generated file contains a sample Java application project to get you started. + * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle + * User Manual available at https://docs.gradle.org/7.0/userguide/building_java_projects.html + */ + +plugins { + id 'groovy' + id 'java-library' +} + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + testImplementation 'org.codehaus.groovy:groovy:3.0.7' + testImplementation 'org.spockframework:spock-core:2.0-M4-groovy-3.0' + testImplementation 'junit:junit:4.13.1' + testImplementation 'org.slf4j:slf4j-api:1.7.30' + + implementation 'org.slf4j:slf4j-api:1.7.30' + implementation 'org.slf4j:slf4j-simple:1.7.30' + +} + +tasks.named('test') { + // Use junit platform for unit tests. + useJUnitPlatform() +} diff --git a/shared/src/main/java/org/sysmon/shared/MetricBean.java b/shared/src/main/java/org/sysmon/shared/MetricBean.java new file mode 100644 index 0000000..3ffe2e4 --- /dev/null +++ b/shared/src/main/java/org/sysmon/shared/MetricBean.java @@ -0,0 +1,7 @@ +package org.sysmon.shared; + +public interface MetricBean { + + public MetricResult getMetrics(); + +} diff --git a/shared/src/main/java/org/sysmon/shared/MetricMeasurement.java b/shared/src/main/java/org/sysmon/shared/MetricMeasurement.java new file mode 100644 index 0000000..e7d1960 --- /dev/null +++ b/shared/src/main/java/org/sysmon/shared/MetricMeasurement.java @@ -0,0 +1,17 @@ +package org.sysmon.shared; + +public class MetricMeasurement { + + private String name; + private Object value; + + public MetricMeasurement(String name, Object value) { + this.name = name; + this.value = value; + } + + public String toString() { + return String.format("%s: %s", name, value); + } + +} diff --git a/shared/src/main/java/org/sysmon/shared/MetricResult.java b/shared/src/main/java/org/sysmon/shared/MetricResult.java new file mode 100644 index 0000000..881b534 --- /dev/null +++ b/shared/src/main/java/org/sysmon/shared/MetricResult.java @@ -0,0 +1,31 @@ +package org.sysmon.shared; + +import java.time.Instant; +import java.util.List; + +public class MetricResult { + + private final String name; + private final Instant timestamp; + private List measurementList; + + public MetricResult(String name) { + this.name = name; + this.timestamp = Instant.now(); + } + + public void setMeasurementList(List measurementList) { + this.measurementList = measurementList; + } + + + public String toString() { + StringBuilder sb = new StringBuilder(name).append("\n"); + for(MetricMeasurement mm : measurementList) { + sb.append(mm.toString()).append("\n"); + } + + return sb.toString(); + } + +}