feat: update victoriametrics

This commit is contained in:
Ryan Yin
2024-10-30 20:50:00 +08:00
parent 0d7b4ac928
commit 1e33fd1e17
3 changed files with 180 additions and 1515 deletions

View File

@@ -1,6 +1,3 @@
# Based on
# - https://github.com/NixOS/nixpkgs/blob/nixos-24.05/nixos/modules/services/databases/victoriametrics.nix
# - https://github.com/NixOS/nixpkgs/blob/nixos-24.05/nixos/modules/services/monitoring/prometheus/default.nix
{ {
config, config,
pkgs, pkgs,
@@ -9,75 +6,53 @@
}: }:
with lib; let with lib; let
cfg = config.services.my-victoriametrics; cfg = config.services.my-victoriametrics;
yaml = pkgs.formats.yaml {}; settingsFormat = pkgs.formats.yaml {};
promTypes = import ./promTypes.nix {inherit lib;};
bindAddr = "${cfg.listenAddress}:${builtins.toString cfg.port}";
workingDir = "/var/lib/" + cfg.stateDir; workingDir = "/var/lib/" + cfg.stateDir;
startCommandLine =
lib.escapeShellArgs [
"${cfg.package}/bin/victoria-metrics"
"-storageDataPath=${workingDir}"
"-httpListenAddr=${cfg.listenAddress}"
"-retentionPeriod=${cfg.retentionPeriod}"
]
++ lib.optional (cfg.prometheusConfig != null) "-promscrape.config=${prometheusConfigYml}"
++ cfg.extraOptions;
prometheusConfigYml = checkedConfig (
settingsFormat.generate "prometheusConfig.yaml" cfg.prometheusConfig
);
generatedPrometheusYml = yaml.generate "prometheus.yml" scrapeConfig; checkedConfig = file:
if cfg.checkConfig
# This becomes the main config file for VictoriaMetrics's `-promscrape.config`
# https://docs.victoriametrics.com/vmagent/#how-to-collect-metrics-in-prometheus-format
scrapeConfig = {
global = filterValidPrometheus cfg.globalConfig;
scrape_configs = filterValidPrometheus cfg.scrapeConfigs;
};
filterValidPrometheus = filterAttrsListRecursive (n: v: !(n == "_module" || v == null));
filterAttrsListRecursive = pred: x:
if isAttrs x
then then
listToAttrs pkgs.runCommand "checked-config" {nativeBuildInputs = [cfg.package];} ''
( ln -s ${file} $out
concatMap ${startCommandLine} -dryRun
( ''
name: let else file;
v = x.${name};
in
if pred name v
then [
(nameValuePair name (filterAttrsListRecursive pred v))
]
else []
)
(attrNames x)
)
else if isList x
then map (filterAttrsListRecursive pred) x
else x;
in { in {
options.services.my-victoriametrics = { options.services.my-victoriametrics = {
enable = mkEnableOption "VictoriaMetrics, a time series database, long-term remote storage for victoriametrics"; enable = mkEnableOption "VictoriaMetrics, a time series database.";
package = mkPackageOption pkgs "victoriametrics" {}; package = mkPackageOption pkgs "victoriametrics" {};
port = mkOption {
type = types.port;
default = 8428;
description = ''
Port to listen on.
'';
};
listenAddress = mkOption { listenAddress = mkOption {
default = ":8428";
type = types.str; type = types.str;
default = "0.0.0.0";
description = '' description = ''
Address to listen on for the http API. TCP address to listen for incoming http requests.
''; '';
}; };
stateDir = mkOption { stateDir = mkOption {
type = types.str; type = types.str;
default = "victoriametrics2"; default = "victoriametrics";
description = '' description = ''
Directory below `/var/lib` to store VictoriaMetrics metrics data. Directory below `/var/lib` to store VictoriaMetrics metrics data.
This directory will be created automatically using systemd's StateDirectory mechanism. This directory will be created automatically using systemd's StateDirectory mechanism.
''; '';
}; };
retentionTime = mkOption { retentionPeriod = mkOption {
type = types.nullOr types.str; type = types.nullOr types.str;
default = null; default = null;
example = "15d"; example = "15d";
@@ -89,60 +64,77 @@ in {
''; '';
}; };
globalConfig = mkOption { prometheusConfig = lib.mkOption {
type = promTypes.globalConfig; type = lib.types.submodule {freeformType = settingsFormat.type;};
default = {}; default = {};
example = literalExpression ''
{
scrape_configs = [
{
job_name = "postgres-exporter";
metrics_path = "/metrics";
static_configs = [
{
targets = ["1.2.3.4:9187"];
labels.type = "database";
}
];
}
{
job_name = "node-exporter";
metrics_path = "/metrics";
static_configs = [
{
targets = ["1.2.3.4:9100"];
labels.type = "node";
}
{
targets = ["5.6.7.8:9100"];
labels.type = "node";
}
];
}
];
}
'';
description = '' description = ''
Parameters that are valid in all configuration contexts. They Config for prometheus style metrics.
also serve as defaults for other configuration sections See the docs: <https://docs.victoriametrics.com/vmagent/#how-to-collect-metrics-in-prometheus-format>
for more information.
''; '';
}; };
scrapeConfigs = mkOption { extraOptions = mkOption {
type = types.listOf promTypes.scrape_config;
default = [];
description = ''
A list of scrape configurations.
See docs: <https://docs.victoriametrics.com/vmagent/#how-to-collect-metrics-in-prometheus-format>
'';
};
extraFlags = mkOption {
type = types.listOf types.str; type = types.listOf types.str;
default = []; default = [];
example = literalExpression ''
[
"-httpAuth.username=username"
"-httpAuth.password=file:///abs/path/to/file"
"-loggerLevel=WARN"
]
'';
description = '' description = ''
Extra options to pass to VictoriaMetrics. See the README: Extra options to pass to VictoriaMetrics. See the docs:
<https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/README.md> <https://docs.victoriametrics.com/single-server-victoriametrics/#list-of-command-line-flags>
or {command}`victoriametrics -help` for more or {command}`victoriametrics -help` for more information.
information.
''; '';
}; };
}; };
config = lib.mkIf cfg.enable {
users.groups.victoriametrics = {};
users.users.victoriametrics = {
description = "victoriametrics daemon user";
isSystemUser = true; # required when uid is null
group = "victoriametrics";
};
systemd.services.my-victoriametrics = { config = lib.mkIf cfg.enable {
systemd.services.victoriametrics = {
description = "VictoriaMetrics time series database"; description = "VictoriaMetrics time series database";
wantedBy = ["multi-user.target"]; wantedBy = ["multi-user.target"];
after = ["network.target"]; after = ["network.target"];
startLimitBurst = 5; startLimitBurst = 5;
serviceConfig = { serviceConfig = {
ExecStart = '' ExecStart = startCommandLine;
${cfg.package}/bin/victoria-metrics \ DynamicUser = true;
-storageDataPath=${workingDir} \
-httpListenAddr=${bindAddr} \
-retentionPeriod=${cfg.retentionTime} \
-promscrape.config=${generatedPrometheusYml} \
${lib.escapeShellArgs cfg.extraFlags}
'';
RestartSec = 1;
User = "victoriametrics"; User = "victoriametrics";
Group = "victoriametrics";
RestartSec = 1;
Restart = "on-failure"; Restart = "on-failure";
RuntimeDirectory = "victoriametrics"; RuntimeDirectory = "victoriametrics";
RuntimeDirectoryMode = "0700"; RuntimeDirectoryMode = "0700";
@@ -154,11 +146,6 @@ in {
LimitNOFILE = 1048576; LimitNOFILE = 1048576;
# Hardening # Hardening
AmbientCapabilities = lib.mkIf (cfg.port < 1024) ["CAP_NET_BIND_SERVICE"];
CapabilityBoundingSet =
if (cfg.port < 1024)
then ["CAP_NET_BIND_SERVICE"]
else [""];
DeviceAllow = ["/dev/null rw"]; DeviceAllow = ["/dev/null rw"];
DevicePolicy = "strict"; DevicePolicy = "strict";
LockPersonality = true; LockPersonality = true;
@@ -177,19 +164,30 @@ in {
ProtectProc = "invisible"; ProtectProc = "invisible";
ProtectSystem = "full"; ProtectSystem = "full";
RemoveIPC = true; RemoveIPC = true;
RestrictAddressFamilies = ["AF_INET" "AF_INET6" "AF_UNIX"]; RestrictAddressFamilies = [
"AF_INET"
"AF_INET6"
"AF_UNIX"
];
RestrictNamespaces = true; RestrictNamespaces = true;
RestrictRealtime = true; RestrictRealtime = true;
RestrictSUIDSGID = true; RestrictSUIDSGID = true;
SystemCallArchitectures = "native"; SystemCallArchitectures = "native";
SystemCallFilter = ["@system-service" "~@privileged"]; SystemCallFilter = [
"@system-service"
"~@privileged"
];
}; };
postStart = lib.mkBefore '' postStart = let
until ${lib.getBin pkgs.curl}/bin/curl -s -o /dev/null http://${bindAddr}/ping; do bindAddr =
sleep 1; (lib.optionalString (lib.hasPrefix ":" cfg.listenAddress) "127.0.0.1") + cfg.listenAddress;
done in
''; lib.mkBefore ''
until ${lib.getBin pkgs.curl}/bin/curl -s -o /dev/null http://${bindAddr}/ping; do
sleep 1;
done
'';
}; };
}; };
} }

File diff suppressed because it is too large Load Diff

View File

@@ -13,11 +13,10 @@
# https://victoriametrics.io/docs/victoriametrics/latest/configuration/configuration/ # https://victoriametrics.io/docs/victoriametrics/latest/configuration/configuration/
services.my-victoriametrics = { services.my-victoriametrics = {
enable = true; enable = true;
listenAddress = "127.0.0.1"; listenAddress = "127.0.0.1:9090";
port = 9090; retentionPeriod = "30d";
retentionTime = "30d";
extraFlags = [ extraOptions = [
# Allowed percent of system memory VictoriaMetrics caches may occupy. # Allowed percent of system memory VictoriaMetrics caches may occupy.
"-memory.allowedPercent=50" "-memory.allowedPercent=50"
]; ];
@@ -26,87 +25,89 @@
# specifies a set of targets and parameters describing how to scrape metrics from them. # specifies a set of targets and parameters describing how to scrape metrics from them.
# https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config # https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config
scrapeConfigs = prometheusConfig = {
[ scrape_configs =
# --- Homelab Applications --- # [
# --- Homelab Applications --- #
{ {
job_name = "dnsmasq-exporter"; job_name = "dnsmasq-exporter";
scrape_interval = "30s"; scrape_interval = "30s";
metrics_path = "/metrics"; metrics_path = "/metrics";
static_configs = [ static_configs = [
{ {
targets = ["${myvars.networking.hostsAddr.suzi.ipv4}:9153"]; targets = ["${myvars.networking.hostsAddr.suzi.ipv4}:9153"];
labels.type = "app"; labels.type = "app";
labels.app = "dnsmasq"; labels.app = "dnsmasq";
labels.host = "suzi"; labels.host = "suzi";
} }
]; ];
} }
{ {
job_name = "v2ray-exporter"; job_name = "v2ray-exporter";
scrape_interval = "30s"; scrape_interval = "30s";
metrics_path = "/metrics"; metrics_path = "/metrics";
static_configs = [ static_configs = [
{ {
targets = ["${myvars.networking.hostsAddr.aquamarine.ipv4}:9153"]; targets = ["${myvars.networking.hostsAddr.aquamarine.ipv4}:9153"];
labels.type = "app"; labels.type = "app";
labels.app = "v2ray"; labels.app = "v2ray";
labels.host = "aquamarine"; labels.host = "aquamarine";
} }
]; ];
} }
{ {
job_name = "postgres-exporter"; job_name = "postgres-exporter";
scrape_interval = "30s"; scrape_interval = "30s";
metrics_path = "/metrics"; metrics_path = "/metrics";
static_configs = [ static_configs = [
{ {
targets = ["${myvars.networking.hostsAddr.aquamarine.ipv4}:9187"]; targets = ["${myvars.networking.hostsAddr.aquamarine.ipv4}:9187"];
labels.type = "app"; labels.type = "app";
labels.app = "postgresql"; labels.app = "postgresql";
labels.host = "aquamarine"; labels.host = "aquamarine";
} }
]; ];
} }
{ {
job_name = "sftpgo-embedded-exporter"; job_name = "sftpgo-embedded-exporter";
scrape_interval = "30s"; scrape_interval = "30s";
metrics_path = "/metrics"; metrics_path = "/metrics";
static_configs = [ static_configs = [
{ {
targets = ["${myvars.networking.hostsAddr.aquamarine.ipv4}:10000"]; targets = ["${myvars.networking.hostsAddr.aquamarine.ipv4}:10000"];
labels.type = "app"; labels.type = "app";
labels.app = "sftpgo"; labels.app = "sftpgo";
labels.host = "aquamarine"; labels.host = "aquamarine";
} }
]; ];
} }
] ]
# --- Hosts --- # # --- Hosts --- #
++ ( ++ (
lib.attrsets.foldlAttrs lib.attrsets.foldlAttrs
(acc: hostname: addr: (acc: hostname: addr:
acc acc
++ [ ++ [
{ {
job_name = "node-exporter-${hostname}"; job_name = "node-exporter-${hostname}";
scrape_interval = "30s"; scrape_interval = "30s";
metrics_path = "/metrics"; metrics_path = "/metrics";
static_configs = [ static_configs = [
{ {
# All my NixOS hosts. # All my NixOS hosts.
targets = ["${addr.ipv4}:9100"]; targets = ["${addr.ipv4}:9100"];
labels.type = "node"; labels.type = "node";
labels.host = hostname; labels.host = hostname;
} }
]; ];
} }
]) ])
[] []
myvars.networking.hostsAddr myvars.networking.hostsAddr
); );
};
}; };
services.vmalert = { services.vmalert = {