Compare commits

..

No commits in common. "master" and "v1.0.0" have entirely different histories.

24 changed files with 246 additions and 352 deletions

View file

@ -11,10 +11,10 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK 17 - name: Set up JDK 11
uses: actions/setup-java@v2 uses: actions/setup-java@v2
with: with:
java-version: '17' java-version: '11'
distribution: 'adopt' distribution: 'adopt'
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew

View file

@ -5,18 +5,16 @@ on:
types: [ created ] types: [ created ]
jobs: jobs:
publish: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK 8 - name: Set up JDK 11
uses: actions/setup-java@v2 uses: actions/setup-java@v2
with: with:
java-version: '8' java-version: '11'
distribution: 'adopt' distribution: 'adopt'
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew
- name: Build with Gradle and publish on Modrinth - name: Build with Gradle and publish on Modrinth
run: ./gradlew publish run: ./gradlew publish
env:
MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }}

View file

@ -1,11 +1,11 @@
# FabricExporter # FabricExporter
![](https://img.shields.io/github/license/ruscalworld/fabric-exporter) ![](https://img.shields.io/github/license/RuscalWorld/FabricExporter)
![](https://img.shields.io/github/actions/workflow/status/ruscalworld/fabric-exporter/gradle.yml?branch=master) ![](https://img.shields.io/github/workflow/status/RuscalWorld/FabricExporter/Build)
Fabric mod that adds a Prometheus exporter with general metrics of your server. Fabric mod that adds a Prometheus exporter with general metrics of your server.
![Grafana Dashboard](https://grafana.com/api/dashboards/14492/images/10444/image) ![Grafana Dashboard](https://img.share.superhub.xyz/2oiycx.png)
--- ---
@ -25,7 +25,7 @@ Here is a list of metrics that are collected by FabricExporter.
You can disable any of these metrics in [config](src/main/resources/config/exporter.properties). You can disable any of these metrics in [config](src/main/resources/config/exporter.properties).
| Prometheus name | Description | Config property | Collected by | | Prometheus name | Description | Config property | Collected by |
|---------------------------------|-----------------------------------------------------------------------------------------|------------------------------|-------------------| | --------------- | ----------- | --------------- | ------------ |
| `minecraft_loaded_chunks` | Amount of currently loaded chunks on server | `enable-loaded-chunks` | Minecraft | | `minecraft_loaded_chunks` | Amount of currently loaded chunks on server | `enable-loaded-chunks` | Minecraft |
| `minecraft_total_loaded_chunks` | Amount of total loaded chunks on server | `enable-total-loaded-chunks` | Minecraft | | `minecraft_total_loaded_chunks` | Amount of total loaded chunks on server | `enable-total-loaded-chunks` | Minecraft |
| `minecraft_mspt` | Count of milliseconds per tick (MSPT) | `enable-mspt` | Spark | | `minecraft_mspt` | Count of milliseconds per tick (MSPT) | `enable-mspt` | Spark |
@ -33,7 +33,6 @@ You can disable any of these metrics in [config](src/main/resources/config/expor
| `minecraft_players_online` | Amount of currently online players on your server | `enable-players-online` | FabricExporter | | `minecraft_players_online` | Amount of currently online players on your server | `enable-players-online` | FabricExporter |
| `minecraft_entities` | Amount of currently loaded entities on your server | `enable-entities` | FabricExporter | | `minecraft_entities` | Amount of currently loaded entities on your server | `enable-entities` | FabricExporter |
| `minecraft_handshakes` | Count of handshake requests | `enable-handshakes` | FabricExporter | | `minecraft_handshakes` | Count of handshake requests | `enable-handshakes` | FabricExporter |
| `jvm_*` | JVM metrics collected by [Prometheus client](https://github.com/prometheus/client_java) | `export-jvm-metrics` | Prometheus client |
## Getting started ## Getting started
@ -41,7 +40,7 @@ To use this mod you should have at least Fabric server and Prometheus installed.
### Installing mod ### Installing mod
1. Download the mod from [Releases](https://github.com/ruscalworld/fabric-exporter/releases) page. 1. Download the mod from [Releases](https://github.com/RuscalWorld/FabricExporter/releases) page.
2. Drop downloaded mod jar to the `mods` folder. 2. Drop downloaded mod jar to the `mods` folder.
3. Start your server to generate config file. 3. Start your server to generate config file.
4. Open `config/exporter.properties`, ensure that `server-port` value is an open port that can be accessed by your Prometheus and change it if required. 4. Open `config/exporter.properties`, ensure that `server-port` value is an open port that can be accessed by your Prometheus and change it if required.
@ -83,15 +82,15 @@ In this file you can see some general settings and metrics settings.
### General settings ### General settings
| Property | Description | Default value | | Property | Description | Default value |
|-------------------|------------------------------------------------------------------|---------------| | -------- | ----------- | ------------- |
| `server-port` | Port on what the web server will listen for requests | `25585` | | `server-port` | Port on what the web server will listen for requests | `25585` |
| `update-interval` | Interval between gauge metrics updates in milliseconds | `1000` | | `update-interval` | Interval between gauge metrics updates in milliseconds | `1000` |
| `use-spark` | If set to `false`, FabricExporter will be independent from Spark | `true` | | `use-spark` | If set to `false`, FabricExporter will be independent from Spark | `true` |
### Metrics settings ### Metrics settings
You can disable any metric that registered via MetricRegistry (all metrics by default) using `exporter.properties` file. You can disable any metric that registered via MetricRegistry (all metrics by default) using the settings below.
Names of properties consist of `enable` and metric name without prefix and `_` replaced with `-`. Names of properties consist of `enabled` and metric name without prefix and `_` replaced with `-`.
For example, if you want to disable `minecraft_players_online`, you should set `enable-players-online` to `false`. For example, if you want to disable `minecraft_players_online`, you should set `enable-players-online` to `false`.
You can also see list of available properties in "Exposed metrics" section. You can also see list of available properties in "Exposed metrics" section.
If you can't find property for some metrics, you can manually add it. If you can't find property for some metrics, you can manually add it.

View file

@ -1,9 +1,16 @@
import net.fabricmc.loom.task.RemapJarTask import net.fabricmc.loom.task.RemapJarTask
import com.modrinth.minotaur.TaskModrinthUpload
buildscript {
dependencies {
classpath 'com.github.jengelman.gradle.plugins:shadow:6.1.0'
}
}
plugins { plugins {
id 'com.github.johnrengelman.shadow' version '7.1.2' id 'com.github.johnrengelman.shadow' version '6.1.0'
id 'com.modrinth.minotaur' version '2.+' id "com.modrinth.minotaur" version "1.1.0"
id 'fabric-loom' version '0.12-SNAPSHOT' id 'fabric-loom' version '0.6-SNAPSHOT'
id 'maven-publish' id 'maven-publish'
} }
@ -13,8 +20,10 @@ repositories {
} }
} }
sourceCompatibility = JavaVersion.VERSION_17 apply plugin: 'com.github.johnrengelman.shadow'
targetCompatibility = JavaVersion.VERSION_17
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
archivesBaseName = project.archives_base_name archivesBaseName = project.archives_base_name
version = project.mod_version version = project.mod_version
@ -31,78 +40,70 @@ dependencies {
// PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs. // PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs.
// You may need to force-disable transitiveness on them. // You may need to force-disable transitiveness on them.
implementation "io.prometheus:simpleclient:${project.prometheus_version}" compile "io.prometheus:simpleclient:${project.prometheus_version}"
implementation "io.prometheus:simpleclient_httpserver:${project.prometheus_version}" compile "io.prometheus:simpleclient_httpserver:${project.prometheus_version}"
implementation "io.prometheus:simpleclient_hotspot:${project.prometheus_version}"
compileOnly "me.lucko:spark-api:0.1-SNAPSHOT" compileOnly "me.lucko:spark-api:0.1-SNAPSHOT"
} }
processResources { processResources {
inputs.property 'version', project.version inputs.property "version", project.version
duplicatesStrategy = DuplicatesStrategy.INCLUDE
from(sourceSets.main.resources.srcDirs) { from(sourceSets.main.resources.srcDirs) {
include 'fabric.mod.json' include "fabric.mod.json"
expand 'version': project.version expand "version": project.version
} }
from(sourceSets.main.resources.srcDirs) { from(sourceSets.main.resources.srcDirs) {
exclude 'fabric.mod.json' exclude "fabric.mod.json"
} }
} }
// ensure that the encoding is set to UTF-8, no matter what the system default is // ensure that the encoding is set to UTF-8, no matter what the system default is
// this fixes some edge cases with special characters not displaying correctly // this fixes some edge cases with special characters not displaying correctly
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
tasks.withType(JavaCompile).configureEach { tasks.withType(JavaCompile) {
options.encoding = "UTF-8" options.encoding = "UTF-8"
} }
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present. // if it is present.
// If you remove this task, sources will not be generated. // If you remove this task, sources will not be generated.
tasks.register('sourcesJar', Jar) { task sourcesJar(type: Jar, dependsOn: classes) {
dependsOn classes classifier = "sources"
from sourceSets.main.allSource from sourceSets.main.allSource
} }
jar { jar {
from 'LICENSE' from "LICENSE"
} }
shadowJar { shadowJar {
archiveClassifier = 'shaded-dev' archiveClassifier = "shaded-dev"
dependencies { dependencies {
include dependency("io.prometheus:simpleclient:${project.prometheus_version}") include dependency("io.prometheus:simpleclient:${project.prometheus_version}")
include dependency("io.prometheus:simpleclient_common:${project.prometheus_version}") include dependency("io.prometheus:simpleclient_common:${project.prometheus_version}")
include dependency("io.prometheus:simpleclient_httpserver:${project.prometheus_version}") include dependency("io.prometheus:simpleclient_httpserver:${project.prometheus_version}")
include dependency("io.prometheus:simpleclient_hotspot:${project.prometheus_version}")
} }
} }
tasks.register('remapShadowJar', RemapJarTask) { task remapShadowJar(type: RemapJarTask, dependsOn: shadowJar) {
dependsOn shadowJar
input = shadowJar.archiveFile input = shadowJar.archiveFile
archiveFileName = shadowJar.archiveFileName.get().replaceAll('-shaded-dev\\.jar\$', '.jar') archiveFileName = shadowJar.archiveFileName.get().replaceAll("-shaded-dev\\.jar\$", ".jar")
addNestedDependencies = true addNestedDependencies = true
} remapAccessWidener = true
modrinth {
token = System.getenv('MODRINTH_TOKEN')
projectId = 'dbVXHSlv'
versionNumber = project.mod_version
versionType = 'release'
uploadFile = remapShadowJar
gameVersions.add(project.minecraft_version)
loaders.add('fabric')
dependencies {
required.project 'fabric-api'
optional.project 'spark'
}
} }
assemble.dependsOn(remapShadowJar) assemble.dependsOn(remapShadowJar)
task publishModrinth(type: TaskModrinthUpload, dependsOn: remapShadowJar) {
onlyIf { System.getenv("MODRINTH_TOKEN") }
token = System.getenv("MODRINTH_TOKEN")
projectId = 'dbVXHSlv'
versionNumber = project.mod_version
uploadFile = remapShadowJar
addGameVersion(project.minecraft_version)
addLoader('fabric')
}

View file

@ -1,15 +1,15 @@
# Done to increase the memory available to gradle. # Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx2G org.gradle.jvmargs=-Xmx1G
# Fabric Properties # Fabric Properties
# check these on https://modmuss50.me/fabric.html # check these on https://modmuss50.me/fabric.html
minecraft_version=1.20.1 minecraft_version=1.16.5
yarn_mappings=1.20.1+build.2 yarn_mappings=1.16.5+build.9
loader_version=0.14.21 loader_version=0.11.3
# Mod Properties # Mod Properties
mod_version=1.0.10 mod_version=1.0.0
maven_group=ru.ruscalworld maven_group=ru.ruscalworld
archives_base_name=fabricexporter archives_base_name=fabricexporter
# Dependencies # Dependencies
# check this on https://modmuss50.me/fabric.html # check this on https://modmuss50.me/fabric.html
fabric_version=0.83.1+1.20.1 fabric_version=0.25.1+build.416-1.16
prometheus_version=0.16.0 prometheus_version=0.10.0

Binary file not shown.

View file

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-6.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

257
gradlew vendored
View file

@ -1,7 +1,7 @@
#!/bin/sh #!/usr/bin/env sh
# #
# Copyright © 2015-2021 the original authors. # Copyright 2015 the original author or authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@ -17,101 +17,67 @@
# #
############################################################################## ##############################################################################
# ##
# Gradle start up script for POSIX generated by Gradle. ## Gradle start up script for UN*X
# ##
# 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/master/subprojects/plugins/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 # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
app_path=$0 PRG="$0"
# Need this for relative symlinks.
# Need this for daisy-chained symlinks. while [ -h "$PRG" ] ; do
while ls=`ls -ld "$PRG"`
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path link=`expr "$ls" : '.*-> \(.*\)$'`
[ -h "$app_path" ] if expr "$link" : '/.*' > /dev/null; then
do PRG="$link"
ls=$( ls -ld "$app_path" ) else
link=${ls#*' -> '} PRG=`dirname "$PRG"`"/$link"
case $link in #( fi
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # 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"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD="maximum"
warn () { warn () {
echo "$*" echo "$*"
} >&2 }
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} >&2 }
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "$( uname )" in #( case "`uname`" in
CYGWIN* ) cygwin=true ;; #( CYGWIN* )
Darwin* ) darwin=true ;; #( cygwin=true
MSYS* | MINGW* ) msys=true ;; #( ;;
NONSTOP* ) nonstop=true ;; Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@ -121,9 +87,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java JAVACMD="$JAVA_HOME/jre/sh/java"
else else
JAVACMD=$JAVA_HOME/bin/java JAVACMD="$JAVA_HOME/bin/java"
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -132,7 +98,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
@ -140,95 +106,80 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
case $MAX_FD in #( MAX_FD_LIMIT=`ulimit -H -n`
max*) if [ $? -eq 0 ] ; then
MAX_FD=$( ulimit -H -n ) || if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
warn "Could not query maximum file descriptor limit" MAX_FD="$MAX_FD_LIMIT"
esac fi
case $MAX_FD in #( ulimit -n $MAX_FD
'' | soft) :;; #( if [ $? -ne 0 ] ; then
*) warn "Could not set maximum file descriptor limit: $MAX_FD"
ulimit -n "$MAX_FD" || fi
warn "Could not set maximum file descriptor limit to $MAX_FD" else
esac warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi fi
# Collect all arguments for the java command, stacking in reverse order: # For Darwin, add options to specify how the application appears in the dock
# * args from the command line if $darwin; then
# * the main class name GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
# * -classpath fi
# * -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 # For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=$( cygpath --unix "$JAVACMD" ) JAVACMD=`cygpath --unix "$JAVACMD"`
# Now convert the arguments - kludge to limit ourselves to /bin/sh # We build the pattern for arguments to be converted via cygpath
for arg do ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
if SEP=""
case $arg in #( for dir in $ROOTDIRSRAW ; do
-*) false ;; # don't mess with options #( ROOTDIRS="$ROOTDIRS$SEP$dir"
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath SEP="|"
[ -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 done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi fi
# Collect all arguments for the java command; # Escape application args
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of save () {
# shell script including quotes and variable substitutions, so put them in for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
# double quotes to make sure that they get re-expanded; and echo " "
# * put everything else in single quotes, so that it's not re-expanded. }
APP_ARGS=`save "$@"`
set -- \ # Collect all arguments for the java command, following the shell quoting and substitution rules
"-Dorg.gradle.appname=$APP_BASE_NAME" \ eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@" exec "$JAVACMD" "$@"

21
gradlew.bat vendored
View file

@ -40,7 +40,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if "%ERRORLEVEL%" == "0" goto init
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@ -54,7 +54,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto init
echo. echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@ -64,6 +64,21 @@ echo location of your Java installation.
goto fail goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute :execute
@rem Setup the command line @rem Setup the command line
@ -71,7 +86,7 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell

View file

@ -1,5 +1,6 @@
pluginManagement { pluginManagement {
repositories { repositories {
jcenter()
maven { maven {
name = 'Fabric' name = 'Fabric'
url = 'https://maven.fabricmc.net/' url = 'https://maven.fabricmc.net/'

View file

@ -1,21 +1,16 @@
package ru.ruscalworld.fabricexporter; package ru.ruscalworld.fabricexporter;
import io.prometheus.client.exporter.HTTPServer; import io.prometheus.client.exporter.HTTPServer;
import io.prometheus.client.hotspot.DefaultExports;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import ru.ruscalworld.fabricexporter.config.MainConfig; import ru.ruscalworld.fabricexporter.config.MainConfig;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
public class FabricExporter implements ModInitializer { public class FabricExporter implements ModInitializer {
private static final Logger logger = LogManager.getLogger();
private static FabricExporter instance; private static FabricExporter instance;
private MinecraftServer server; private MinecraftServer server;
@ -34,21 +29,10 @@ public class FabricExporter implements ModInitializer {
e.printStackTrace(); e.printStackTrace();
} }
Optional<ModContainer> spark = FabricLoader.getInstance().getModContainer("spark");
if (spark.isEmpty() && config.shouldUseSpark()) {
config.setShouldUseSpark(false);
logger.warn("Spark mod is not installed, but \"use-spark\" property is enabled! TPS and MSPT metrics will be disabled.");
logger.warn("To fix this, you should either set \"use-spark\" in exporter.properties to false or install Spark mod (https://spark.lucko.me).");
}
MetricRegistry metricRegistry = new MetricRegistry(this); MetricRegistry metricRegistry = new MetricRegistry(this);
metricRegistry.registerDefault(); metricRegistry.registerDefault();
this.setMetricRegistry(metricRegistry); this.setMetricRegistry(metricRegistry);
if (config.shouldExportJvmDefaults()) {
DefaultExports.initialize();
}
ServerLifecycleEvents.SERVER_STARTING.register(this::setServer); ServerLifecycleEvents.SERVER_STARTING.register(this::setServer);
ServerLifecycleEvents.SERVER_STARTED.register(server -> { ServerLifecycleEvents.SERVER_STARTED.register(server -> {
try { try {
@ -63,8 +47,8 @@ public class FabricExporter implements ModInitializer {
}); });
ServerLifecycleEvents.SERVER_STOPPING.register(server -> { ServerLifecycleEvents.SERVER_STOPPING.register(server -> {
this.getHttpServer().close(); this.getHttpServer().stop();
this.getMetricRegistry().getMetricUpdaterTimer().cancel(); this.getMetricRegistry().getTimer().cancel();
}); });
instance = this; instance = this;

View file

@ -4,14 +4,7 @@ import io.prometheus.client.Collector;
import io.prometheus.client.Counter; import io.prometheus.client.Counter;
import io.prometheus.client.SimpleCollector; import io.prometheus.client.SimpleCollector;
import ru.ruscalworld.fabricexporter.config.MainConfig; import ru.ruscalworld.fabricexporter.config.MainConfig;
import ru.ruscalworld.fabricexporter.metrics.Metric; import ru.ruscalworld.fabricexporter.metrics.*;
import ru.ruscalworld.fabricexporter.metrics.spark.MillisPerTick;
import ru.ruscalworld.fabricexporter.metrics.spark.SparkMetric;
import ru.ruscalworld.fabricexporter.metrics.spark.TicksPerSecond;
import ru.ruscalworld.fabricexporter.metrics.world.Entities;
import ru.ruscalworld.fabricexporter.metrics.world.LoadedChunks;
import ru.ruscalworld.fabricexporter.metrics.world.OnlinePlayers;
import ru.ruscalworld.fabricexporter.metrics.world.TotalLoadedChunks;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -22,18 +15,18 @@ public class MetricRegistry {
private final FabricExporter exporter; private final FabricExporter exporter;
private final List<Metric> metrics = new ArrayList<>(); private final List<Metric> metrics = new ArrayList<>();
private final HashMap<String, Collector> customMetrics = new HashMap<>(); private final HashMap<String, Collector> customMetrics = new HashMap<>();
private final Timer metricUpdaterTimer; private final Timer timer;
public MetricRegistry(FabricExporter exporter) { public MetricRegistry(FabricExporter exporter) {
this.exporter = exporter; this.exporter = exporter;
metricUpdaterTimer = new Timer("Metric Updater Timer"); timer = new Timer();
} }
public void runUpdater() { public void runUpdater() {
MainConfig config = this.getExporter().getConfig(); MainConfig config = this.getExporter().getConfig();
MetricUpdater metricUpdater = new MetricUpdater(this.getExporter()); MetricUpdater metricUpdater = new MetricUpdater(this.getExporter());
this.getMetrics().forEach(metricUpdater::registerMetric); this.getMetrics().forEach(metricUpdater::registerMetric);
this.getMetricUpdaterTimer().schedule(metricUpdater, 1000, config.getUpdateInterval()); this.getTimer().schedule(metricUpdater, 1000, config.getUpdateInterval());
} }
public void registerDefault() { public void registerDefault() {
@ -41,11 +34,8 @@ public class MetricRegistry {
this.registerMetric(new Entities()); this.registerMetric(new Entities());
this.registerMetric(new LoadedChunks()); this.registerMetric(new LoadedChunks());
this.registerMetric(new TotalLoadedChunks()); this.registerMetric(new TotalLoadedChunks());
if (this.getExporter().getConfig().shouldUseSpark()) {
this.registerMetric(new TicksPerSecond()); this.registerMetric(new TicksPerSecond());
this.registerMetric(new MillisPerTick()); this.registerMetric(new MillisPerTick());
}
this.registerCustomMetric("handshakes", new Counter.Builder() this.registerCustomMetric("handshakes", new Counter.Builder()
.name(getMetricName("handshakes")) .name(getMetricName("handshakes"))
@ -86,8 +76,8 @@ public class MetricRegistry {
return exporter; return exporter;
} }
public Timer getMetricUpdaterTimer() { public Timer getTimer() {
return metricUpdaterTimer; return timer;
} }
public HashMap<String, Collector> getCustomMetrics() { public HashMap<String, Collector> getCustomMetrics() {

View file

@ -1,7 +1,5 @@
package ru.ruscalworld.fabricexporter; package ru.ruscalworld.fabricexporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ruscalworld.fabricexporter.metrics.Metric; import ru.ruscalworld.fabricexporter.metrics.Metric;
import java.util.ArrayList; import java.util.ArrayList;
@ -9,7 +7,6 @@ import java.util.List;
import java.util.TimerTask; import java.util.TimerTask;
public class MetricUpdater extends TimerTask { public class MetricUpdater extends TimerTask {
private final static Logger logger = LoggerFactory.getLogger("MetricUpdater");
private final List<Metric> metrics = new ArrayList<>(); private final List<Metric> metrics = new ArrayList<>();
private final FabricExporter exporter; private final FabricExporter exporter;
@ -23,7 +20,7 @@ public class MetricUpdater extends TimerTask {
try { try {
metric.update(this.getExporter()); metric.update(this.getExporter());
} catch (Exception exception) { } catch (Exception exception) {
logger.error("Error updating metric " + metric.getName(), exception); exception.printStackTrace();
} }
} }
} }

View file

@ -8,7 +8,6 @@ public class MainConfig extends Config {
private int port; private int port;
private int updateInterval; private int updateInterval;
private boolean useSpark; private boolean useSpark;
private boolean exportJvmDefaults;
public MainConfig(String name) { public MainConfig(String name) {
super(name); super(name);
@ -25,8 +24,6 @@ public class MainConfig extends Config {
this.setUpdateInterval(ConvertUtil.intToStringOrDefault(updateIntervalString, 1000)); this.setUpdateInterval(ConvertUtil.intToStringOrDefault(updateIntervalString, 1000));
this.setShouldUseSpark(properties.getProperty("use-spark", "true").equalsIgnoreCase("true")); this.setShouldUseSpark(properties.getProperty("use-spark", "true").equalsIgnoreCase("true"));
this.setShouldExportJvmDefaults(properties.getProperty("export-default-jvm-metrics", "true").equalsIgnoreCase("true"));
} }
public int getPort() { public int getPort() {
@ -52,12 +49,4 @@ public class MainConfig extends Config {
public void setShouldUseSpark(boolean useSpark) { public void setShouldUseSpark(boolean useSpark) {
this.useSpark = useSpark; this.useSpark = useSpark;
} }
public boolean shouldExportJvmDefaults() {
return exportJvmDefaults;
}
public void setShouldExportJvmDefaults(boolean exportJvmDefaults) {
this.exportJvmDefaults = exportJvmDefaults;
}
} }

View file

@ -1,31 +1,16 @@
package ru.ruscalworld.fabricexporter.metrics.world; package ru.ruscalworld.fabricexporter.metrics;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
import net.minecraft.registry.Registries;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.TypeFilter; import net.minecraft.util.registry.Registry;
import ru.ruscalworld.fabricexporter.FabricExporter; import ru.ruscalworld.fabricexporter.FabricExporter;
import ru.ruscalworld.fabricexporter.metrics.Metric;
import ru.ruscalworld.fabricexporter.util.TextUtil; import ru.ruscalworld.fabricexporter.util.TextUtil;
import java.util.HashMap; import java.util.HashMap;
public class Entities extends Metric { public class Entities extends Metric {
private static final TypeFilter<Entity, ?> ENTITY_FILTER = new TypeFilter<>() {
@Override
public Entity downcast(Entity entity) {
return entity;
}
@Override
public Class<? extends Entity> getBaseClass() {
return Entity.class;
}
};
public Entities() { public Entities() {
super("entities", "Amount of entities in the world", "world", "group", "type"); super("entities", "Amount of entities in the world", "world", "group", "type");
} }
@ -35,15 +20,15 @@ public class Entities extends Metric {
for (ServerWorld world : exporter.getServer().getWorlds()) { for (ServerWorld world : exporter.getServer().getWorlds()) {
HashMap<String, Integer> currentWorldEntities = new HashMap<>(); HashMap<String, Integer> currentWorldEntities = new HashMap<>();
world.getEntitiesByType(ENTITY_FILTER, (entity) -> true).forEach(entity -> { for (Entity entity : world.getEntitiesByType(null, entity -> true)) {
String name = Registries.ENTITY_TYPE.getId(entity.getType()).getPath(); String name = Registry.ENTITY_TYPE.getId(entity.getType()).getPath();
Integer typeCount = currentWorldEntities.getOrDefault(name, 0); Integer typeCount = currentWorldEntities.getOrDefault(name, 0);
currentWorldEntities.put(name, typeCount + 1); currentWorldEntities.put(name, typeCount + 1);
}); }
for (String type : currentWorldEntities.keySet()) { for (String type : currentWorldEntities.keySet()) {
Integer count = currentWorldEntities.get(type); Integer count = currentWorldEntities.get(type);
EntityType<?> entityType = Registries.ENTITY_TYPE.get(new Identifier(type)); EntityType<?> entityType = Registry.ENTITY_TYPE.get(new Identifier(type));
this.getGauge().labels(TextUtil.getWorldName(world), entityType.getSpawnGroup().getName(), type).set(count); this.getGauge().labels(TextUtil.getWorldName(world), entityType.getSpawnGroup().getName(), type).set(count);
} }
} }

View file

@ -1,8 +1,7 @@
package ru.ruscalworld.fabricexporter.metrics.world; package ru.ruscalworld.fabricexporter.metrics;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
import ru.ruscalworld.fabricexporter.FabricExporter; import ru.ruscalworld.fabricexporter.FabricExporter;
import ru.ruscalworld.fabricexporter.metrics.Metric;
import ru.ruscalworld.fabricexporter.util.TextUtil; import ru.ruscalworld.fabricexporter.util.TextUtil;
public class LoadedChunks extends Metric { public class LoadedChunks extends Metric {

View file

@ -0,0 +1,23 @@
package ru.ruscalworld.fabricexporter.metrics;
import me.lucko.spark.api.statistic.StatisticWindow;
import me.lucko.spark.api.statistic.misc.DoubleAverageInfo;
import me.lucko.spark.api.statistic.types.GenericStatistic;
import ru.ruscalworld.fabricexporter.FabricExporter;
public class MillisPerTick extends SparkMetric {
public MillisPerTick() {
super("mspt", "Milliseconds per tick (MSPT)", "type");
}
@Override
public void update(FabricExporter exporter) {
GenericStatistic<DoubleAverageInfo, StatisticWindow.MillisPerTick> mspt = this.getSpark().mspt();
if (mspt == null) this.getGauge().set(0);
else {
this.getGauge().labels("min").set(mspt.poll(StatisticWindow.MillisPerTick.MINUTES_1).min());
this.getGauge().labels("mean").set(mspt.poll(StatisticWindow.MillisPerTick.MINUTES_1).mean());
this.getGauge().labels("max").set(mspt.poll(StatisticWindow.MillisPerTick.MINUTES_1).max());
}
}
}

View file

@ -1,8 +1,7 @@
package ru.ruscalworld.fabricexporter.metrics.world; package ru.ruscalworld.fabricexporter.metrics;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
import ru.ruscalworld.fabricexporter.FabricExporter; import ru.ruscalworld.fabricexporter.FabricExporter;
import ru.ruscalworld.fabricexporter.metrics.Metric;
import ru.ruscalworld.fabricexporter.util.TextUtil; import ru.ruscalworld.fabricexporter.util.TextUtil;
public class OnlinePlayers extends Metric { public class OnlinePlayers extends Metric {

View file

@ -1,8 +1,7 @@
package ru.ruscalworld.fabricexporter.metrics.spark; package ru.ruscalworld.fabricexporter.metrics;
import me.lucko.spark.api.Spark; import me.lucko.spark.api.Spark;
import me.lucko.spark.api.SparkProvider; import me.lucko.spark.api.SparkProvider;
import ru.ruscalworld.fabricexporter.metrics.Metric;
public abstract class SparkMetric extends Metric { public abstract class SparkMetric extends Metric {
public SparkMetric(String name, String help, String... labels) { public SparkMetric(String name, String help, String... labels) {

View file

@ -1,4 +1,4 @@
package ru.ruscalworld.fabricexporter.metrics.spark; package ru.ruscalworld.fabricexporter.metrics;
import me.lucko.spark.api.statistic.StatisticWindow; import me.lucko.spark.api.statistic.StatisticWindow;
import me.lucko.spark.api.statistic.types.DoubleStatistic; import me.lucko.spark.api.statistic.types.DoubleStatistic;

View file

@ -1,8 +1,7 @@
package ru.ruscalworld.fabricexporter.metrics.world; package ru.ruscalworld.fabricexporter.metrics;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
import ru.ruscalworld.fabricexporter.FabricExporter; import ru.ruscalworld.fabricexporter.FabricExporter;
import ru.ruscalworld.fabricexporter.metrics.Metric;
import ru.ruscalworld.fabricexporter.util.TextUtil; import ru.ruscalworld.fabricexporter.util.TextUtil;
public class TotalLoadedChunks extends Metric { public class TotalLoadedChunks extends Metric {

View file

@ -1,29 +0,0 @@
package ru.ruscalworld.fabricexporter.metrics.spark;
import me.lucko.spark.api.statistic.StatisticWindow;
import me.lucko.spark.api.statistic.misc.DoubleAverageInfo;
import me.lucko.spark.api.statistic.types.GenericStatistic;
import ru.ruscalworld.fabricexporter.FabricExporter;
public class MillisPerTick extends SparkMetric {
public MillisPerTick() {
super("mspt", "Milliseconds per tick (MSPT)", "type");
}
@Override
public void update(FabricExporter exporter) {
GenericStatistic<DoubleAverageInfo, StatisticWindow.MillisPerTick> mspt = this.getSpark().mspt();
if (mspt == null) this.setValue(0, 0, 0);
else this.setValue(
mspt.poll(StatisticWindow.MillisPerTick.MINUTES_1).min(),
mspt.poll(StatisticWindow.MillisPerTick.MINUTES_1).mean(),
mspt.poll(StatisticWindow.MillisPerTick.MINUTES_1).max()
);
}
private void setValue(double min, double mean, double max) {
this.getGauge().labels("min").set(min);
this.getGauge().labels("mean").set(mean);
this.getGauge().labels("max").set(max);
}
}

View file

@ -1,4 +1,4 @@
# On which port Prometheus webserver should be started? # On which port webserver should be started?
# Default: 25585 # Default: 25585
server-port=25585 server-port=25585
@ -14,13 +14,8 @@ update-interval=1000
# Default: true # Default: true
use-spark=true use-spark=true
# Should FabricExporter register default Hotspot exports?
# This enables advanced metrics for JVM
# Default: true
export-default-jvm-metrics=true
# You can disable any metric that registered via MetricRegistry (all metrics by default) using the settings below # You can disable any metric that registered via MetricRegistry (all metrics by default) using the settings below
# Names of properties consist of "enable" and metric name without prefix and "_" replaced with "-" # Names of properties consist of "enabled" and metric name without prefix and "_" replaced with "-"
# For example, if you want to disable "minecraft_players_online", you should set "enable-players-online" to "false" # For example, if you want to disable "minecraft_players_online", you should set "enable-players-online" to "false"
# If you can't find property for some metrics, you can manually add it # If you can't find property for some metrics, you can manually add it
# All metrics are enabled by default # All metrics are enabled by default

View file

@ -21,8 +21,7 @@
"fabricexporter.mixins.json" "fabricexporter.mixins.json"
], ],
"depends": { "depends": {
"fabricloader": ">=0.14.13", "fabricloader": ">=0.11.3",
"minecraft": ">=1.20.1",
"fabric": "*" "fabric": "*"
}, },
"recommends": { "recommends": {