diff --git a/.gitignore b/.gitignore index 5759fa9..48d32c6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,30 @@ -*.pyo -*.pyc -*.swp -build -.gradle -bin/ -.project -*.iml -.idea/ -eclipse/ -.classpath -logs/ -.settings -target/ +*.pyo +*.pyc +*.swp +build +.gradle +bin/ +.project +*.iml +.idea/ +eclipse/ +.classpath +logs/ +.settings +target/ + +#forge .idea things: +*.ipr +*.iws +# Editor/tooling droppings +.vscode/ +.cursor/ +.codegraph/ +graphify-out/ +*.code-workspace -#forge .idea things: -*.ipr -*.iws \ No newline at end of file +# Local tool installs / build output not meant for version control +mvn-bin/ +dist/ +node_modules/ +*.tar.gz diff --git a/SplunkCraft/default/app.conf b/SplunkCraft/default/app.conf new file mode 100644 index 0000000..b006f64 --- /dev/null +++ b/SplunkCraft/default/app.conf @@ -0,0 +1,23 @@ +# +# SplunkCraft -- Minecraft player analytics app. +# Owns the minecraft_player_stats KV-store collection populated by the logtosplunk plugin, +# plus the reports and dashboards built on top of it. +# + +[install] +state = enabled +state_change_requires_restart = 0 +is_configured = 1 +build = 1 + +[ui] +is_visible = 1 +label = SplunkCraft + +[launcher] +author = masao.jeffery@gmail.com +description = Minecraft player stats, reports and dashboards (KV-store backed). +version = 1.0 + +[package] +id = SplunkCraft diff --git a/SplunkCraft/default/collections.conf b/SplunkCraft/default/collections.conf new file mode 100644 index 0000000..77139cc --- /dev/null +++ b/SplunkCraft/default/collections.conf @@ -0,0 +1,9 @@ +# KV-store collection holding the latest per-player snapshot scraped from the Minecraft +# server's on-disk stats/advancements JSON by the logtosplunk plugin (PlayerStatsScraper). +# Documents are keyed by player UUID (_key), so each scrape upserts (overwrites) the player's +# row rather than appending -- this is current-state snapshot data, not a time series. + +[minecraft_player_stats] +enforceTypes = false +# Accelerate the fields we filter/sort on most. +accelerated_fields.player_idx = {"uuid": 1, "name": 1} diff --git a/SplunkCraft/default/transforms.conf b/SplunkCraft/default/transforms.conf new file mode 100644 index 0000000..ac021c6 --- /dev/null +++ b/SplunkCraft/default/transforms.conf @@ -0,0 +1,14 @@ +# Lookup definition exposing the minecraft_player_stats KV-store collection to SPL. +# Use in searches as: | inputlookup minecraft_player_stats +# or: ... | lookup minecraft_player_stats uuid OUTPUT name advancements_completed ... + +[minecraft_player_stats] +external_type = kvstore +collection = minecraft_player_stats +fields_list = _key, uuid, name, last_modified, data_version, \ + stat_mined_total, stat_used_total, stat_crafted_total, stat_broken_total, \ + stat_dropped_total, stat_picked_up_total, stat_killed_total, stat_killed_by_total, \ + stat_custom_total, \ + deaths, mob_kills, player_kills, play_time, total_world_time, walk_one_cm, sprint_one_cm, \ + jump, damage_dealt, damage_taken, time_since_rest, \ + advancements_completed, advancements_total diff --git a/SplunkCraft/metadata/default.meta b/SplunkCraft/metadata/default.meta new file mode 100644 index 0000000..fa4faed --- /dev/null +++ b/SplunkCraft/metadata/default.meta @@ -0,0 +1,12 @@ +# Make the collection and its lookup readable app-wide (and globally, so other apps and +# saved searches can reference the lookup). Writes restricted to admin/power. + +[] +access = read : [ * ], write : [ admin, power ] +export = system + +[collections/minecraft_player_stats] +export = system + +[transforms/minecraft_player_stats] +export = system diff --git a/default/app.conf b/default/app.conf index ad18d6b..0ff0a44 100755 --- a/default/app.conf +++ b/default/app.conf @@ -1,21 +1,22 @@ -# -# Splunk app configuration file -# - -[install] -state = enabled -state_change_requires_restart = 0 -is_configured = 0 -build = 1 - -[ui] -is_visible = 1 -label = Minecraft - -[launcher] -author = mpapale@splunk.com -description = The Splunk App for Minecraft let's you visualize your Minecraft server data. -version = 1.0 - -[package] -id = minecraft-app +# +# Splunk app configuration file +# + +[install] +state = enabled +state_change_requires_restart = 0 +is_configured = 0 +build = 1 + +[ui] +is_visible = 1 +label = Minecraft +supported_themes = light, dark + +[launcher] +author = mpapale@splunk.com +description = The Splunk App for Minecraft let's you visualize your Minecraft server data. +version = 1.0 + +[package] +id = minecraft-app diff --git a/forge-1.20.1-47.4.20/build.gradle b/forge-1.20.1-47.4.20/build.gradle new file mode 100644 index 0000000..810406e --- /dev/null +++ b/forge-1.20.1-47.4.20/build.gradle @@ -0,0 +1,97 @@ +plugins { + id 'eclipse' + id 'idea' + id 'net.minecraftforge.gradle' version '[6.0,6.2)' + id 'com.github.johnrengelman.shadow' version '8.1.1' + id 'java' +} + +version = "${mod_version}" +group = "${mod_group_id}" + +base { + archivesName = "${archives_base_name}" +} + +java { + toolchain.languageVersion = JavaLanguageVersion.of(17) +} + +minecraft { + // 1.20.1 uses Mojang's official mappings. + mappings channel: 'official', version: minecraft_version + copyIdeResources = true +} + +// Reuse the platform-agnostic core from the shared-mc module (single source of truth). +sourceSets.main.java.srcDir '../shared-mc/src/main/java' + +// 'shade' holds runtime libs that Minecraft/Forge does NOT provide; they get fat-jarred +// into the final mod jar by shadowJar, then reobfuscated. +configurations { + shade + implementation.extendsFrom shade +} + +repositories { + mavenCentral() + maven { + name = 'Splunk Artifactory' + url = 'https://splunk.jfrog.io/splunk/ext-releases-local/' + } +} + +dependencies { + minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" + + // Provided by Minecraft/Forge at runtime: compile-only, not bundled. + compileOnly "com.google.code.gson:gson:2.13.2" + compileOnly "com.google.guava:guava:33.5.0-jre" + + // Not provided by Minecraft/Forge: bundle via shadow (transitive=false, exact set only). + // httpcore5-h2 is REQUIRED even for plain HTTP: httpclient5's TlsConfig references + // org.apache.hc.core5.http2.HttpVersionPolicy. Omitting it => NoClassDefFoundError on + // the first POST. + shade("com.splunk.logging:splunk-library-javalogging:1.11.8") { transitive = false } + shade("org.apache.httpcomponents.client5:httpclient5:5.5.1") { transitive = false } + shade("org.apache.httpcomponents.core5:httpcore5:5.3.6") { transitive = false } + shade("org.apache.httpcomponents.core5:httpcore5-h2:5.3.6") { transitive = false } + shade("commons-codec:commons-codec:1.17.1") { transitive = false } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' +} + +// Plain jar = thin dev jar (named mappings, NO bundled libs). Pushed to build/devlibs so it +// can never be mistaken for the shippable artifact in build/libs. Deploying it = missing +// httpcore5 at runtime. The shaded+reobf shadowJar (build/libs) is the only deployable jar. +tasks.named('jar', Jar) { + archiveClassifier = 'slim' + destinationDirectory = layout.buildDirectory.dir('devlibs') + manifest { + attributes([ + 'Implementation-Version': project.version, + 'Specification-Title' : 'logtosplunk', + 'Specification-Version' : '1' + ]) + } +} + +tasks.named('shadowJar') { + configurations = [project.configurations.shade] + archiveClassifier = '' + manifest { + attributes(['Implementation-Version': project.version]) + } + finalizedBy 'reobfShadowJar' +} + +// Reobfuscate the shaded jar from official -> SRG so Forge can load it at runtime. +reobf { + shadowJar { } +} + +tasks.named('assemble') { + dependsOn 'shadowJar' +} diff --git a/forge-1.20.1-47.4.20/gradle.properties b/forge-1.20.1-47.4.20/gradle.properties new file mode 100644 index 0000000..bc972a2 --- /dev/null +++ b/forge-1.20.1-47.4.20/gradle.properties @@ -0,0 +1,9 @@ +org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=false + +minecraft_version=1.20.1 +forge_version=47.4.20 + +mod_version=1.0.0 +mod_group_id=com.splunk +archives_base_name=logtosplunk-forge-47.4.20 diff --git a/forge-1.20.1-47.4.20/gradle/wrapper/gradle-wrapper.jar b/forge-1.20.1-47.4.20/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/forge-1.20.1-47.4.20/gradle/wrapper/gradle-wrapper.jar differ diff --git a/forge-1.20.1-47.4.20/gradle/wrapper/gradle-wrapper.properties b/forge-1.20.1-47.4.20/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a441313 --- /dev/null +++ b/forge-1.20.1-47.4.20/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/forge-1.20.1-47.4.20/gradlew b/forge-1.20.1-47.4.20/gradlew new file mode 100644 index 0000000..b740cf1 --- /dev/null +++ b/forge-1.20.1-47.4.20/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/forge-1.20.1-47.4.20/gradlew.bat b/forge-1.20.1-47.4.20/gradlew.bat new file mode 100644 index 0000000..7101f8e --- /dev/null +++ b/forge-1.20.1-47.4.20/gradlew.bat @@ -0,0 +1,92 @@ +@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=. +@rem This is normally unused +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% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/forge-1.20.1-47.4.20/settings.gradle b/forge-1.20.1-47.4.20/settings.gradle new file mode 100644 index 0000000..aed928d --- /dev/null +++ b/forge-1.20.1-47.4.20/settings.gradle @@ -0,0 +1,11 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { + name = 'MinecraftForge' + url = 'https://maven.minecraftforge.net/' + } + } +} + +rootProject.name = 'logtosplunk-forge' diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/LogToSplunkForge.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/LogToSplunkForge.java new file mode 100644 index 0000000..a87cd0c --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/LogToSplunkForge.java @@ -0,0 +1,94 @@ +package com.splunk.forge; + +import java.io.File; +import java.io.FileReader; +import java.util.Properties; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.splunk.forge.eventloggers.BlockEventLogger; +import com.splunk.forge.eventloggers.CombatEventLogger; +import com.splunk.forge.eventloggers.DeathEventLogger; +import com.splunk.forge.eventloggers.ItemEventLogger; +import com.splunk.forge.eventloggers.PerformanceSampler; +import com.splunk.forge.eventloggers.PlayerEventLogger; +import com.splunk.forge.eventloggers.PlayerStatsScraper; +import com.splunk.forge.eventloggers.ProgressionEventLogger; +import com.splunk.forge.eventloggers.ServerEventLogger; +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; + +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.Mod; + +/** + * Forge entrypoint for Minecraft 1.20.1. Mirrors the spigot/fabric core: loads + * {@code /config/splunk.properties}, wires up the shared event loggers, and registers + * them on the Forge event bus. Unlike Fabric, Forge exposes native block-place and chat + * events, so no mixin is required. + * + *

The extended logging categories (combat/item/progression/server/performance) and the + * KV-store player-stats scraper are opt-in via the same {@code splunk.craft.enable.*} toggles + * used by the spigot module, gated the same way. + */ +@Mod(LogToSplunkForge.MODID) +public class LogToSplunkForge { + public static final String MODID = "logtosplunk"; + public static final String SPLUNK_PROPERTIES = "/config/splunk.properties"; + + private static final Logger LOGGER = LogManager.getLogger("LogToSplunk"); + + public LogToSplunkForge() { + final Properties properties = loadProperties(); + + MinecraftForge.EVENT_BUS.register(new PlayerEventLogger(properties)); + MinecraftForge.EVENT_BUS.register(new BlockEventLogger(properties)); + MinecraftForge.EVENT_BUS.register(new DeathEventLogger(properties)); + + if (Boolean.parseBoolean(properties.getProperty(AbstractEventLogger.ENABLE_COMBAT, "false"))) { + MinecraftForge.EVENT_BUS.register(new CombatEventLogger(properties)); + } + if (Boolean.parseBoolean(properties.getProperty(AbstractEventLogger.ENABLE_ITEM, "false"))) { + MinecraftForge.EVENT_BUS.register(new ItemEventLogger(properties)); + } + if (Boolean.parseBoolean(properties.getProperty(AbstractEventLogger.ENABLE_PROGRESSION, "false"))) { + MinecraftForge.EVENT_BUS.register(new ProgressionEventLogger(properties)); + } + if (Boolean.parseBoolean(properties.getProperty(AbstractEventLogger.ENABLE_SERVER, "false"))) { + MinecraftForge.EVENT_BUS.register(new ServerEventLogger(properties)); + } + if (Boolean.parseBoolean(properties.getProperty(AbstractEventLogger.ENABLE_PERFORMANCE, "false"))) { + int interval = parseIntProperty( + properties, AbstractEventLogger.PERFORMANCE_INTERVAL_TICKS, 600); + PerformanceSampler sampler = new PerformanceSampler(properties); + sampler.start(interval); + MinecraftForge.EVENT_BUS.register(sampler); + } + if (Boolean.parseBoolean(properties.getProperty(AbstractEventLogger.ENABLE_PLAYERSTATS, "false"))) { + int interval = parseIntProperty( + properties, AbstractEventLogger.PLAYERSTATS_INTERVAL_TICKS, 6000); + new PlayerStatsScraper(properties).startAsync(interval); + } + + LOGGER.info("Splunk for Minecraft (Forge) initialized."); + } + + private static int parseIntProperty(Properties properties, String key, int defaultValue) { + try { + return Integer.parseInt(properties.getProperty(key, Integer.toString(defaultValue))); + } catch (NumberFormatException e) { + return defaultValue; + } + } + + private Properties loadProperties() { + final Properties properties = new Properties(); + final String path = System.getProperty("user.dir") + SPLUNK_PROPERTIES; + try (final FileReader reader = new FileReader(new File(path))) { + properties.load(reader); + } catch (final Exception e) { + LOGGER.warn("Unable to load properties for LogToSplunk at {}! Default values will be used.", path, e); + } + return properties; + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/BlockEventLogger.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/BlockEventLogger.java new file mode 100644 index 0000000..9160e00 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/BlockEventLogger.java @@ -0,0 +1,61 @@ +package com.splunk.forge.eventloggers; + +import java.util.Properties; + +import com.splunk.sharedmc.Point3dLong; +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableBlockEvent; +import com.splunk.sharedmc.loggable_events.LoggableBlockEvent.BlockEventAction; + +import net.minecraft.core.BlockPos; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraftforge.event.level.BlockEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.registries.ForgeRegistries; + +/** + * Logs block break/place events via Forge's native {@code BlockEvent.BreakEvent} and + * {@code BlockEvent.EntityPlaceEvent}. + */ +public class BlockEventLogger extends AbstractEventLogger { + + public BlockEventLogger(Properties props) { + super(props); + } + + @SubscribeEvent + public void onBreak(BlockEvent.BreakEvent event) { + final Player player = event.getPlayer(); + log(levelOf(event.getLevel(), player), player, event.getPos(), event.getState(), BlockEventAction.BREAK); + } + + @SubscribeEvent + public void onPlace(BlockEvent.EntityPlaceEvent event) { + final Player player = event.getEntity() instanceof Player p ? p : null; + log(levelOf(event.getLevel(), player), player, event.getPos(), event.getPlacedBlock(), BlockEventAction.PLACE); + } + + private static Level levelOf(LevelAccessor accessor, Player player) { + if (accessor instanceof Level level) { + return level; + } + return player != null ? player.level() : null; + } + + private void log(Level level, Player player, BlockPos pos, BlockState state, BlockEventAction action) { + if (level == null || level.isClientSide()) { + return; + } + final long worldTime = level.getGameTime(); + final String worldName = level.dimension().location().toString(); + final Point3dLong loc = new Point3dLong(pos.getX(), pos.getY(), pos.getZ()); + final ResourceLocation id = ForgeRegistries.BLOCKS.getKey(state.getBlock()); + final String blockName = id != null ? id.toString() : "unknown"; + final String playerName = player != null ? player.getName().getString() : null; + logAndSend(new LoggableBlockEvent(action, worldTime, worldName, loc, blockName, playerName)); + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/CombatEventLogger.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/CombatEventLogger.java new file mode 100644 index 0000000..8c2ad99 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/CombatEventLogger.java @@ -0,0 +1,129 @@ +package com.splunk.forge.eventloggers; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import com.splunk.sharedmc.Point3dLong; +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableCombatEvent; +import com.splunk.sharedmc.loggable_events.LoggableCombatEvent.CombatAction; +import com.splunk.sharedmc.util.EventThrottle; + +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.Level; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.entity.living.LivingDamageEvent; +import net.minecraftforge.event.entity.living.LivingHealEvent; +import net.minecraftforge.event.entity.player.PlayerEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; + +/** + * Logs combat and survival events. High-frequency events (damage, hunger) are throttled + * per-player. Mirrors the spigot module's {@code CombatEventLogger}. + * + *

Forge has no hunger-change event (unlike Bukkit's {@code FoodLevelChangeEvent}), so hunger + * is polled every {@link #FOOD_SAMPLE_INTERVAL_TICKS} ticks and reported only when a player's + * food level actually changed since the last sample. + * + *

Note: there is intentionally no death/kill handler here, matching the spigot module — + * kill events are handled by {@code DeathEventLogger} to avoid double-logging. + */ +public class CombatEventLogger extends AbstractEventLogger { + + private static final long THROTTLE_MS = 1000L; + private static final int FOOD_SAMPLE_INTERVAL_TICKS = 20; + + private final EventThrottle throttle = new EventThrottle(THROTTLE_MS); + private final Map lastKnownFoodLevel = new HashMap<>(); + private int tickCounter = 0; + + public CombatEventLogger(Properties props) { + super(props); + } + + /** Throttled per-victim: damage events can fire many times per second. */ + @SubscribeEvent + public void onDamage(LivingDamageEvent event) { + LivingEntity entity = event.getEntity(); + if (!(entity instanceof ServerPlayer)) { + return; + } + ServerPlayer victim = (ServerPlayer) entity; + if (!throttle.allow("dmg:" + victim.getName().getString())) { + return; + } + Entity damager = event.getSource().getEntity(); + LoggableCombatEvent loggable = base(CombatAction.DAMAGE, victim); + loggable.setVictim(victim.getName().getString()) + .setSource(damager != null ? damager.getType().toString() : event.getSource().getMsgId()) + .setAmount(event.getAmount()) + .setCause(event.getSource().getMsgId()) + .setHealthRemaining(victim.getHealth()); + logAndSend(loggable); + } + + /** Throttled per-player: regen-based healing (e.g. saturation) can fire frequently. */ + @SubscribeEvent + public void onHeal(LivingHealEvent event) { + LivingEntity entity = event.getEntity(); + if (!(entity instanceof ServerPlayer)) { + return; + } + ServerPlayer player = (ServerPlayer) entity; + if (!throttle.allow("heal:" + player.getName().getString())) { + return; + } + LoggableCombatEvent loggable = base(CombatAction.HEAL, player); + loggable.setVictim(player.getName().getString()) + .setAmount(event.getAmount()) + .setHealthRemaining(player.getHealth()); + logAndSend(loggable); + } + + /** Not throttled: respawn is a rare, deliberate-trigger event for a given player. */ + @SubscribeEvent + public void onRespawn(PlayerEvent.PlayerRespawnEvent event) { + if (!(event.getEntity() instanceof ServerPlayer)) { + return; + } + ServerPlayer player = (ServerPlayer) event.getEntity(); + lastKnownFoodLevel.remove(player.getUUID()); + LoggableCombatEvent loggable = base(CombatAction.RESPAWN, player); + loggable.setVictim(player.getName().getString()); + logAndSend(loggable); + } + + /** Polls food level; Forge has no hunger-change event to subscribe to directly. */ + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent event) { + if (event.phase != TickEvent.Phase.END) { + return; + } + if (++tickCounter % FOOD_SAMPLE_INTERVAL_TICKS != 0) { + return; + } + for (ServerPlayer player : event.getServer().getPlayerList().getPlayers()) { + int foodLevel = player.getFoodData().getFoodLevel(); + Integer previous = lastKnownFoodLevel.put(player.getUUID(), foodLevel); + if (previous != null && previous == foodLevel) { + continue; + } + if (!throttle.allow("food:" + player.getName().getString())) { + continue; + } + LoggableCombatEvent loggable = base(CombatAction.HUNGER, player); + loggable.setVictim(player.getName().getString()).setFoodLevel(foodLevel); + logAndSend(loggable); + } + } + + private LoggableCombatEvent base(CombatAction action, ServerPlayer player) { + Level level = player.level(); + Point3dLong loc = new Point3dLong(player.getX(), player.getY(), player.getZ()); + return new LoggableCombatEvent(action, level.getGameTime(), level.dimension().location().toString(), loc); + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/DeathEventLogger.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/DeathEventLogger.java new file mode 100644 index 0000000..3066e94 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/DeathEventLogger.java @@ -0,0 +1,49 @@ +package com.splunk.forge.eventloggers; + +import java.util.Properties; + +import com.splunk.sharedmc.Point3dLong; +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableDeathEvent; +import com.splunk.sharedmc.loggable_events.LoggableDeathEvent.DeathEventAction; + +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.Level; +import net.minecraftforge.event.entity.living.LivingDeathEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; + +/** + * Logs entity deaths (players and mobs) via Forge's native {@code LivingDeathEvent}. + */ +public class DeathEventLogger extends AbstractEventLogger { + + public DeathEventLogger(Properties props) { + super(props); + } + + @SubscribeEvent + public void onDeath(LivingDeathEvent event) { + final LivingEntity entity = event.getEntity(); + final Level level = entity.level(); + if (level.isClientSide()) { + return; + } + final long worldTime = level.getGameTime(); + final String worldName = level.dimension().location().toString(); + final Point3dLong loc = new Point3dLong(entity.getX(), entity.getY(), entity.getZ()); + + final boolean isPlayer = entity instanceof ServerPlayer; + final DeathEventAction action = isPlayer ? DeathEventAction.PLAYER_DIED : DeathEventAction.MOB_DIED; + + final String victim = entity.getName().getString(); + final DamageSource source = event.getSource(); + final Entity attacker = source.getEntity(); + final String killer = attacker != null ? attacker.getName().getString() : null; + final String damageSource = source.getMsgId(); + + logAndSend(new LoggableDeathEvent(action, worldTime, worldName, loc, killer, victim, damageSource)); + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ItemEventLogger.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ItemEventLogger.java new file mode 100644 index 0000000..6a919ae --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ItemEventLogger.java @@ -0,0 +1,61 @@ +package com.splunk.forge.eventloggers; + +import java.util.Properties; + +import com.splunk.sharedmc.Point3dLong; +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableItemEvent; +import com.splunk.sharedmc.loggable_events.LoggableItemEvent.ItemAction; +import com.splunk.sharedmc.util.EventThrottle; + +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraftforge.event.entity.item.ItemTossEvent; +import net.minecraftforge.event.entity.player.EntityItemPickupEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; + +/** + * Logs item pickup and drop events. Pickup is throttled (it can fire rapidly, e.g. when + * picking up XP orbs or arrows); drop is not throttled since it is a deliberate, low + * frequency player action. Mirrors the spigot module's {@code ItemEventLogger}. + */ +public class ItemEventLogger extends AbstractEventLogger { + + private final EventThrottle throttle = new EventThrottle(1000L); + + public ItemEventLogger(Properties props) { + super(props); + } + + @SubscribeEvent + public void onPickup(EntityItemPickupEvent event) { + Player player = event.getEntity(); + if (!throttle.allow("pickup:" + player.getName().getString())) { + return; + } + ItemStack stack = event.getItem().getItem(); + Level level = player.level(); + Point3dLong loc = new Point3dLong(player.getX(), player.getY(), player.getZ()); + LoggableItemEvent loggable = new LoggableItemEvent( + ItemAction.PICKUP, level.getGameTime(), level.dimension().location().toString(), loc); + loggable.setPlayerName(player.getName().getString()) + .setItem(stack.getItem().toString()) + .setQuantity(stack.getCount()); + logAndSend(loggable); + } + + @SubscribeEvent + public void onDrop(ItemTossEvent event) { + Player player = event.getPlayer(); + ItemStack stack = event.getEntity().getItem(); + Level level = player.level(); + Point3dLong loc = new Point3dLong(player.getX(), player.getY(), player.getZ()); + LoggableItemEvent loggable = new LoggableItemEvent( + ItemAction.DROP, level.getGameTime(), level.dimension().location().toString(), loc); + loggable.setPlayerName(player.getName().getString()) + .setItem(stack.getItem().toString()) + .setQuantity(stack.getCount()); + logAndSend(loggable); + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PerformanceSampler.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PerformanceSampler.java new file mode 100644 index 0000000..ca9656b --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PerformanceSampler.java @@ -0,0 +1,39 @@ +package com.splunk.forge.eventloggers; + +import java.util.Properties; + +import com.splunk.forge.scheduling.ScheduledMetricLogger; +import com.splunk.sharedmc.loggable_events.LoggablePerformanceEvent; + +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.server.ServerLifecycleHooks; + +/** + * Periodically samples server performance (online players, loaded chunks). Mirrors the + * spigot module's {@code PerformanceSampler}; TPS/MSPT are omitted (see that class's javadoc + * for why they're Bukkit/Paper-only there — Forge has no equivalent public API either, without + * reaching into internal tick-time tracking not exposed by {@code MinecraftServer}). + */ +public class PerformanceSampler extends ScheduledMetricLogger { + + public PerformanceSampler(Properties props) { + super(props); + } + + @Override + protected void sample() { + MinecraftServer server = ServerLifecycleHooks.getCurrentServer(); + if (server == null) { + return; + } + LoggablePerformanceEvent e = new LoggablePerformanceEvent(0L); + e.setOnlinePlayers(server.getPlayerCount()); + int loaded = 0; + for (ServerLevel level : server.getAllLevels()) { + loaded += level.getChunkSource().getLoadedChunksCount(); + } + e.setLoadedChunks(loaded); + logAndSend(e); + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PlayerEventLogger.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PlayerEventLogger.java new file mode 100644 index 0000000..d2f0225 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PlayerEventLogger.java @@ -0,0 +1,107 @@ +package com.splunk.forge.eventloggers; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import com.splunk.sharedmc.Point3dLong; +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggablePlayerEvent; +import com.splunk.sharedmc.loggable_events.LoggablePlayerEvent.PlayerEventAction; + +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.Level; +import net.minecraftforge.event.ServerChatEvent; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.entity.player.PlayerEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.server.ServerLifecycleHooks; + +/** + * Logs player connect/disconnect/chat/move events. Forge has no per-move event, so movement + * is derived by polling player positions every {@link #MOVE_SAMPLE_INTERVAL_TICKS} ticks and + * emitting only when a player has moved more than {@link #GRANULARITY} blocks. + */ +public class PlayerEventLogger extends AbstractEventLogger { + public static final double GRANULARITY = 1.5; + private static final int MOVE_SAMPLE_INTERVAL_TICKS = 10; + + private int tickCounter = 0; + private final Map lastKnownCoordinates = new HashMap<>(); + + public PlayerEventLogger(Properties props) { + super(props); + } + + @SubscribeEvent + public void onLogin(PlayerEvent.PlayerLoggedInEvent event) { + if (!(event.getEntity() instanceof ServerPlayer player)) { + return; + } + final LoggablePlayerEvent loggable = base(player, PlayerEventAction.PLAYER_CONNECT); + loggable.setPlayerUuid(player.getStringUUID()); + logAndSend(loggable); + } + + @SubscribeEvent + public void onLogout(PlayerEvent.PlayerLoggedOutEvent event) { + if (!(event.getEntity() instanceof ServerPlayer player)) { + return; + } + lastKnownCoordinates.remove(player.getUUID()); + logAndSend(base(player, PlayerEventAction.PLAYER_DISCONNECT)); + } + + @SubscribeEvent + public void onChat(ServerChatEvent event) { + final ServerPlayer player = event.getPlayer(); + final LoggablePlayerEvent loggable = base(player, PlayerEventAction.CHAT); + loggable.setMessage(event.getMessage().getString()); + logAndSend(loggable); + } + + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent event) { + if (event.phase != TickEvent.Phase.END) { + return; + } + if (++tickCounter % MOVE_SAMPLE_INTERVAL_TICKS != 0) { + return; + } + final MinecraftServer server = ServerLifecycleHooks.getCurrentServer(); + if (server == null) { + return; + } + for (final ServerPlayer player : server.getPlayerList().getPlayers()) { + final Point3dLong current = new Point3dLong(player.getX(), player.getY(), player.getZ()); + final Point3dLong previous = lastKnownCoordinates.get(player.getUUID()); + if (previous != null && distance(previous, current) < GRANULARITY) { + continue; + } + final LoggablePlayerEvent loggable = base(player, PlayerEventAction.LOCATION); + loggable.setFrom(previous); + loggable.setTo(current); + lastKnownCoordinates.put(player.getUUID(), current); + logAndSend(loggable); + } + } + + private LoggablePlayerEvent base(ServerPlayer player, PlayerEventAction action) { + final Level level = player.level(); + final long worldTime = level.getGameTime(); + final String worldName = level.dimension().location().toString(); + final Point3dLong loc = new Point3dLong(player.getX(), player.getY(), player.getZ()); + final LoggablePlayerEvent loggable = new LoggablePlayerEvent(action, worldTime, worldName, loc); + loggable.setPlayerName(player.getName().getString()); + return loggable; + } + + private static double distance(Point3dLong a, Point3dLong b) { + final double dx = a.xCoord - b.xCoord; + final double dy = a.yCoord - b.yCoord; + final double dz = a.zCoord - b.zCoord; + return Math.sqrt(dx * dx + dy * dy + dz * dz); + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PlayerStatsScraper.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PlayerStatsScraper.java new file mode 100644 index 0000000..a8d9d40 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/PlayerStatsScraper.java @@ -0,0 +1,247 @@ +package com.splunk.forge.eventloggers; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import com.splunk.forge.scheduling.ScheduledMetricLogger; +import com.splunk.sharedmc.KvStoreConnection; +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; + +/** + * Periodically scrapes the per-player snapshot files Minecraft writes to disk + * ({@code /stats/.json} and {@code /advancements/.json}), flattens + * them into one document per player, and upserts those documents into a Splunk KV-store + * collection via {@link KvStoreConnection}. + * + *

Identical to the spigot module's {@code PlayerStatsScraper} (this class never touched the + * Bukkit API to begin with — only file I/O, gson, and the shared KV-store client), copied here + * because Forge cannot depend on the spigot module's Bukkit-based scheduler. + * + *

Runs off the main server thread (see {@link ScheduledMetricLogger#startAsync}); it only + * reads files and does HTTP, never touches live world state. To avoid re-uploading unchanged + * players every cycle, the last-seen file modification time per UUID is cached and only changed + * files are pushed. + */ +public class PlayerStatsScraper extends ScheduledMetricLogger { + + /** Default world directory name; overridable via {@link AbstractEventLogger#WORLD_PATH}. */ + private static final String DEFAULT_WORLD = "world"; + + /** Custom-stat keys we surface as first-class columns (the rest are kept as category totals). */ + private static final String[] CUSTOM_STAT_COLUMNS = { + "minecraft:deaths", + "minecraft:mob_kills", + "minecraft:player_kills", + "minecraft:play_time", + "minecraft:total_world_time", + "minecraft:walk_one_cm", + "minecraft:sprint_one_cm", + "minecraft:jump", + "minecraft:damage_dealt", + "minecraft:damage_taken", + "minecraft:time_since_rest" + }; + + private final KvStoreConnection kv; + private final File statsDir; + private final File advancementsDir; + private final File usercacheFile; + + /** UUID -> last stats-file lastModified() we successfully uploaded, to push only deltas. */ + private final Map uploadedMtimes = new HashMap<>(); + + public PlayerStatsScraper(Properties props) { + super(props); + + String host = props.getProperty(KVSTORE_HOST, "127.0.0.1"); + int port = intProp(KVSTORE_PORT, 8089); + String app = props.getProperty(KVSTORE_APP, "minecraft-app"); + String collection = props.getProperty(KVSTORE_COLLECTION, "minecraft_player_stats"); + String token = props.getProperty(KVSTORE_TOKEN); + if (token == null || token.trim().isEmpty()) { + throw new IllegalArgumentException("Property `" + KVSTORE_TOKEN + "` must be set (a splunkd " + + "bearer token) to write player stats to the KV store."); + } + this.kv = new KvStoreConnection(host, port, app, collection, token); + + String serverDir = System.getProperty("user.dir"); + String world = props.getProperty(WORLD_PATH, DEFAULT_WORLD); + File worldDir = new File(world); + if (!worldDir.isAbsolute()) { + worldDir = new File(serverDir, world); + } + this.statsDir = new File(worldDir, "stats"); + this.advancementsDir = new File(worldDir, "advancements"); + this.usercacheFile = new File(serverDir, "usercache.json"); + } + + @Override + protected void sample() { + File[] statFiles = statsDir.listFiles((dir, name) -> name.endsWith(".json")); + if (statFiles == null || statFiles.length == 0) { + logger.debug("No player stats files found at {}", statsDir.getAbsolutePath()); + return; + } + + Map uuidToName = loadUsercache(); + + JsonArray batch = new JsonArray(); + for (File statFile : statFiles) { + String uuid = stripExtension(statFile.getName()); + long mtime = statFile.lastModified(); + + File advFile = new File(advancementsDir, uuid + ".json"); + long advMtime = advFile.exists() ? advFile.lastModified() : 0L; + long combinedMtime = Math.max(mtime, advMtime); + + Long lastSeen = uploadedMtimes.get(uuid); + if (lastSeen != null && lastSeen == combinedMtime) { + continue; // unchanged since last successful upload + } + + JsonObject doc = buildDocument(uuid, uuidToName.get(uuid), statFile, advFile, combinedMtime); + if (doc != null) { + batch.add(doc); + } + } + + if (batch.size() == 0) { + return; + } + + if (kv.batchSave(batch.toString())) { + // Only mark as uploaded once splunkd accepted the batch. + for (JsonElement el : batch) { + JsonObject doc = el.getAsJsonObject(); + uploadedMtimes.put(doc.get("uuid").getAsString(), doc.get("last_modified").getAsLong()); + } + logger.info("Upserted {} player-stats document(s) to KV store.", batch.size()); + } else { + logger.warn("KV-store upsert failed; will retry {} player(s) next cycle.", batch.size()); + } + } + + private JsonObject buildDocument(String uuid, String name, File statFile, File advFile, long combinedMtime) { + try (Reader r = new FileReader(statFile)) { + JsonObject root = JsonParser.parseReader(r).getAsJsonObject(); + + JsonObject doc = new JsonObject(); + doc.addProperty("_key", uuid); // makes batch_save an idempotent upsert + doc.addProperty("uuid", uuid); + if (name != null) { + doc.addProperty("name", name); + } + doc.addProperty("last_modified", combinedMtime); + if (root.has("DataVersion")) { + doc.addProperty("data_version", root.get("DataVersion").getAsInt()); + } + + JsonObject stats = root.has("stats") ? root.getAsJsonObject("stats") : new JsonObject(); + + // Per-category totals (sum of all entries within minecraft:mined, :killed, etc.). + for (Map.Entry cat : stats.entrySet()) { + String column = "stat_" + simpleKey(cat.getKey()) + "_total"; + doc.addProperty(column, sumValues(cat.getValue().getAsJsonObject())); + } + + // Selected custom stats surfaced as their own columns. + if (stats.has("minecraft:custom")) { + JsonObject custom = stats.getAsJsonObject("minecraft:custom"); + for (String key : CUSTOM_STAT_COLUMNS) { + if (custom.has(key)) { + doc.addProperty(simpleKey(key), custom.get(key).getAsLong()); + } + } + } + + addAdvancementCounts(doc, advFile); + return doc; + } catch (IOException | RuntimeException e) { + logger.warn("Failed to parse stats for player {} ({})", uuid, statFile.getName(), e); + return null; + } + } + + /** + * Counts completed advancements, excluding recipe unlocks ({@code minecraft:recipes/...}) + * which are noise. Adds {@code advancements_completed} and {@code advancements_total}. + */ + private void addAdvancementCounts(JsonObject doc, File advFile) { + if (!advFile.exists()) { + return; + } + try (Reader r = new FileReader(advFile)) { + JsonObject root = JsonParser.parseReader(r).getAsJsonObject(); + int completed = 0; + int total = 0; + for (Map.Entry e : root.entrySet()) { + String id = e.getKey(); + if ("DataVersion".equals(id) || id.startsWith("minecraft:recipes/")) { + continue; + } + if (!e.getValue().isJsonObject()) { + continue; + } + total++; + JsonObject adv = e.getValue().getAsJsonObject(); + if (adv.has("done") && adv.get("done").getAsBoolean()) { + completed++; + } + } + doc.addProperty("advancements_completed", completed); + doc.addProperty("advancements_total", total); + } catch (IOException | RuntimeException e) { + logger.debug("Failed to parse advancements file {}", advFile.getName(), e); + } + } + + /** Sums every numeric value in a stat category object (e.g. all blocks under minecraft:mined). */ + private static long sumValues(JsonObject obj) { + long sum = 0L; + for (Map.Entry e : obj.entrySet()) { + sum += e.getValue().getAsLong(); + } + return sum; + } + + /** Builds a flat UUID -> name map from the server's usercache.json (best-effort). */ + private Map loadUsercache() { + Map map = new HashMap<>(); + if (!usercacheFile.exists()) { + return map; + } + try (Reader r = new FileReader(usercacheFile)) { + JsonArray arr = JsonParser.parseReader(r).getAsJsonArray(); + for (JsonElement el : arr) { + JsonObject o = el.getAsJsonObject(); + if (o.has("uuid") && o.has("name")) { + map.put(o.get("uuid").getAsString(), o.get("name").getAsString()); + } + } + } catch (IOException | RuntimeException e) { + logger.debug("Could not read usercache.json for player names", e); + } + return map; + } + + /** "minecraft:mined" -> "mined"; "minecraft:play_time" -> "play_time". */ + private static String simpleKey(String namespacedKey) { + int idx = namespacedKey.indexOf(':'); + return idx >= 0 ? namespacedKey.substring(idx + 1) : namespacedKey; + } + + private static String stripExtension(String fileName) { + int idx = fileName.lastIndexOf('.'); + return idx >= 0 ? fileName.substring(0, idx) : fileName; + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ProgressionEventLogger.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ProgressionEventLogger.java new file mode 100644 index 0000000..7f81e69 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ProgressionEventLogger.java @@ -0,0 +1,84 @@ +package com.splunk.forge.eventloggers; + +import java.util.Properties; + +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableProgressionEvent; +import com.splunk.sharedmc.loggable_events.LoggableProgressionEvent.ProgressionAction; + +import com.mojang.brigadier.context.CommandContextBuilder; + +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.world.entity.player.Player; +import net.minecraftforge.event.CommandEvent; +import net.minecraftforge.event.entity.player.ItemFishedEvent; +import net.minecraftforge.event.entity.player.PlayerEvent; +import net.minecraftforge.event.entity.player.PlayerXpEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; + +/** + * Logs progression and activity: level, craft, fish, command. Mirrors the spigot module's + * {@code ProgressionEventLogger}, minus two categories Forge 1.20.1 has no event for: + * + *

+ */ +public class ProgressionEventLogger extends AbstractEventLogger { + + public ProgressionEventLogger(Properties props) { + super(props); + } + + private LoggableProgressionEvent base(ProgressionAction action, Player player) { + LoggableProgressionEvent e = new LoggableProgressionEvent( + action, player.level().getGameTime(), player.level().dimension().location().toString()); + e.setPlayerName(player.getName().getString()); + return e; + } + + @SubscribeEvent + public void onLevelChange(PlayerXpEvent.LevelChange event) { + Player player = event.getEntity(); + LoggableProgressionEvent e = base(ProgressionAction.LEVEL_CHANGE, player); + e.setNewLevel(player.experienceLevel + event.getLevels()); + logAndSend(e); + } + + @SubscribeEvent + public void onCraft(PlayerEvent.ItemCraftedEvent event) { + Player player = event.getEntity(); + LoggableProgressionEvent e = base(ProgressionAction.CRAFT, player); + e.setDetail(event.getCrafting().getItem().toString()); + logAndSend(e); + } + + @SubscribeEvent + public void onFish(ItemFishedEvent event) { + Player player = event.getEntity(); + LoggableProgressionEvent e = base(ProgressionAction.FISH, player); + e.setDetail(event.getHookEntity().getHookedIn() != null + ? "entity" + : event.getDrops().size() + " item(s)"); + logAndSend(e); + } + + @SubscribeEvent + public void onCommand(CommandEvent event) { + CommandContextBuilder context = event.getParseResults().getContext(); + CommandSourceStack source = context.getSource(); + if (!(source.getEntity() instanceof Player)) { + return; + } + Player player = (Player) source.getEntity(); + LoggableProgressionEvent e = base(ProgressionAction.COMMAND, player); + e.setDetail(event.getParseResults().getReader().getString()); + logAndSend(e); + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ServerEventLogger.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ServerEventLogger.java new file mode 100644 index 0000000..5b5486a --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/eventloggers/ServerEventLogger.java @@ -0,0 +1,64 @@ +package com.splunk.forge.eventloggers; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableServerEvent; +import com.splunk.sharedmc.loggable_events.LoggableServerEvent.ServerAction; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.server.ServerStartedEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; + +/** + * Logs server lifecycle and world-state events. Mirrors the spigot module's + * {@code ServerEventLogger}. + * + *

Forge has no dedicated weather-change event (unlike Bukkit's {@code WeatherChangeEvent}), + * so each loaded level's raining state is polled every {@link #WEATHER_SAMPLE_INTERVAL_TICKS} + * ticks and reported only when it actually changed since the last sample. + */ +public class ServerEventLogger extends AbstractEventLogger { + + private static final int WEATHER_SAMPLE_INTERVAL_TICKS = 200; + + private final Map lastKnownWeather = new HashMap<>(); + private int tickCounter = 0; + + public ServerEventLogger(Properties props) { + super(props); + } + + @SubscribeEvent + public void onServerStarted(ServerStartedEvent event) { + LoggableServerEvent e = new LoggableServerEvent(ServerAction.SERVER_START, 0L, null); + e.setMotd(event.getServer().getMotd()); + logAndSend(e); + } + + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent event) { + if (event.phase != TickEvent.Phase.END) { + return; + } + if (++tickCounter % WEATHER_SAMPLE_INTERVAL_TICKS != 0) { + return; + } + for (ServerLevel level : event.getServer().getAllLevels()) { + ResourceLocation dimension = level.dimension().location(); + boolean raining = level.isRaining(); + Boolean previous = lastKnownWeather.put(dimension, raining); + if (previous != null && previous == raining) { + continue; + } + LoggableServerEvent e = new LoggableServerEvent( + ServerAction.WEATHER_CHANGE, level.getGameTime(), dimension.toString()); + e.setWeather(raining ? "storm" : "clear"); + logAndSend(e); + } + } +} diff --git a/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/scheduling/ScheduledMetricLogger.java b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/scheduling/ScheduledMetricLogger.java new file mode 100644 index 0000000..4315838 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/java/com/splunk/forge/scheduling/ScheduledMetricLogger.java @@ -0,0 +1,79 @@ +package com.splunk.forge.scheduling; + +import java.util.Properties; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; + +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; + +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; + +/** + * Base for loggers driven by a timer rather than a game event. Mirrors the spigot module's + * {@code ScheduledMetricLogger}, adapted to Forge: {@link #start(long)} samples on the main + * server thread via the Forge tick event bus (subclass MUST register {@code this} on + * {@code MinecraftForge.EVENT_BUS} for the tick handler to fire); {@link #startAsync(long)} + * samples off-thread on a dedicated scheduled executor, for subclasses that do blocking I/O. + */ +public abstract class ScheduledMetricLogger extends AbstractEventLogger { + + /** Assumes a steady 20 ticks/second, matching vanilla server tick rate. */ + private static final long MS_PER_TICK = 50L; + + private long intervalTicks; + private int tickCounter = 0; + + public ScheduledMetricLogger(Properties props) { + super(props); + } + + /** Called on each scheduled interval. Build and send the metric event(s) here. */ + protected abstract void sample(); + + /** + * Arms the tick-driven sampler. The caller must also register {@code this} instance on + * {@code MinecraftForge.EVENT_BUS} so {@link #onServerTick(TickEvent.ServerTickEvent)} fires. + */ + public void start(long intervalTicks) { + this.intervalTicks = intervalTicks; + } + + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent event) { + if (intervalTicks <= 0 || event.phase != TickEvent.Phase.END) { + return; + } + if (++tickCounter % intervalTicks != 0) { + return; + } + runSampleSafely(); + } + + /** + * Like {@link #start(long)} but runs {@link #sample()} on a dedicated background thread, so + * blocking I/O (file reads, HTTP) never stalls a server tick. Subclasses scheduled this way + * MUST NOT touch Minecraft world/entity state from {@link #sample()} (only safe on the main + * thread). + */ + public void startAsync(long intervalTicks) { + long periodMs = Math.max(MS_PER_TICK, intervalTicks * MS_PER_TICK); + ThreadFactory daemonFactory = r -> { + Thread t = new Thread(r, "logtosplunk-scheduled-metric"); + t.setDaemon(true); + return t; + }; + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(daemonFactory); + executor.scheduleAtFixedRate(this::runSampleSafely, periodMs, periodMs, TimeUnit.MILLISECONDS); + } + + private void runSampleSafely() { + try { + sample(); + } catch (Exception e) { + logger.warn("Scheduled metric sample failed", e); + } + } +} diff --git a/forge-1.20.1-47.4.20/src/main/resources/META-INF/mods.toml b/forge-1.20.1-47.4.20/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..90956f0 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/resources/META-INF/mods.toml @@ -0,0 +1,27 @@ +modLoader="javafml" +loaderVersion="[47,)" +license="Apache-2.0" +issueTrackerURL="" + +[[mods]] +modId="logtosplunk" +version="${file.jarVersion}" +displayName="Splunk for Minecraft (Forge)" +authors="Splunk" +description=''' +Logs Minecraft server events (player, block, death) to Splunk via the HTTP Event Collector. +''' + +[[dependencies.logtosplunk]] + modId="forge" + mandatory=true + versionRange="[47,)" + ordering="NONE" + side="SERVER" + +[[dependencies.logtosplunk]] + modId="minecraft" + mandatory=true + versionRange="[1.20.1,1.21)" + ordering="NONE" + side="SERVER" diff --git a/forge-1.20.1-47.4.20/src/main/resources/pack.mcmeta b/forge-1.20.1-47.4.20/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..52fe4de --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "logtosplunk resources", + "pack_format": 15 + } +} diff --git a/forge-1.20.1-47.4.20/src/main/resources/splunk.properties.sample b/forge-1.20.1-47.4.20/src/main/resources/splunk.properties.sample new file mode 100644 index 0000000..019b306 --- /dev/null +++ b/forge-1.20.1-47.4.20/src/main/resources/splunk.properties.sample @@ -0,0 +1,42 @@ +splunk.craft.connection.host=127.0.0.1 +splunk.craft.connection.port=8088 +splunk.craft.token=CHANGEME-1234-5678-1234-123456789012 +splunk.craft.enable.consolelog=true + +# --- Extended logging categories (all opt-in; default off) --- +# Combat & survival: damage, kills, healing, hunger, respawn (throttled per player) +splunk.craft.enable.combat=false +# Item economy: pickup, drop +splunk.craft.enable.item=false +# Progression: xp, level, enchant, craft, fish, command +splunk.craft.enable.progression=false +# Server lifecycle: start, weather change +splunk.craft.enable.server=false +# Performance sampler: online players, loaded chunks (TPS/MSPT require Paper API) +splunk.craft.enable.performance=false +# How often (in server ticks, 20 ticks = 1s) to sample performance +splunk.craft.performance.interval_ticks=600 +# Session detail: log client IP on connect (PII -- opt in deliberately) +splunk.craft.enable.session_ip=false +# Session detail: teleport, gamemode change, bed enter, world change +splunk.craft.enable.session_detail=false + +# --- Player stats scraper -> KV store (snapshot data, NOT sent via HEC) --- +# Reads /players/stats/.json + advancements/.json and upserts one doc per +# player into a Splunk KV-store collection. Uses the splunkd MANAGEMENT REST endpoint, which +# is a different host/port and credential than HEC -- HEC cannot write a KV store. +splunk.craft.enable.playerstats=false +# How often (in server ticks, 20 ticks = 1s) to scrape; 6000 = ~5 min +splunk.craft.playerstats.interval_ticks=6000 +# splunkd management interface (NOT the HEC port). Default mgmt port is 8089, HTTPS. +splunk.craft.kvstore.host=127.0.0.1 +splunk.craft.kvstore.port=8089 +# App namespace (app DIRECTORY name under etc/apps) that owns the collection. The +# SplunkCraft app ships collections.conf + transforms.conf for minecraft_player_stats. +splunk.craft.kvstore.app=SplunkCraft +# KV-store collection name (must match collections.conf) +splunk.craft.kvstore.collection=minecraft_player_stats +# Splunk bearer/JWT token with write access (Settings -> Tokens). NOT the HEC token. +splunk.craft.kvstore.bearer_token=CHANGEME +# Optional: world directory name or absolute path (default: world) +#splunk.craft.world.path=world \ No newline at end of file diff --git a/logtosplunk-plugin/pom.xml b/logtosplunk-plugin/pom.xml index 33e5b52..3fef39d 100644 --- a/logtosplunk-plugin/pom.xml +++ b/logtosplunk-plugin/pom.xml @@ -8,108 +8,75 @@ 4.0.0 + logtosplunk-plugin - - - - mvnrepository-central - mvnrepository.com Central - https://repo1.maven.org/maven2/ - - - splunk-artifactory - Splunk Releases - https://splunk.jfrog.io/splunk/ext-releases-local - - - - - - org.apache.logging.log4j - log4j-api - 2.25.1 - - - org.apache.logging.log4j - log4j-core - 2.25.1 - - - com.splunk.logging - splunk-library-javalogging - 1.11.8 - - - com.splunk - shared-mc - ${project.version} - - - com.splunk - spigot - ${project.version} - - + pom + org.apache.maven.plugins - maven-shade-plugin - - - ${project.build.directory}/dependency-reduced-pom.xml - - - - 2.4.1 + maven-antrun-plugin + 3.1.0 + collect-dist package - shade + run + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - include-forge - - - com.splunk - logtosplunk-forge - ${project.version} - - - org.apache.logging.log4j - log4j-api - - - org.apache.logging.log4j - log4j-core - - - com.splunk - splunk-library-javalogging - 1.0.1 - - - com.splunk - shared-mc - ${project.version} - - - com.splunk - spigot - ${project.version} - - - - - diff --git a/logtosplunk-plugin/src/main/config/splunk.properties b/logtosplunk-plugin/src/main/config/splunk.properties index 181fca7..39b562b 100644 --- a/logtosplunk-plugin/src/main/config/splunk.properties +++ b/logtosplunk-plugin/src/main/config/splunk.properties @@ -1,4 +1,68 @@ +# ============================================================================= +# LogToSplunk plugin/mod configuration +# ============================================================================= +# How to use: copy this file to /config/splunk.properties (the plugin/mod reads +# it from `/config/splunk.properties` at startup -- NOT from inside the +# jar). Replace every CHANGEME value below, then restart the server. +# +# Two independent Splunk connections are configured here: +# 1. HTTP Event Collector (HEC) -- `splunk.craft.connection.*` / `splunk.craft.token`. +# All the per-event logging below (block/death/player/combat/item/etc.) is sent here, +# as JSON, sourcetype `minecraft:json`. The index it lands in is whatever index the HEC +# token itself is bound to on the Splunk side (Settings -> Data Inputs -> HTTP Event +# Collector) -- there is no `index=` key in this file. +# 2. KV-store REST endpoint (splunkd management port) -- `splunk.craft.kvstore.*`, used only +# by the player-stats scraper. Different host/port/credential than HEC; see the comment +# block above `splunk.craft.enable.playerstats` below for why. +# ============================================================================= + +# --- HTTP Event Collector (HEC) connection --- +# Splunk host that accepts HEC requests (the splunkd HEC listener, default port 8088, HTTP). splunk.craft.connection.host=127.0.0.1 +# HEC port. 8088 is the Splunk default; confirm against Settings -> Data Inputs -> HTTP Event +# Collector -> Global Settings if you've customized it. splunk.craft.connection.port=8088 +# HEC token (a UUID) from Settings -> Data Inputs -> HTTP Event Collector -> . +# This determines which index/sourcetype-defaults events land under -- NOT a KV-store credential. splunk.craft.token=CHANGEME-1234-5678-1234-123456789012 -splunk.craft.enable.consolelog=true \ No newline at end of file +# If true, every event sent to Splunk is also echoed to the server console/log file. +# Useful for debugging; safe to leave on, since it's just a duplicate of what already went to HEC. +splunk.craft.enable.consolelog=true + +# --- Extended logging categories (all opt-in; default off) --- +# Combat & survival: damage, kills, healing, hunger, respawn (throttled per player) +splunk.craft.enable.combat=false +# Item economy: pickup, drop +splunk.craft.enable.item=false +# Progression: xp, level, enchant, craft, fish, command +splunk.craft.enable.progression=false +# Server lifecycle: start, weather change +splunk.craft.enable.server=false +# Performance sampler: online players, loaded chunks (TPS/MSPT require Paper API) +splunk.craft.enable.performance=false +# How often (in server ticks, 20 ticks = 1s) to sample performance +splunk.craft.performance.interval_ticks=600 +# Session detail: log client IP on connect (PII -- opt in deliberately) +splunk.craft.enable.session_ip=false +# Session detail: teleport, gamemode change, bed enter, world change +splunk.craft.enable.session_detail=false + +# --- Player stats scraper -> KV store (snapshot data, NOT sent via HEC) --- +# Reads /players/stats/.json + advancements/.json and upserts one doc per +# player into a Splunk KV-store collection. Uses the splunkd MANAGEMENT REST endpoint, which +# is a different host/port and credential than HEC -- HEC cannot write a KV store. +splunk.craft.enable.playerstats=false +# How often (in server ticks, 20 ticks = 1s) to scrape; 6000 = ~5 min +splunk.craft.playerstats.interval_ticks=6000 +# splunkd management interface (NOT the HEC port). Default mgmt port is 8089, HTTPS. +splunk.craft.kvstore.host=127.0.0.1 +splunk.craft.kvstore.port=8089 +# App namespace (app DIRECTORY name under etc/apps) that owns the collection. The +# SplunkCraft app ships collections.conf + transforms.conf for minecraft_player_stats. +splunk.craft.kvstore.app=SplunkCraft +# KV-store collection name (must match collections.conf) +splunk.craft.kvstore.collection=minecraft_player_stats +# Splunk bearer/JWT token with write access (Settings -> Tokens). NOT the HEC token. +splunk.craft.kvstore.bearer_token=CHANGEME +# Optional: world directory name or absolute path (default: world) +#splunk.craft.world.path=world \ No newline at end of file diff --git a/owasp-suppressions.xml b/owasp-suppressions.xml new file mode 100644 index 0000000..34c7c49 --- /dev/null +++ b/owasp-suppressions.xml @@ -0,0 +1,55 @@ + + + + + + + CVE-2026-53914: affects all kotlin-stdlib versions, no fix available. kotlin-stdlib + is a transitive dep from okhttp3 via splunk-library-javalogging; we write no Kotlin code. + Pinned to 2.0.21 (latest); re-evaluate when a fixed kotlin-stdlib version is published. + ^pkg:maven/org\.jetbrains\.kotlin/kotlin\-stdlib.*@.*$ + CVE-2026-53914 + + + + + CVE-2020-29582: Kotlin scripting temp-dir exposure. We don't use Kotlin scripting; + kotlin-stdlib is a transitive dep from okhttp3/splunk-library-javalogging. + ^pkg:maven/org\.jetbrains\.kotlin/kotlin\-stdlib.*@.*$ + CVE-2020-29582 + + + + + + False positive: shared-mc JAR matched to Minecraft game CPE due to "minecraft" in + project path and "SNAPSHOT" in version. CVE-2023-33245 and CVE-2021-35054 are Minecraft + game vulnerabilities, unrelated to this library. + ^pkg:maven/com\.splunk/shared\-mc@.*$ + CVE-2023-33245 + + + False positive — same reason as CVE-2023-33245 above. + ^pkg:maven/com\.splunk/shared\-mc@.*$ + CVE-2021-35054 + + + diff --git a/pom.xml b/pom.xml index bd12947..fb65c0e 100644 --- a/pom.xml +++ b/pom.xml @@ -6,49 +6,116 @@ splunk.minecraft.app 1.0-SNAPSHOT - spigot shared-mc + spigot + paper forge + neoforge logtosplunk-plugin pom - + + + 21 + UTF-8 + + 1.21.1 + spigot + 1.21.1-R0.1 + + mvnrepository-central mvnrepository.com Central https://repo1.maven.org/maven2/ + + papermc + Paper Maven + https://repo.papermc.io/repository/maven-public/ + + + spigot-repo + Spigot Snapshots + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + + org.jetbrains.kotlin + kotlin-stdlib + 2.0.21 + + + org.jetbrains.kotlin + kotlin-stdlib-common + 2.0.21 + + + org.jetbrains.kotlin + kotlin-stdlib-jdk7 + 2.0.21 + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + 2.0.21 + + org.apache.logging.log4j log4j-api 2.25.1 + provided org.apache.logging.log4j log4j-core 2.25.1 + provided com.splunk.logging splunk-library-javalogging 1.11.8 + + com.google.code.gson + gson + 2.13.2 + + + com.google.guava + guava + 33.5.0-jre + + + org.apache.httpcomponents.core5 + httpcore5 + 5.3.6 + + + org.apache.httpcomponents.client5 + httpclient5 + 5.5.1 + junit junit - 4.8.2 + 4.13.2 test - - com.googlecode.json-simple - json-simple - 1.1 - @@ -56,10 +123,26 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 3.14.0 + + 21 + + + + org.owasp + dependency-check-maven + 12.1.0 - 1.8 - 1.8 + 7.0 + + true + + false + + ${maven.multiModuleProjectDirectory}/owasp-suppressions.xml + diff --git a/shared-mc/pom.xml b/shared-mc/pom.xml index 5e0ba66..8dec369 100644 --- a/shared-mc/pom.xml +++ b/shared-mc/pom.xml @@ -26,43 +26,30 @@ org.apache.logging.log4j log4j-api - 2.25.1 org.apache.logging.log4j log4j-core - 2.25.1 org.apache.httpcomponents.core5 httpcore5 - 5.3.6 org.apache.httpcomponents.client5 httpclient5 - 5.5.1 com.google.guava guava - 33.5.0-jre com.google.code.gson gson - 2.13.2 com.splunk.logging splunk-library-javalogging - 1.11.8 - - com.googlecode.json-simple - json-simple - 1.1 - - junit junit diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/KvStoreConnection.java b/shared-mc/src/main/java/com/splunk/sharedmc/KvStoreConnection.java new file mode 100644 index 0000000..fc2c8bb --- /dev/null +++ b/shared-mc/src/main/java/com/splunk/sharedmc/KvStoreConnection.java @@ -0,0 +1,117 @@ +package com.splunk.sharedmc; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import javax.net.ssl.SSLContext; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.ssl.SSLContextBuilder; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.io.HttpClientConnectionManager; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder; +import org.apache.hc.client5.http.ssl.TrustAllStrategy; + +/** + * Writes documents straight into a Splunk KV-store collection via the splunkd REST API + * ({@code .../storage/collections/data//batch_save}). + * + *

This is deliberately NOT a {@link SplunkConnection}/HEC path: the HTTP Event Collector + * can only write events into an index, never into a KV store. Populating a KV store + * requires the management REST endpoint, which uses a different host/port (splunkd mgmt, + * default 8089, HTTPS) and a different credential ({@code Authorization: Bearer }), + * not the HEC token. + * + *

batch_save upserts by each document's {@code _key}, so re-sending the same player UUID + * overwrites the previous snapshot rather than appending — which is exactly what we want for + * non-time-series snapshot data. + * + *

SSL note: splunkd's management port presents a self-signed certificate by default. To + * keep this usable in a lab/self-hosted Minecraft deployment, the client trusts all certs and + * skips hostname verification. For a hardened deployment, replace the trust strategy with a + * truststore containing the splunkd cert. + */ +public class KvStoreConnection { + + private static final String LOGGER_PREFIX = "KvStoreConnection - "; + private static final String BATCH_SAVE_URL = + "https://%s:%s/servicesNS/nobody/%s/storage/collections/data/%s/batch_save"; + + private final Logger logger; + private final String url; + private final String token; + + public KvStoreConnection(String host, int port, String app, String collection, String token) { + this.logger = LogManager.getLogger(LOGGER_PREFIX + host + ':' + port + '/' + collection); + this.token = token; + this.url = String.format(BATCH_SAVE_URL, host, port, app, collection); + } + + /** + * Upserts a batch of documents. The body must be a JSON array of objects, each of which + * should carry a {@code _key} to make the write idempotent. + * + * @param jsonArrayBody JSON array string, e.g. {@code [{"_key":"...","name":"..."}, ...]}. + * @return true if splunkd accepted the batch (2xx). + */ + public boolean batchSave(String jsonArrayBody) { + final CloseableHttpClient client = buildClient(); + if (client == null) { + return false; + } + try { + HttpPost post = new HttpPost(url); + post.setHeader("Authorization", "Bearer " + token); + post.setEntity(new StringEntity(jsonArrayBody, ContentType.APPLICATION_JSON)); + + try (CloseableHttpResponse response = client.execute(post)) { + int code = response.getCode(); + if (code > 199 && code < 300) { + return true; + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + response.getEntity().writeTo(out); + logger.error("KV-store batch_save failed (HTTP {}): {}", code, new String(out.toByteArray())); + return false; + } + } catch (final IOException e) { + logger.error("Unable to write to KV store!", e); + return false; + } finally { + try { + client.close(); + } catch (final IOException ignored) { + // closing best-effort + } + } + } + + private CloseableHttpClient buildClient() { + try { + SSLContext sslContext = SSLContextBuilder.create() + .loadTrustMaterial(null, TrustAllStrategy.INSTANCE) + .build(); + SSLConnectionSocketFactory sslFactory = SSLConnectionSocketFactoryBuilder.create() + .setSslContext(sslContext) + .setHostnameVerifier(NoopHostnameVerifier.INSTANCE) + .build(); + HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() + .setSSLSocketFactory(sslFactory) + .build(); + return HttpClients.custom().setConnectionManager(cm).build(); + } catch (final Exception e) { + logger.error("Unable to build TLS client for KV store connection", e); + return null; + } + } +} diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/SingleSplunkConnection.java b/shared-mc/src/main/java/com/splunk/sharedmc/SingleSplunkConnection.java index 0f4af0b..f1a7bd8 100644 --- a/shared-mc/src/main/java/com/splunk/sharedmc/SingleSplunkConnection.java +++ b/shared-mc/src/main/java/com/splunk/sharedmc/SingleSplunkConnection.java @@ -24,8 +24,6 @@ import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.core5.io.CloseMode; -import org.json.simple.JSONObject; - /** * Knows a single Splunk instance by its host:port and forwards data to it. */ @@ -84,6 +82,20 @@ public void run() { } } + /** + * Wraps a raw event message in the Splunk HTTP Event Collector JSON envelope: + * {@code {"event": ""}}. Built with gson (replaced the previous json-simple + * dependency). Package-private for testing. + * + * @param message The raw event message to wrap. + * @return The HEC envelope as a JSON string. + */ + static String buildHecEnvelope(String message) { + com.google.gson.JsonObject event = new com.google.gson.JsonObject(); + event.addProperty("event", message); + return event.toString(); + } + /** * Queues up a message to send to this Spunk connections' Splunk instance. * @@ -91,11 +103,7 @@ public void run() { */ @Override public void sendToSplunk(String message) { - JSONObject event = new JSONObject(); - //message = Calendar.getInstance().getTime().toString() + ' ' + message; - event.put("event", message); - - messagesToSend.append(event.toString()); + messagesToSend.append(buildHecEnvelope(message)); } private boolean sendData() { diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/event_loggers/AbstractEventLogger.java b/shared-mc/src/main/java/com/splunk/sharedmc/event_loggers/AbstractEventLogger.java index 1bcea5c..86212f8 100644 --- a/shared-mc/src/main/java/com/splunk/sharedmc/event_loggers/AbstractEventLogger.java +++ b/shared-mc/src/main/java/com/splunk/sharedmc/event_loggers/AbstractEventLogger.java @@ -19,6 +19,35 @@ public class AbstractEventLogger { public static final String SPLUNK_PORT = "splunk.craft.connection.port"; public static final String SPLUNK_TOKEN = "splunk.craft.token"; + /** + * Opt-in toggles for the extended logging categories. All default to {@code false} in + * config so existing deployments don't see new event volume until explicitly enabled. + */ + public static final String ENABLE_COMBAT = "splunk.craft.enable.combat"; + public static final String ENABLE_ITEM = "splunk.craft.enable.item"; + public static final String ENABLE_PROGRESSION = "splunk.craft.enable.progression"; + public static final String ENABLE_SESSION_DETAIL = "splunk.craft.enable.session_detail"; + public static final String ENABLE_SERVER = "splunk.craft.enable.server"; + public static final String ENABLE_PERFORMANCE = "splunk.craft.enable.performance"; + public static final String ENABLE_SESSION_IP = "splunk.craft.enable.session_ip"; + public static final String PERFORMANCE_INTERVAL_TICKS = "splunk.craft.performance.interval_ticks"; + + /** + * Player-stats scraper: periodically reads the per-player {@code stats/.json} and + * {@code advancements/.json} files and upserts a flattened snapshot into a Splunk + * KV-store collection via {@link com.splunk.sharedmc.KvStoreConnection}. This path uses the + * splunkd management REST endpoint (default port 8089, HTTPS, bearer token) -- NOT HEC, + * which cannot write a KV store. + */ + public static final String ENABLE_PLAYERSTATS = "splunk.craft.enable.playerstats"; + public static final String PLAYERSTATS_INTERVAL_TICKS = "splunk.craft.playerstats.interval_ticks"; + public static final String KVSTORE_HOST = "splunk.craft.kvstore.host"; + public static final String KVSTORE_PORT = "splunk.craft.kvstore.port"; + public static final String KVSTORE_APP = "splunk.craft.kvstore.app"; + public static final String KVSTORE_COLLECTION = "splunk.craft.kvstore.collection"; + public static final String KVSTORE_TOKEN = "splunk.craft.kvstore.bearer_token"; + public static final String WORLD_PATH = "splunk.craft.world.path"; + protected static final Logger logger = LogManager.getLogger(LOGGER_NAME); private static SingleSplunkConnection connection; @@ -31,7 +60,10 @@ public class AbstractEventLogger { private static int port; private static String token; + protected final Properties props; + public AbstractEventLogger(Properties properties) { + this.props = properties; // brittle way to do this if (connection == null) { logEventsToConsole = Boolean.valueOf(properties.getProperty(LOG_EVENTS_TO_CONSOLE_PROP_KEY, "true")); @@ -59,4 +91,24 @@ protected void logAndSend(LoggableEvent loggable) { } connection.sendToSplunk(loggable.toJson()); } + + /** + * Reads a boolean toggle from the plugin's {@link Properties}, loaded once at startup + * (no hot-reload); default false keeps high-volume categories opt-in. + */ + protected boolean isEnabled(String key) { + return Boolean.parseBoolean(props.getProperty(key, "false")); + } + + /** + * Reads an integer config value from the plugin's {@link Properties}, loaded once at + * startup (no hot-reload); falls back to {@code defaultValue} if missing or unparseable. + */ + protected int intProp(String key, int defaultValue) { + try { + return Integer.parseInt(props.getProperty(key, Integer.toString(defaultValue))); + } catch (NumberFormatException e) { + return defaultValue; + } + } } diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/AbstractLoggableEvent.java b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/AbstractLoggableEvent.java index 56a93d5..a5507cb 100644 --- a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/AbstractLoggableEvent.java +++ b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/AbstractLoggableEvent.java @@ -16,23 +16,31 @@ public class AbstractLoggableEvent extends SplunkCimLogEvent implements Loggable public static final String ACTION = "action"; /** - * Constructor. Enforces that subclasses must have a loggable event type. + * Constructor. Enforces that subclasses must have a loggable event type. Null-checks + * {@code coordinates} before dereferencing it (fixes a prior NPE risk when an event has + * no location, e.g. server lifecycle events) and delegates to the 3-arg constructor. * * @param type The type of event that this is. */ public AbstractLoggableEvent(LoggableEventType type, long worldTime, String worldName, Point3dLong coordinates) { + this(type, worldTime, worldName); + if (coordinates != null) { + this.addField("xCoord", coordinates.xCoord); + this.addField("yCoord", coordinates.yCoord); + this.addField("zCoord", coordinates.zCoord); + } + } + + /** + * Constructor for events with no world location (e.g. server lifecycle, performance). + */ + public AbstractLoggableEvent(LoggableEventType type, long worldTime, String worldName) { super(type.getEventName(), ""); - this.addField("time", System.currentTimeMillis()); - - this.addField("game_time", worldTime); - if(worldName != null) { + if (worldName != null) { this.addField("world", worldName); } - this.addField("xCoord", coordinates.xCoord); - this.addField("yCoord", coordinates.yCoord); - this.addField("zCoord", coordinates.zCoord); } @Override diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableCombatEvent.java b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableCombatEvent.java new file mode 100644 index 0000000..dc19c70 --- /dev/null +++ b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableCombatEvent.java @@ -0,0 +1,61 @@ +package com.splunk.sharedmc.loggable_events; + +import com.splunk.sharedmc.Point3dLong; + +/** + * Combat and survival events: damage dealt/taken, kills, healing, hunger, respawn. + */ +public class LoggableCombatEvent extends AbstractLoggableEvent { + + /** + * Constructor. + * + * @param action The type of combat action this represents, e.g. 'damage' or 'kill'. + */ + public LoggableCombatEvent(CombatAction action, long gameTime, String worldName, Point3dLong location) { + super(LoggableEventType.COMBAT, gameTime, worldName, location); + this.addField(ACTION, action.asString()); + } + + public LoggableCombatEvent setVictim(String victim) { + this.addField("victim", victim); + return this; + } + + public LoggableCombatEvent setSource(String source) { + this.addField("source", source); + return this; + } + + public LoggableCombatEvent setAmount(double amount) { + this.addField("amount", amount); + return this; + } + + public LoggableCombatEvent setCause(String cause) { + this.addField(CAUSE, cause); + return this; + } + + public LoggableCombatEvent setFoodLevel(int foodLevel) { + this.addField("food_level", foodLevel); + return this; + } + + public LoggableCombatEvent setHealthRemaining(double health) { + this.addField("health_remaining", health); + return this; + } + + public enum CombatAction { + DAMAGE("damage"), + KILL("kill"), + HEAL("heal"), + HUNGER("hunger"), + RESPAWN("respawn"); + + private final String action; + CombatAction(String action) { this.action = action; } + public String asString() { return action; } + } +} diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableEventType.java b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableEventType.java index 3e2382d..7587242 100644 --- a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableEventType.java +++ b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableEventType.java @@ -1,12 +1,19 @@ package com.splunk.sharedmc.loggable_events; /** - * Categories of loggable events. + * Categories of loggable events. Includes the extended logging categories SERVER, + * PERFORMANCE, COMBAT, ITEM, and PROGRESSION added alongside the original PLAYER, BLOCK, + * and DEATH categories. */ public enum LoggableEventType { PLAYER("PlayerEvent"), BLOCK("BlockEvent"), - DEATH("DeathEvent"); + DEATH("DeathEvent"), + SERVER("ServerEvent"), + PERFORMANCE("PerformanceEvent"), + COMBAT("CombatEvent"), + ITEM("ItemEvent"), + PROGRESSION("ProgressionEvent"); private final String eventName; diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableItemEvent.java b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableItemEvent.java new file mode 100644 index 0000000..4f9e44f --- /dev/null +++ b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableItemEvent.java @@ -0,0 +1,43 @@ +package com.splunk.sharedmc.loggable_events; + +import com.splunk.sharedmc.Point3dLong; + +/** + * Item economy events: pickup and drop. + */ +public class LoggableItemEvent extends AbstractLoggableEvent { + + /** + * Constructor. + * + * @param action The type of item action this represents, e.g. 'pickup' or 'drop'. + */ + public LoggableItemEvent(ItemAction action, long gameTime, String worldName, Point3dLong location) { + super(LoggableEventType.ITEM, gameTime, worldName, location); + this.addField(ACTION, action.asString()); + } + + public LoggableItemEvent setPlayerName(String playerName) { + this.addField(PLAYER_NAME, playerName); + return this; + } + + public LoggableItemEvent setItem(String item) { + this.addField("item", item); + return this; + } + + public LoggableItemEvent setQuantity(int quantity) { + this.addField("quantity", quantity); + return this; + } + + public enum ItemAction { + PICKUP("pickup"), + DROP("drop"); + + private final String action; + ItemAction(String action) { this.action = action; } + public String asString() { return action; } + } +} diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggablePerformanceEvent.java b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggablePerformanceEvent.java new file mode 100644 index 0000000..f9ee0ca --- /dev/null +++ b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggablePerformanceEvent.java @@ -0,0 +1,47 @@ +package com.splunk.sharedmc.loggable_events; + +/** + * A sampled snapshot of server performance metrics. Unlike the other LoggableEvent types, + * this is produced periodically by {@code ScheduledMetricLogger} polling rather than in + * response to a Bukkit event. + */ +public class LoggablePerformanceEvent extends AbstractLoggableEvent { + + /** + * Constructor. + * + * @param gameTime The in-game time at which this sample was taken. + */ + public LoggablePerformanceEvent(long gameTime) { + super(LoggableEventType.PERFORMANCE, gameTime, null); + this.addField(ACTION, "performance_sample"); + } + + /** + * Unused on vanilla spigot-api — {@code Bukkit.getTPS()} is a Paper-only API; retained + * for when/if the project switches to paper-api. + */ + public LoggablePerformanceEvent setTps(double tps) { + this.addField("tps", tps); + return this; + } + + /** + * Unused on vanilla spigot-api — {@code Bukkit.getAverageTickTime()} is a Paper-only + * API; retained for when/if the project switches to paper-api. + */ + public LoggablePerformanceEvent setMspt(double mspt) { + this.addField("mspt", mspt); + return this; + } + + public LoggablePerformanceEvent setOnlinePlayers(int count) { + this.addField("online_players", count); + return this; + } + + public LoggablePerformanceEvent setLoadedChunks(int chunks) { + this.addField("loaded_chunks", chunks); + return this; + } +} diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggablePlayerEvent.java b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggablePlayerEvent.java index 92112a6..3230f96 100644 --- a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggablePlayerEvent.java +++ b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggablePlayerEvent.java @@ -51,7 +51,40 @@ public LoggablePlayerEvent setFrom(Point3dLong from) { this.addField("from_x", from.xCoord); this.addField("from_y", from.yCoord); this.addField("from_z", from.zCoord); - + + return this; + } + + /** + * Sets the player's unique id, captured on connect to disambiguate players across + * name changes. + */ + public LoggablePlayerEvent setPlayerUuid(String uuid) { + this.addField("uuid", uuid); + return this; + } + + /** + * Sets the player's client IP. The project explicitly treats this as non-PII data; + * it is only logged when {@code splunk.craft.enable.session_ip=true}. + */ + public LoggablePlayerEvent setPlayerIp(String ip) { + this.addField("client_ip", ip); + return this; + } + + /** + * Currently unused — {@code Player.getProtocolVersion()} is a Paper-only API and is + * not available on vanilla spigot-api. + */ + public LoggablePlayerEvent setProtocolVersion(int protocol) { + this.addField("protocol_version", protocol); + return this; + } + + /** Sets the player's new game mode, e.g. for a gamemode-change event. */ + public LoggablePlayerEvent setGamemode(String gamemode) { + this.addField("gamemode", gamemode); return this; } @@ -62,7 +95,16 @@ public enum PlayerEventAction { PLAYER_CONNECT("player_connect"), PLAYER_DISCONNECT("player_disconnect"), CHAT("chat"), - LOCATION("move"); + LOCATION("move"), + /** Player teleported, e.g. via command, plugin, or end/nether portal. */ + TELEPORT("teleport"), + /** Player switched game mode, e.g. survival to creative. */ + GAMEMODE_CHANGE("gamemode_change"), + /** Player entered a bed. */ + BED_ENTER("bed_enter"), + /** Player changed worlds, e.g. via portal or teleport command. */ + WORLD_CHANGE("world_change"), + ADVANCEMENT("advancement"); /** * The name of the action. diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableProgressionEvent.java b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableProgressionEvent.java new file mode 100644 index 0000000..1a94bd2 --- /dev/null +++ b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableProgressionEvent.java @@ -0,0 +1,51 @@ +package com.splunk.sharedmc.loggable_events; + +/** + * Player progression and activity: XP, level, enchant, craft, fish, command. + */ +public class LoggableProgressionEvent extends AbstractLoggableEvent { + + /** + * Constructor. + * + * @param action The type of progression action this represents, e.g. 'level_change'. + */ + public LoggableProgressionEvent(ProgressionAction action, long gameTime, String worldName) { + super(LoggableEventType.PROGRESSION, gameTime, worldName); + this.addField(ACTION, action.asString()); + } + + public LoggableProgressionEvent setPlayerName(String playerName) { + this.addField(PLAYER_NAME, playerName); + return this; + } + + public LoggableProgressionEvent setNewLevel(int level) { + this.addField("new_level", level); + return this; + } + + public LoggableProgressionEvent setExpAmount(int exp) { + this.addField("exp_amount", exp); + return this; + } + + /** Free-form detail: command text, enchant name, crafted item, fish caught. */ + public LoggableProgressionEvent setDetail(String detail) { + this.addField("detail", detail); + return this; + } + + public enum ProgressionAction { + EXP_CHANGE("exp_change"), + LEVEL_CHANGE("level_change"), + ENCHANT("enchant"), + CRAFT("craft"), + FISH("fish"), + COMMAND("command"); + + private final String action; + ProgressionAction(String action) { this.action = action; } + public String asString() { return action; } + } +} diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableServerEvent.java b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableServerEvent.java new file mode 100644 index 0000000..c411365 --- /dev/null +++ b/shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableServerEvent.java @@ -0,0 +1,37 @@ +package com.splunk.sharedmc.loggable_events; + +/** + * Server lifecycle and world-state events (start, stop, weather). + */ +public class LoggableServerEvent extends AbstractLoggableEvent { + + /** + * Constructor. + * + * @param action The type of server action this represents, e.g. 'server_start'. + */ + public LoggableServerEvent(ServerAction action, long gameTime, String worldName) { + super(LoggableEventType.SERVER, gameTime, worldName); + this.addField(ACTION, action.asString()); + } + + public LoggableServerEvent setWeather(String weather) { + this.addField("weather", weather); + return this; + } + + public LoggableServerEvent setMotd(String motd) { + this.addField("motd", motd); + return this; + } + + public enum ServerAction { + SERVER_START("server_start"), + SERVER_STOP("server_stop"), + WEATHER_CHANGE("weather_change"); + + private final String action; + ServerAction(String action) { this.action = action; } + public String asString() { return action; } + } +} diff --git a/shared-mc/src/main/java/com/splunk/sharedmc/util/EventThrottle.java b/shared-mc/src/main/java/com/splunk/sharedmc/util/EventThrottle.java new file mode 100644 index 0000000..6e0ff58 --- /dev/null +++ b/shared-mc/src/main/java/com/splunk/sharedmc/util/EventThrottle.java @@ -0,0 +1,63 @@ +package com.splunk.sharedmc.util; + +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; + +/** + * Per-key time-window throttle, backed by a guava {@link Cache}. Used to prevent flooding + * Splunk with high-frequency events (e.g. damage, food level changes, item pickups). + * {@link #allow(String)} returns true at most once per window per key. Backed by a + * size-bounded guava cache so it is safe for many players. + */ +public class EventThrottle { + + private static final int MAX_KEYS = 1024; + + private final long windowMillis; + private final LongSupplier clock; + private final Cache lastAllowed; + + /** + * Constructor using the real system clock. + * + * @param windowMillis Minimum time, in milliseconds, between two allowed calls for the + * same key. + */ + public EventThrottle(long windowMillis) { + this(windowMillis, System::currentTimeMillis); + } + + /** + * Testable constructor with an injectable clock. The {@code clock} param exists so the + * throttle can be unit-tested without depending on real wall-clock time. + * + * @param windowMillis Minimum time, in milliseconds, between two allowed calls for the + * same key. + * @param clock Supplies the current time; injected so tests can control elapsed time. + */ + public EventThrottle(long windowMillis, LongSupplier clock) { + this.windowMillis = windowMillis; + this.clock = clock; + this.lastAllowed = CacheBuilder.newBuilder() + .maximumSize(MAX_KEYS) + .expireAfterAccess(windowMillis * 4, TimeUnit.MILLISECONDS) + .build(); + } + + /** + * @return true if an event for {@code key} should be sent now (first call, or the + * window since the last allowed call has elapsed); false to drop it. + */ + public synchronized boolean allow(String key) { + long now = clock.getAsLong(); + Long last = lastAllowed.getIfPresent(key); + if (last == null || (now - last) >= windowMillis) { + lastAllowed.put(key, now); + return true; + } + return false; + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/SingleSplunkConnectionTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/SingleSplunkConnectionTest.java new file mode 100644 index 0000000..8fe1cc0 --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/SingleSplunkConnectionTest.java @@ -0,0 +1,26 @@ +package com.splunk.sharedmc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.Test; + +public class SingleSplunkConnectionTest { + + @Test + public void buildHecEnvelope_wrapsMessageInEventField() { + String out = SingleSplunkConnection.buildHecEnvelope("hello world"); + JsonObject parsed = JsonParser.parseString(out).getAsJsonObject(); + assertEquals("hello world", parsed.get("event").getAsString()); + } + + @Test + public void buildHecEnvelope_escapesQuotes() { + String out = SingleSplunkConnection.buildHecEnvelope("a \"quoted\" value"); + JsonObject parsed = JsonParser.parseString(out).getAsJsonObject(); + assertEquals("a \"quoted\" value", parsed.get("event").getAsString()); + assertTrue(out.contains("\\\"")); + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/AbstractLoggableEventTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/AbstractLoggableEventTest.java new file mode 100644 index 0000000..532e475 --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/AbstractLoggableEventTest.java @@ -0,0 +1,18 @@ +package com.splunk.sharedmc.loggable_events; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +public class AbstractLoggableEventTest { + + @Test + public void locationLessConstructor_doesNotNpe_andOmitsCoords() { + AbstractLoggableEvent e = + new AbstractLoggableEvent(LoggableEventType.SERVER, 0L, "world"); + String json = e.toJson(); + assertTrue(json.contains("SERVER".toLowerCase()) || json.contains("ServerEvent")); + assertFalse("location-less event must not emit xCoord", json.contains("xCoord")); + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableCombatEventTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableCombatEventTest.java new file mode 100644 index 0000000..41ad5b9 --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableCombatEventTest.java @@ -0,0 +1,30 @@ +package com.splunk.sharedmc.loggable_events; + +import static org.junit.Assert.assertTrue; +import com.splunk.sharedmc.Point3dLong; +import org.junit.Test; + +public class LoggableCombatEventTest { + @Test + public void damage_carriesAttackerVictimAndAmount() { + LoggableCombatEvent e = new LoggableCombatEvent( + LoggableCombatEvent.CombatAction.DAMAGE, 0L, "world", new Point3dLong(1, 2, 3)); + e.setVictim("Steve").setSource("Zombie").setAmount(4.5).setCause("ENTITY_ATTACK"); + String json = e.toJson(); + assertTrue(json.contains("victim")); + assertTrue(json.contains("Steve")); + assertTrue(json.contains("source")); + assertTrue(json.contains("4.5")); + assertTrue(json.contains("damage")); + } + + @Test + public void hunger_carriesFoodLevel() { + LoggableCombatEvent e = new LoggableCombatEvent( + LoggableCombatEvent.CombatAction.HUNGER, 0L, "world", null); + e.setVictim("Alex").setFoodLevel(7); + String json = e.toJson(); + assertTrue(json.contains("food_level")); + assertTrue(json.contains("hunger")); + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableItemEventTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableItemEventTest.java new file mode 100644 index 0000000..8e32437 --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableItemEventTest.java @@ -0,0 +1,18 @@ +package com.splunk.sharedmc.loggable_events; + +import static org.junit.Assert.assertTrue; +import com.splunk.sharedmc.Point3dLong; +import org.junit.Test; + +public class LoggableItemEventTest { + @Test + public void pickup_carriesItemAndQuantity() { + LoggableItemEvent e = new LoggableItemEvent( + LoggableItemEvent.ItemAction.PICKUP, 0L, "world", new Point3dLong(0, 64, 0)); + e.setPlayerName("Steve").setItem("DIAMOND").setQuantity(3); + String json = e.toJson(); + assertTrue(json.contains("pickup")); + assertTrue(json.contains("DIAMOND")); + assertTrue(json.contains("quantity")); + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggablePerformanceEventTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggablePerformanceEventTest.java new file mode 100644 index 0000000..b8df58d --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggablePerformanceEventTest.java @@ -0,0 +1,17 @@ +package com.splunk.sharedmc.loggable_events; + +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class LoggablePerformanceEventTest { + @Test + public void sample_serializesMetrics() { + LoggablePerformanceEvent e = new LoggablePerformanceEvent(0L); + e.setTps(19.8).setMspt(8.4).setOnlinePlayers(12).setLoadedChunks(1500); + String json = e.toJson(); + assertTrue(json.contains("tps")); + assertTrue(json.contains("19.8")); + assertTrue(json.contains("mspt")); + assertTrue(json.contains("online_players")); + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggablePlayerEventTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggablePlayerEventTest.java new file mode 100644 index 0000000..65162d2 --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggablePlayerEventTest.java @@ -0,0 +1,31 @@ +package com.splunk.sharedmc.loggable_events; + +import static org.junit.Assert.assertTrue; +import com.splunk.sharedmc.Point3dLong; +import org.junit.Test; + +public class LoggablePlayerEventTest { + @Test + public void connect_carriesSessionDetail() { + LoggablePlayerEvent e = new LoggablePlayerEvent( + LoggablePlayerEvent.PlayerEventAction.PLAYER_CONNECT, 0L, "world", new Point3dLong(0, 64, 0)); + e.setPlayerName("Steve") + .setPlayerUuid("11111111-2222-3333-4444-555555555555") + .setPlayerIp("203.0.113.7") + .setProtocolVersion(767); + String json = e.toJson(); + assertTrue(json.contains("uuid")); + assertTrue(json.contains("203.0.113.7")); + assertTrue(json.contains("protocol_version")); + } + + @Test + public void gamemodeChange_serializesAction() { + LoggablePlayerEvent e = new LoggablePlayerEvent( + LoggablePlayerEvent.PlayerEventAction.GAMEMODE_CHANGE, 0L, "world", new Point3dLong(0, 64, 0)); + e.setGamemode("CREATIVE"); + String json = e.toJson(); + assertTrue(json.contains("gamemode_change")); + assertTrue(json.contains("CREATIVE")); + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableProgressionEventTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableProgressionEventTest.java new file mode 100644 index 0000000..31475ec --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableProgressionEventTest.java @@ -0,0 +1,27 @@ +package com.splunk.sharedmc.loggable_events; + +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class LoggableProgressionEventTest { + @Test + public void levelUp_carriesNewLevel() { + LoggableProgressionEvent e = new LoggableProgressionEvent( + LoggableProgressionEvent.ProgressionAction.LEVEL_CHANGE, 0L, "world"); + e.setPlayerName("Alex").setNewLevel(30); + String json = e.toJson(); + assertTrue(json.contains("level_change")); + assertTrue(json.contains("new_level")); + assertTrue(json.contains("30")); + } + + @Test + public void command_carriesCommandText() { + LoggableProgressionEvent e = new LoggableProgressionEvent( + LoggableProgressionEvent.ProgressionAction.COMMAND, 0L, "world"); + e.setPlayerName("Alex").setDetail("/gamemode creative"); + String json = e.toJson(); + assertTrue(json.contains("command")); + assertTrue(json.contains("gamemode creative")); + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableServerEventTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableServerEventTest.java new file mode 100644 index 0000000..f3b973e --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/loggable_events/LoggableServerEventTest.java @@ -0,0 +1,24 @@ +package com.splunk.sharedmc.loggable_events; + +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class LoggableServerEventTest { + @Test + public void serverStart_serializesAction() { + LoggableServerEvent e = new LoggableServerEvent( + LoggableServerEvent.ServerAction.SERVER_START, 0L, null); + String json = e.toJson(); + assertTrue(json.contains("server_start")); + } + + @Test + public void weatherChange_carriesState() { + LoggableServerEvent e = new LoggableServerEvent( + LoggableServerEvent.ServerAction.WEATHER_CHANGE, 1000L, "world"); + e.setWeather("storm"); + String json = e.toJson(); + assertTrue(json.contains("weather")); + assertTrue(json.contains("storm")); + } +} diff --git a/shared-mc/src/test/java/com/splunk/sharedmc/util/EventThrottleTest.java b/shared-mc/src/test/java/com/splunk/sharedmc/util/EventThrottleTest.java new file mode 100644 index 0000000..4ebe425 --- /dev/null +++ b/shared-mc/src/test/java/com/splunk/sharedmc/util/EventThrottleTest.java @@ -0,0 +1,27 @@ +package com.splunk.sharedmc.util; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import org.junit.Test; + +public class EventThrottleTest { + @Test + public void firstEventForKeyPasses_secondWithinWindowBlocked() { + long[] now = {1_000L}; + EventThrottle throttle = new EventThrottle(1000L, () -> now[0]); + + assertTrue("first event passes", throttle.allow("Steve")); + now[0] = 1_500L; // 500ms later, inside window + assertFalse("second event inside window blocked", throttle.allow("Steve")); + now[0] = 2_100L; // 1100ms after first, outside window + assertTrue("event after window passes", throttle.allow("Steve")); + } + + @Test + public void differentKeysAreIndependent() { + long[] now = {0L}; + EventThrottle throttle = new EventThrottle(1000L, () -> now[0]); + assertTrue(throttle.allow("Steve")); + assertTrue(throttle.allow("Alex")); + } +} diff --git a/spigot/pom.xml b/spigot/pom.xml index 451e073..e4db243 100644 --- a/spigot/pom.xml +++ b/spigot/pom.xml @@ -10,44 +10,121 @@ spigot - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - + + + 1.21.1 + spigot + 1.21.1-R0.1 + 1.21.1-R0.1-SNAPSHOT + + + + + mc-1201 + + 1.20.1 + 1.20.1-R0.1 + 1.20.1-R0.1-SNAPSHOT + + + + mc-1204 + + 1.20.4 + 1.20.4-R0.1 + 1.20.4-R0.1-SNAPSHOT + + + + mc-1206 + + 1.20.6 + 1.20.6-R0.1 + 1.20.6-R0.1-SNAPSHOT + + + + + + org.spigotmc + spigot-api + ${spigot.api.version} + provided + net.md-5 bungeecord-chat 1.21-R0.4 + provided - - - org.spigotmc - spigot-api - 26.2-R0.1-20260616.212206-1 - - - - org.bukkit - bukkit - 26.2-R0.1-SNAPSHOT - + + com.github.cryptomorin XSeries 13.5.1 - + + + org.apache.logging.log4j + log4j-api + - + com.splunk shared-mc ${project.version} + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + logtosplunk-${mc.version}-${loader.name}-${loader.version.display} + false + + + *:* + + META-INF/versions/*/module-info.class + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + package + + shade + + + + + + diff --git a/spigot/src/main/java/com/splunk/spigot/LogToSplunkPlugin.java b/spigot/src/main/java/com/splunk/spigot/LogToSplunkPlugin.java index 1aecb1f..6effeec 100644 --- a/spigot/src/main/java/com/splunk/spigot/LogToSplunkPlugin.java +++ b/spigot/src/main/java/com/splunk/spigot/LogToSplunkPlugin.java @@ -21,7 +21,7 @@ public class LogToSplunkPlugin extends JavaPlugin implements Listener { public static final String NAME = "Splunk for Minecraft"; public static final String SPLUNK_PROPERTIES = "/config/splunk.properties"; - private Properties properties; + protected Properties properties; private static final Logger logger = LogManager.getLogger(LogToSplunkPlugin.class.getName()); @@ -47,14 +47,51 @@ public void onEnable() { getServer().getPluginManager().registerEvents(new DeathEventLogger(properties), this); getServer().getPluginManager().registerEvents(new PlayerEventLogger(properties), this); + final org.bukkit.plugin.PluginManager pm = getServer().getPluginManager(); + final java.util.Properties p = properties; + + // Each extended logging category is opt-in: only register its listener/sampler if + // the corresponding splunk.craft.enable.* toggle is set to true in config. + if (Boolean.parseBoolean(p.getProperty("splunk.craft.enable.combat", "false"))) { + pm.registerEvents(new com.splunk.spigot.eventloggers.CombatEventLogger(p), this); + } + if (Boolean.parseBoolean(p.getProperty("splunk.craft.enable.item", "false"))) { + pm.registerEvents(new com.splunk.spigot.eventloggers.ItemEventLogger(p), this); + } + if (Boolean.parseBoolean(p.getProperty("splunk.craft.enable.progression", "false"))) { + pm.registerEvents(new com.splunk.spigot.eventloggers.ProgressionEventLogger(p), this); + } + if (Boolean.parseBoolean(p.getProperty("splunk.craft.enable.server", "false"))) { + pm.registerEvents(new com.splunk.spigot.eventloggers.ServerEventLogger(p), this); + } + if (Boolean.parseBoolean(p.getProperty("splunk.craft.enable.performance", "false"))) { + int interval = 600; + try { + interval = Integer.parseInt(p.getProperty("splunk.craft.performance.interval_ticks", "600")); + } catch (NumberFormatException ignored) { } + createPerformanceSampler(p).start(this, interval); + } + // Player-stats scraper: reads on-disk stats/advancements JSON and upserts to the KV + // store. Runs async (file I/O + HTTP) so it never stalls a tick. + if (Boolean.parseBoolean(p.getProperty("splunk.craft.enable.playerstats", "false"))) { + int interval = 6000; + try { + interval = Integer.parseInt(p.getProperty("splunk.craft.playerstats.interval_ticks", "6000")); + } catch (NumberFormatException ignored) { } + new com.splunk.spigot.eventloggers.PlayerStatsScraper(p).startAsync(this, interval); + } + logAndSend("Splunk for Minecraft initialized."); } /** - * Logs and sends messages to be prepared for Splunk. - * - * @param message The message to log. + * Factory for the performance sampler. Subclasses (e.g. the Paper module) override this + * to return a platform-specific sampler that fills in TPS/MSPT from Paper-only APIs. */ + protected com.splunk.spigot.eventloggers.PerformanceSampler createPerformanceSampler(Properties props) { + return new com.splunk.spigot.eventloggers.PerformanceSampler(props); + } + private void logAndSend(String message) { logger.info(message); } diff --git a/spigot/src/main/java/com/splunk/spigot/eventloggers/CombatEventLogger.java b/spigot/src/main/java/com/splunk/spigot/eventloggers/CombatEventLogger.java new file mode 100644 index 0000000..57ef3bd --- /dev/null +++ b/spigot/src/main/java/com/splunk/spigot/eventloggers/CombatEventLogger.java @@ -0,0 +1,104 @@ +package com.splunk.spigot.eventloggers; + +import static com.splunk.spigot.LogToSplunkPlugin.locationAsPoint; + +import java.util.Properties; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityRegainHealthEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.player.PlayerRespawnEvent; + +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableCombatEvent; +import com.splunk.sharedmc.loggable_events.LoggableCombatEvent.CombatAction; +import com.splunk.sharedmc.util.EventThrottle; + +/** + * Logs combat and survival events. High-frequency events (damage, hunger) are throttled + * per-player. + * + *

Note: there is intentionally no {@code onDeath}/{@code EntityDeathEvent} handler here. + * Kill events are still handled by the pre-existing {@code DeathEventLogger} to avoid + * double-logging the same kill as both a CombatEvent and a DeathEvent. + */ +public class CombatEventLogger extends AbstractEventLogger implements Listener { + + private static final long THROTTLE_MS = 1000L; + private final EventThrottle throttle = new EventThrottle(THROTTLE_MS); + + public CombatEventLogger(Properties props) { + super(props); + } + + /** Throttled per-victim: damage events can fire many times per second. */ + @EventHandler + public void onDamage(EntityDamageByEntityEvent event) { + if (!(event.getEntity() instanceof Player)) { + return; + } + Player victim = (Player) event.getEntity(); + if (!throttle.allow("dmg:" + victim.getName())) { + return; + } + LoggableCombatEvent loggable = new LoggableCombatEvent( + CombatAction.DAMAGE, victim.getWorld().getTime(), victim.getWorld().getName(), + locationAsPoint(victim.getLocation())); + loggable.setVictim(victim.getName()) + .setSource(event.getDamager().getType().toString()) + .setAmount(event.getFinalDamage()) + .setCause(event.getCause().toString()) + .setHealthRemaining(victim.getHealth()); + logAndSend(loggable); + } + + /** Throttled per-player: regen-based healing (e.g. saturation) can fire frequently. */ + @EventHandler + public void onRegainHealth(EntityRegainHealthEvent event) { + if (!(event.getEntity() instanceof Player)) { + return; + } + Player player = (Player) event.getEntity(); + if (!throttle.allow("heal:" + player.getName())) { + return; + } + LoggableCombatEvent loggable = new LoggableCombatEvent( + CombatAction.HEAL, player.getWorld().getTime(), player.getWorld().getName(), + locationAsPoint(player.getLocation())); + loggable.setVictim(player.getName()) + .setAmount(event.getAmount()) + .setCause(event.getRegainReason().toString()) + .setHealthRemaining(player.getHealth()); + logAndSend(loggable); + } + + /** Throttled per-player: food level changes frequently while eating, sprinting, etc. */ + @EventHandler + public void onFoodLevelChange(FoodLevelChangeEvent event) { + if (!(event.getEntity() instanceof Player)) { + return; + } + Player player = (Player) event.getEntity(); + if (!throttle.allow("food:" + player.getName())) { + return; + } + LoggableCombatEvent loggable = new LoggableCombatEvent( + CombatAction.HUNGER, player.getWorld().getTime(), player.getWorld().getName(), + locationAsPoint(player.getLocation())); + loggable.setVictim(player.getName()).setFoodLevel(event.getFoodLevel()); + logAndSend(loggable); + } + + /** Not throttled: respawn is a rare, deliberate-trigger event for a given player. */ + @EventHandler + public void onRespawn(PlayerRespawnEvent event) { + LoggableCombatEvent loggable = new LoggableCombatEvent( + CombatAction.RESPAWN, event.getPlayer().getWorld().getTime(), + event.getPlayer().getWorld().getName(), locationAsPoint(event.getRespawnLocation())); + loggable.setVictim(event.getPlayer().getName()); + logAndSend(loggable); + } +} diff --git a/spigot/src/main/java/com/splunk/spigot/eventloggers/ItemEventLogger.java b/spigot/src/main/java/com/splunk/spigot/eventloggers/ItemEventLogger.java new file mode 100644 index 0000000..60c13f5 --- /dev/null +++ b/spigot/src/main/java/com/splunk/spigot/eventloggers/ItemEventLogger.java @@ -0,0 +1,60 @@ +package com.splunk.spigot.eventloggers; + +import static com.splunk.spigot.LogToSplunkPlugin.locationAsPoint; + +import java.util.Properties; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.player.PlayerDropItemEvent; + +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableItemEvent; +import com.splunk.sharedmc.loggable_events.LoggableItemEvent.ItemAction; +import com.splunk.sharedmc.util.EventThrottle; + +/** + * Logs item pickup and drop events. Pickup is throttled (it can fire rapidly, e.g. when + * picking up XP orbs or arrows); drop is not throttled since it is a deliberate, low + * frequency player action. + */ +public class ItemEventLogger extends AbstractEventLogger implements Listener { + + private final EventThrottle throttle = new EventThrottle(1000L); + + public ItemEventLogger(Properties props) { + super(props); + } + + @EventHandler + public void onPickup(EntityPickupItemEvent event) { + if (!(event.getEntity() instanceof Player)) { + return; + } + Player player = (Player) event.getEntity(); + if (!throttle.allow("pickup:" + player.getName())) { + return; + } + LoggableItemEvent loggable = new LoggableItemEvent( + ItemAction.PICKUP, player.getWorld().getTime(), player.getWorld().getName(), + locationAsPoint(player.getLocation())); + loggable.setPlayerName(player.getName()) + .setItem(event.getItem().getItemStack().getType().toString()) + .setQuantity(event.getItem().getItemStack().getAmount()); + logAndSend(loggable); + } + + @EventHandler + public void onDrop(PlayerDropItemEvent event) { + Player player = event.getPlayer(); + LoggableItemEvent loggable = new LoggableItemEvent( + ItemAction.DROP, player.getWorld().getTime(), player.getWorld().getName(), + locationAsPoint(player.getLocation())); + loggable.setPlayerName(player.getName()) + .setItem(event.getItemDrop().getItemStack().getType().toString()) + .setQuantity(event.getItemDrop().getItemStack().getAmount()); + logAndSend(loggable); + } +} diff --git a/spigot/src/main/java/com/splunk/spigot/eventloggers/PerformanceSampler.java b/spigot/src/main/java/com/splunk/spigot/eventloggers/PerformanceSampler.java new file mode 100644 index 0000000..dd369d8 --- /dev/null +++ b/spigot/src/main/java/com/splunk/spigot/eventloggers/PerformanceSampler.java @@ -0,0 +1,38 @@ +package com.splunk.spigot.eventloggers; + +import java.util.Properties; + +import org.bukkit.Bukkit; + +import com.splunk.sharedmc.loggable_events.LoggablePerformanceEvent; +import com.splunk.spigot.scheduling.ScheduledMetricLogger; + +/** + * Periodically samples server performance (online players, loaded chunks). Extends + * {@link ScheduledMetricLogger}, so this is polling-based rather than event-driven. + * + *

NOTE: {@code Bukkit.getTPS()} and {@code Bukkit.getAverageTickTime()} are + * Paper-only APIs and are not present on vanilla spigot-api (verified via + * {@code javap} against spigot-api 1.21.10 — no {@code getTPS}/{@code AverageTickTime} + * symbols found on {@code org.bukkit.Bukkit}). TPS/MSPT sampling is therefore omitted; + * only online_players and loaded_chunks, which are available on the Bukkit API, are + * sampled here. + */ +public class PerformanceSampler extends ScheduledMetricLogger { + + public PerformanceSampler(Properties props) { + super(props); + } + + @Override + protected void sample() { + LoggablePerformanceEvent e = new LoggablePerformanceEvent(0L); + e.setOnlinePlayers(Bukkit.getOnlinePlayers().size()); + int loaded = 0; + for (org.bukkit.World w : Bukkit.getWorlds()) { + loaded += w.getLoadedChunks().length; + } + e.setLoadedChunks(loaded); + logAndSend(e); + } +} diff --git a/spigot/src/main/java/com/splunk/spigot/eventloggers/PlayerEventLogger.java b/spigot/src/main/java/com/splunk/spigot/eventloggers/PlayerEventLogger.java index c68e170..bf75d26 100644 --- a/spigot/src/main/java/com/splunk/spigot/eventloggers/PlayerEventLogger.java +++ b/spigot/src/main/java/com/splunk/spigot/eventloggers/PlayerEventLogger.java @@ -13,6 +13,12 @@ import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerAdvancementDoneEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerGameModeChangeEvent; +import org.bukkit.event.player.PlayerBedEnterEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; @@ -57,8 +63,13 @@ public PlayerEventLogger(Properties props) { */ @EventHandler public void onPlayerConnect(PlayerLoginEvent event) { - logAndSend( - generateLoggablePlayerEvent(event, PlayerEventAction.PLAYER_CONNECT, null, event.getKickMessage())); + LoggablePlayerEvent loggable = + generateLoggablePlayerEvent(event, PlayerEventAction.PLAYER_CONNECT, null, event.getKickMessage()); + loggable.setPlayerUuid(event.getPlayer().getUniqueId().toString()); + if (isEnabled(ENABLE_SESSION_IP) && event.getAddress() != null) { + loggable.setPlayerIp(event.getAddress().getHostAddress()); + } + logAndSend(loggable); } /** @@ -119,4 +130,98 @@ private LoggablePlayerEvent generateLoggablePlayerEvent( return loggable; } + + /** + * Logs player chat messages to Splunk. + * + * @param event The captured event. + */ + @EventHandler + public void onPlayerChat(AsyncPlayerChatEvent event) { + logAndSend( + generateLoggablePlayerEvent(event, PlayerEventAction.CHAT, null, event.getMessage())); + } + + /** + * Logs player advancement unlocks to Splunk. + * + * @param event The captured event. + */ + @EventHandler + public void onPlayerAdvancementDone(PlayerAdvancementDoneEvent event) { + // We only want to log real achievements/advancements, not recipe unlocks. + String key = event.getAdvancement().getKey().toString(); + if (key.startsWith("minecraft:recipes/")) { + return; + } + logAndSend( + generateLoggablePlayerEvent(event, PlayerEventAction.ADVANCEMENT, null, key)); + } + + /** + * Logs player teleports to Splunk. Returns early via the + * {@code isEnabled(ENABLE_SESSION_DETAIL)} guard — this category is opt-in. + * + * @param event The captured event. + */ + @EventHandler + public void onTeleport(PlayerTeleportEvent event) { + if (!isEnabled(ENABLE_SESSION_DETAIL)) { + return; + } + LoggablePlayerEvent loggable = generateLoggablePlayerEvent( + event, PlayerEventAction.TELEPORT, event.getCause().toString(), null); + loggable.setFrom(locationAsPoint(event.getFrom())); + loggable.setTo(locationAsPoint(event.getTo())); + logAndSend(loggable); + } + + /** + * Logs player game mode changes to Splunk. Returns early via the + * {@code isEnabled(ENABLE_SESSION_DETAIL)} guard — this category is opt-in. + * + * @param event The captured event. + */ + @EventHandler + public void onGameModeChange(PlayerGameModeChangeEvent event) { + if (!isEnabled(ENABLE_SESSION_DETAIL)) { + return; + } + LoggablePlayerEvent loggable = generateLoggablePlayerEvent( + event, PlayerEventAction.GAMEMODE_CHANGE, null, null); + loggable.setGamemode(event.getNewGameMode().toString()); + logAndSend(loggable); + } + + /** + * Logs when a player enters a bed. Returns early via the + * {@code isEnabled(ENABLE_SESSION_DETAIL)} guard — this category is opt-in. + * + * @param event The captured event. + */ + @EventHandler + public void onBedEnter(PlayerBedEnterEvent event) { + if (!isEnabled(ENABLE_SESSION_DETAIL)) { + return; + } + LoggablePlayerEvent loggable = generateLoggablePlayerEvent( + event, PlayerEventAction.BED_ENTER, null, null); + logAndSend(loggable); + } + + /** + * Logs when a player changes worlds. Returns early via the + * {@code isEnabled(ENABLE_SESSION_DETAIL)} guard — this category is opt-in. + * + * @param event The captured event. + */ + @EventHandler + public void onWorldChange(PlayerChangedWorldEvent event) { + if (!isEnabled(ENABLE_SESSION_DETAIL)) { + return; + } + LoggablePlayerEvent loggable = generateLoggablePlayerEvent( + event, PlayerEventAction.WORLD_CHANGE, null, event.getFrom().getName()); + logAndSend(loggable); + } } diff --git a/spigot/src/main/java/com/splunk/spigot/eventloggers/PlayerStatsScraper.java b/spigot/src/main/java/com/splunk/spigot/eventloggers/PlayerStatsScraper.java new file mode 100644 index 0000000..88b2f6d --- /dev/null +++ b/spigot/src/main/java/com/splunk/spigot/eventloggers/PlayerStatsScraper.java @@ -0,0 +1,247 @@ +package com.splunk.spigot.eventloggers; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import com.splunk.sharedmc.KvStoreConnection; +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.spigot.scheduling.ScheduledMetricLogger; + +/** + * Periodically scrapes the per-player snapshot files Minecraft writes to disk + * ({@code /players/stats/.json} and {@code .../advancements/.json}), + * flattens them into one document per player, and upserts those documents into a Splunk + * KV-store collection via {@link KvStoreConnection}. + * + *

This data is intentionally NOT sent through HEC/an index: it is a current snapshot, not + * a time series, so a KV store keyed by player UUID (idempotent overwrite) is the right home. + * See {@link KvStoreConnection} for why HEC can't be used. + * + *

Runs off the main server thread (see {@link ScheduledMetricLogger#startAsync}); it only + * reads files and does HTTP, never touches the Bukkit world API. To avoid re-uploading + * unchanged players every cycle, the last-seen file modification time per UUID is cached and + * only changed files are pushed. + */ +public class PlayerStatsScraper extends ScheduledMetricLogger { + + /** Default world directory name; overridable via {@link AbstractEventLogger#WORLD_PATH}. */ + private static final String DEFAULT_WORLD = "world"; + + /** Custom-stat keys we surface as first-class columns (the rest are kept as category totals). */ + private static final String[] CUSTOM_STAT_COLUMNS = { + "minecraft:deaths", + "minecraft:mob_kills", + "minecraft:player_kills", + "minecraft:play_time", + "minecraft:total_world_time", + "minecraft:walk_one_cm", + "minecraft:sprint_one_cm", + "minecraft:jump", + "minecraft:damage_dealt", + "minecraft:damage_taken", + "minecraft:time_since_rest" + }; + + private final KvStoreConnection kv; + private final File statsDir; + private final File advancementsDir; + private final File usercacheFile; + + /** UUID -> last stats-file lastModified() we successfully uploaded, to push only deltas. */ + private final Map uploadedMtimes = new HashMap<>(); + + public PlayerStatsScraper(Properties props) { + super(props); + + String host = props.getProperty(KVSTORE_HOST, "127.0.0.1"); + int port = intProp(KVSTORE_PORT, 8089); + String app = props.getProperty(KVSTORE_APP, "minecraft-app"); + String collection = props.getProperty(KVSTORE_COLLECTION, "minecraft_player_stats"); + String token = props.getProperty(KVSTORE_TOKEN); + if (token == null || token.trim().isEmpty()) { + throw new IllegalArgumentException("Property `" + KVSTORE_TOKEN + "` must be set (a splunkd " + + "bearer token) to write player stats to the KV store."); + } + this.kv = new KvStoreConnection(host, port, app, collection, token); + + String serverDir = System.getProperty("user.dir"); + String world = props.getProperty(WORLD_PATH, DEFAULT_WORLD); + File worldDir = new File(world); + if (!worldDir.isAbsolute()) { + worldDir = new File(serverDir, world); + } + this.statsDir = new File(worldDir, "stats"); + this.advancementsDir = new File(worldDir, "advancements"); + this.usercacheFile = new File(serverDir, "usercache.json"); + } + + @Override + protected void sample() { + File[] statFiles = statsDir.listFiles((dir, name) -> name.endsWith(".json")); + if (statFiles == null || statFiles.length == 0) { + logger.debug("No player stats files found at {}", statsDir.getAbsolutePath()); + return; + } + + Map uuidToName = loadUsercache(); + + JsonArray batch = new JsonArray(); + for (File statFile : statFiles) { + String uuid = stripExtension(statFile.getName()); + long mtime = statFile.lastModified(); + + File advFile = new File(advancementsDir, uuid + ".json"); + long advMtime = advFile.exists() ? advFile.lastModified() : 0L; + long combinedMtime = Math.max(mtime, advMtime); + + Long lastSeen = uploadedMtimes.get(uuid); + if (lastSeen != null && lastSeen == combinedMtime) { + continue; // unchanged since last successful upload + } + + JsonObject doc = buildDocument(uuid, uuidToName.get(uuid), statFile, advFile, combinedMtime); + if (doc != null) { + batch.add(doc); + } + } + + if (batch.size() == 0) { + return; + } + + if (kv.batchSave(batch.toString())) { + // Only mark as uploaded once splunkd accepted the batch. + for (JsonElement el : batch) { + JsonObject doc = el.getAsJsonObject(); + uploadedMtimes.put(doc.get("uuid").getAsString(), doc.get("last_modified").getAsLong()); + } + logger.info("Upserted {} player-stats document(s) to KV store.", batch.size()); + } else { + logger.warn("KV-store upsert failed; will retry {} player(s) next cycle.", batch.size()); + } + } + + private JsonObject buildDocument(String uuid, String name, File statFile, File advFile, long combinedMtime) { + try (Reader r = new FileReader(statFile)) { + JsonObject root = JsonParser.parseReader(r).getAsJsonObject(); + + JsonObject doc = new JsonObject(); + doc.addProperty("_key", uuid); // makes batch_save an idempotent upsert + doc.addProperty("uuid", uuid); + if (name != null) { + doc.addProperty("name", name); + } + doc.addProperty("last_modified", combinedMtime); + if (root.has("DataVersion")) { + doc.addProperty("data_version", root.get("DataVersion").getAsInt()); + } + + JsonObject stats = root.has("stats") ? root.getAsJsonObject("stats") : new JsonObject(); + + // Per-category totals (sum of all entries within minecraft:mined, :killed, etc.). + for (Map.Entry cat : stats.entrySet()) { + String column = "stat_" + simpleKey(cat.getKey()) + "_total"; + doc.addProperty(column, sumValues(cat.getValue().getAsJsonObject())); + } + + // Selected custom stats surfaced as their own columns. + if (stats.has("minecraft:custom")) { + JsonObject custom = stats.getAsJsonObject("minecraft:custom"); + for (String key : CUSTOM_STAT_COLUMNS) { + if (custom.has(key)) { + doc.addProperty(simpleKey(key), custom.get(key).getAsLong()); + } + } + } + + addAdvancementCounts(doc, advFile); + return doc; + } catch (IOException | RuntimeException e) { + logger.warn("Failed to parse stats for player {} ({})", uuid, statFile.getName(), e); + return null; + } + } + + /** + * Counts completed advancements, excluding recipe unlocks ({@code minecraft:recipes/...}) + * which are noise. Adds {@code advancements_completed} and {@code advancements_total}. + */ + private void addAdvancementCounts(JsonObject doc, File advFile) { + if (!advFile.exists()) { + return; + } + try (Reader r = new FileReader(advFile)) { + JsonObject root = JsonParser.parseReader(r).getAsJsonObject(); + int completed = 0; + int total = 0; + for (Map.Entry e : root.entrySet()) { + String id = e.getKey(); + if ("DataVersion".equals(id) || id.startsWith("minecraft:recipes/")) { + continue; + } + if (!e.getValue().isJsonObject()) { + continue; + } + total++; + JsonObject adv = e.getValue().getAsJsonObject(); + if (adv.has("done") && adv.get("done").getAsBoolean()) { + completed++; + } + } + doc.addProperty("advancements_completed", completed); + doc.addProperty("advancements_total", total); + } catch (IOException | RuntimeException e) { + logger.debug("Failed to parse advancements file {}", advFile.getName(), e); + } + } + + /** Sums every numeric value in a stat category object (e.g. all blocks under minecraft:mined). */ + private static long sumValues(JsonObject obj) { + long sum = 0L; + for (Map.Entry e : obj.entrySet()) { + sum += e.getValue().getAsLong(); + } + return sum; + } + + /** Builds a flat UUID -> name map from the server's usercache.json (best-effort). */ + private Map loadUsercache() { + Map map = new HashMap<>(); + if (!usercacheFile.exists()) { + return map; + } + try (Reader r = new FileReader(usercacheFile)) { + JsonArray arr = JsonParser.parseReader(r).getAsJsonArray(); + for (JsonElement el : arr) { + JsonObject o = el.getAsJsonObject(); + if (o.has("uuid") && o.has("name")) { + map.put(o.get("uuid").getAsString(), o.get("name").getAsString()); + } + } + } catch (IOException | RuntimeException e) { + logger.debug("Could not read usercache.json for player names", e); + } + return map; + } + + /** "minecraft:mined" -> "mined"; "minecraft:play_time" -> "play_time". */ + private static String simpleKey(String namespacedKey) { + int idx = namespacedKey.indexOf(':'); + return idx >= 0 ? namespacedKey.substring(idx + 1) : namespacedKey; + } + + private static String stripExtension(String fileName) { + int idx = fileName.lastIndexOf('.'); + return idx >= 0 ? fileName.substring(0, idx) : fileName; + } +} diff --git a/spigot/src/main/java/com/splunk/spigot/eventloggers/ProgressionEventLogger.java b/spigot/src/main/java/com/splunk/spigot/eventloggers/ProgressionEventLogger.java new file mode 100644 index 0000000..07fb58f --- /dev/null +++ b/spigot/src/main/java/com/splunk/spigot/eventloggers/ProgressionEventLogger.java @@ -0,0 +1,80 @@ +package com.splunk.spigot.eventloggers; + +import java.util.Properties; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.enchantment.EnchantItemEvent; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerExpChangeEvent; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerLevelChangeEvent; +import org.bukkit.entity.Player; + +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableProgressionEvent; +import com.splunk.sharedmc.loggable_events.LoggableProgressionEvent.ProgressionAction; + +/** + * Logs progression and activity: XP, level, enchant, craft, fish, command. + */ +public class ProgressionEventLogger extends AbstractEventLogger implements Listener { + + public ProgressionEventLogger(Properties props) { + super(props); + } + + private LoggableProgressionEvent base(ProgressionAction action, Player player) { + LoggableProgressionEvent e = new LoggableProgressionEvent( + action, player.getWorld().getTime(), player.getWorld().getName()); + e.setPlayerName(player.getName()); + return e; + } + + @EventHandler + public void onExpChange(PlayerExpChangeEvent event) { + LoggableProgressionEvent e = base(ProgressionAction.EXP_CHANGE, event.getPlayer()); + e.setExpAmount(event.getAmount()); + logAndSend(e); + } + + @EventHandler + public void onLevelChange(PlayerLevelChangeEvent event) { + LoggableProgressionEvent e = base(ProgressionAction.LEVEL_CHANGE, event.getPlayer()); + e.setNewLevel(event.getNewLevel()); + logAndSend(e); + } + + @EventHandler + public void onEnchant(EnchantItemEvent event) { + LoggableProgressionEvent e = base(ProgressionAction.ENCHANT, event.getEnchanter()); + e.setDetail(event.getItem().getType().toString()); + logAndSend(e); + } + + @EventHandler + public void onCraft(CraftItemEvent event) { + if (!(event.getWhoClicked() instanceof Player)) { + return; + } + Player player = (Player) event.getWhoClicked(); + LoggableProgressionEvent e = base(ProgressionAction.CRAFT, player); + e.setDetail(event.getRecipe().getResult().getType().toString()); + logAndSend(e); + } + + @EventHandler + public void onFish(PlayerFishEvent event) { + LoggableProgressionEvent e = base(ProgressionAction.FISH, event.getPlayer()); + e.setDetail(event.getState().toString()); + logAndSend(e); + } + + @EventHandler + public void onCommand(PlayerCommandPreprocessEvent event) { + LoggableProgressionEvent e = base(ProgressionAction.COMMAND, event.getPlayer()); + e.setDetail(event.getMessage()); + logAndSend(e); + } +} diff --git a/spigot/src/main/java/com/splunk/spigot/eventloggers/ServerEventLogger.java b/spigot/src/main/java/com/splunk/spigot/eventloggers/ServerEventLogger.java new file mode 100644 index 0000000..41a61d6 --- /dev/null +++ b/spigot/src/main/java/com/splunk/spigot/eventloggers/ServerEventLogger.java @@ -0,0 +1,37 @@ +package com.splunk.spigot.eventloggers; + +import java.util.Properties; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.server.ServerLoadEvent; +import org.bukkit.event.weather.WeatherChangeEvent; + +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; +import com.splunk.sharedmc.loggable_events.LoggableServerEvent; +import com.splunk.sharedmc.loggable_events.LoggableServerEvent.ServerAction; + +/** + * Logs server lifecycle and world-state events. + */ +public class ServerEventLogger extends AbstractEventLogger implements Listener { + + public ServerEventLogger(Properties props) { + super(props); + } + + @EventHandler + public void onServerLoad(ServerLoadEvent event) { + LoggableServerEvent e = new LoggableServerEvent(ServerAction.SERVER_START, 0L, null); + e.setMotd(event.getType().toString()); + logAndSend(e); + } + + @EventHandler + public void onWeatherChange(WeatherChangeEvent event) { + LoggableServerEvent e = new LoggableServerEvent( + ServerAction.WEATHER_CHANGE, event.getWorld().getTime(), event.getWorld().getName()); + e.setWeather(event.toWeatherState() ? "storm" : "clear"); + logAndSend(e); + } +} diff --git a/spigot/src/main/java/com/splunk/spigot/scheduling/ScheduledMetricLogger.java b/spigot/src/main/java/com/splunk/spigot/scheduling/ScheduledMetricLogger.java new file mode 100644 index 0000000..7197c10 --- /dev/null +++ b/spigot/src/main/java/com/splunk/spigot/scheduling/ScheduledMetricLogger.java @@ -0,0 +1,55 @@ +package com.splunk.spigot.scheduling; + +import java.util.Properties; + +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; + +import com.splunk.sharedmc.event_loggers.AbstractEventLogger; + +/** + * Base for loggers driven by the Bukkit scheduler rather than the event bus. + * Subclasses implement {@link #sample()}; {@link #start(Plugin, long)} schedules it. + */ +public abstract class ScheduledMetricLogger extends AbstractEventLogger { + + public ScheduledMetricLogger(Properties props) { + super(props); + } + + /** Called on each scheduled tick. Build and send the metric event(s) here. */ + protected abstract void sample(); + + /** Schedules {@link #sample()} every {@code intervalTicks} ticks on the main server thread. */ + public void start(Plugin plugin, long intervalTicks) { + new BukkitRunnable() { + @Override + public void run() { + try { + sample(); + } catch (Exception e) { + logger.warn("Scheduled metric sample failed", e); + } + } + }.runTaskTimer(plugin, intervalTicks, intervalTicks); + } + + /** + * Like {@link #start(Plugin, long)} but runs {@link #sample()} off the main server thread. + * Use this when the sample does blocking I/O (file reads, HTTP) so it never stalls a tick. + * Subclasses scheduled this way MUST NOT touch the Bukkit world/entity API from + * {@link #sample()} (those calls are only safe on the main thread). + */ + public void startAsync(Plugin plugin, long intervalTicks) { + new BukkitRunnable() { + @Override + public void run() { + try { + sample(); + } catch (Exception e) { + logger.warn("Scheduled metric sample failed", e); + } + } + }.runTaskTimerAsynchronously(plugin, intervalTicks, intervalTicks); + } +}