From 1a8b4811f7fb52f5375c4fd328f27d258b988867 Mon Sep 17 00:00:00 2001 From: Astro Date: Mon, 12 Apr 2021 23:32:21 +0200 Subject: [PATCH] nix/nixos-module/collectd: add dhcpcount.rb --- .../{collectd.nix => collectd/default.nix} | 16 ++++++++ nix/nixos-module/collectd/dhcpcount.rb | 39 +++++++++++++++++++ nix/nixos-module/default.nix | 2 +- 3 files changed, 56 insertions(+), 1 deletion(-) rename nix/nixos-module/{collectd.nix => collectd/default.nix} (70%) create mode 100644 nix/nixos-module/collectd/dhcpcount.rb diff --git a/nix/nixos-module/collectd.nix b/nix/nixos-module/collectd/default.nix similarity index 70% rename from nix/nixos-module/collectd.nix rename to nix/nixos-module/collectd/default.nix index b31803c..9851699 100644 --- a/nix/nixos-module/collectd.nix +++ b/nix/nixos-module/collectd/default.nix @@ -50,6 +50,22 @@ in hddtemp = ""; sensors = ""; thermal = ""; + }) (lib.optionalAttrs config.services.dhcpd4.enable { + exec = + let + maxTimeout = builtins.foldl' (maxTimeout: net: + let + dhcpConf = config.site.net.${net}.dhcp; + in + if dhcpConf != null && + dhcpConf.server == hostName && + dhcpConf.time > maxTimeout + then dhcpConf.time + else maxTimeout + ) 180 (builtins.attrNames config.site.net); + in '' + Exec "collectd" "${pkgs.ruby}/bin/ruby" "${./dhcpcount.rb}" "${toString maxTimeout}" + ''; }) ]; }; } diff --git a/nix/nixos-module/collectd/dhcpcount.rb b/nix/nixos-module/collectd/dhcpcount.rb new file mode 100644 index 000000000..22062e8 --- /dev/null +++ b/nix/nixos-module/collectd/dhcpcount.rb @@ -0,0 +1,39 @@ +#!/usr/bin/env ruby + +require 'date' + +INTERVAL = 10 +TIMEOUT = ARGV[0].to_i +hostname = `hostname`.strip +STDOUT.sync = true + +loop do + seen = {} + count = 0 + + addr = nil + starts = nil + + IO::readlines("/var/lib/dhcp/dhcpd.leases").each do |line| + if line =~ /^lease (.+) \{/ + addr = $1 + + starts = nil + elsif line =~ /starts \d+ (.+?);/ + starts = DateTime.parse($1).to_time + elsif line =~ /^\}/ + now = Time.now + if starts and + now >= starts and now < starts + TIMEOUT + + unless seen[addr] + count += 1 + seen[addr] = true + end + end + end + end + puts "PUTVAL \"#{hostname}/exec-dhcpd/current_sessions-leases\" interval=#{INTERVAL} N:#{count}" + + sleep INTERVAL +end diff --git a/nix/nixos-module/default.nix b/nix/nixos-module/default.nix index dfd1910..4dbc6b5 100644 --- a/nix/nixos-module/default.nix +++ b/nix/nixos-module/default.nix @@ -13,7 +13,7 @@ in { ../lib/config/options.nix ./defaults.nix ./network.nix - ./collectd.nix + ./collectd ] ++ optionals (hostConfig.role == "server") [ ./server/lxc-containers.nix