Skip to content

Instantly share code, notes, and snippets.

@CPlusPatch
Last active March 23, 2025 21:32
Show Gist options
  • Save CPlusPatch/5e8c5eac5e4567b0e3e4f9c630af3776 to your computer and use it in GitHub Desktop.
Save CPlusPatch/5e8c5eac5e4567b0e3e4f9c630af3776 to your computer and use it in GitHub Desktop.
{
config,
lib,
pkgs,
...
}:
with lib; let
cfg = config.services.randomProcessKiller;
in {
options.services.randomProcessKiller = {
enable = mkEnableOption "Random process killer service";
interval = mkOption {
type = types.str;
default = "hourly";
description = "Interval for killing random processes. Uses Systemd calendar syntax.";
example = "minutely";
};
randomDelaySec = mkOption {
type = types.int;
default = 30;
description = "Random delay in seconds to add to the timer.";
};
excludeProcesses = mkOption {
type = types.listOf types.str;
default = [];
description = "List of process names to exclude from random killing.";
example = ["sshd" "systemd" "nixos-rebuild"];
};
};
config = mkIf cfg.enable {
systemd.services.random-process-killer = {
description = "Kill a random process with SIGKILL";
serviceConfig = {
Type = "oneshot";
ExecStart = pkgs.writeScript "pid-roulette.sh" ''
# Get a list of all processes excluding kernel processes and the script itself
PROCESSES=$(ps -eo pid,cmd --no-headers | grep -v "kernel" | grep -v "random-process-killer" ${concatMapStrings (proc: " | grep -v \"${proc}\"") cfg.excludeProcesses} | awk '{print $1}')
# Convert the process list to an array
PROCESS_ARRAY=($PROCESSES)
# Check if there are any processes to kill
if [ ''${#PROCESS_ARRAY[@]} -eq 0 ]; then
echo "No eligible processes found to kill"
exit 0
fi
# Get a random index
RANDOM_INDEX=$(( $RANDOM % ''${#PROCESS_ARRAY[@]} ))
# Get the random PID
RANDOM_PID=''${PROCESS_ARRAY[$RANDOM_INDEX]}
# Get process info for logging
PROCESS_INFO=$(ps -p $RANDOM_PID -o cmd= 2>/dev/null || echo "unknown")
# Log the kill action (systemd will capture this in journal)
echo "Killing process $RANDOM_PID ($PROCESS_INFO)"
# Kill the random process with SIGKILL
kill -9 $RANDOM_PID
'';
# Run as root to have permissions to kill any process
User = "root";
# Ensure standard output is captured in journal
StandardOutput = "journal";
StandardError = "journal";
# Add syslog identifier for easier filtering
SyslogIdentifier = "random-process-killer";
};
# Don't restart the service if it fails
restartIfChanged = false;
};
systemd.timers.random-process-killer = {
description = "Timer for random process killer";
wantedBy = ["timers.target"];
timerConfig = {
OnCalendar = cfg.interval;
RandomizedDelaySec = toString cfg.randomDelaySec;
Persistent = true;
};
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment