Tangled infrastructure definitions in Nix

Compare changes

Choose any two refs to compare.

Changed files
+94
hosts
nixery
+94
hosts/nixery/services/docker-cleanup.nix
··· 1 + { config, pkgs, ... }: 2 + 3 + { 4 + systemd.services.docker-cleanup = { 5 + description = "Docker cleanup service - removes unused containers, networks, images, and volumes"; 6 + 7 + serviceConfig = { 8 + Type = "oneshot"; 9 + User = "root"; 10 + ExecStart = pkgs.writeShellScript "docker-cleanup" '' 11 + set -e 12 + 13 + echo "Starting Docker cleanup at $(date)" 14 + 15 + # remove containers running for 15+ minutes 16 + echo "Removing containers running for 15+ minutes..." 17 + CONTAINERS_TO_REMOVE=$(${pkgs.docker}/bin/docker ps --format "table {{.ID}}\t{{.RunningFor}}" --no-trunc | awk ' 18 + /minute/ { 19 + if ($2 >= 15) print $1 20 + } 21 + /hour/ { 22 + print $1 23 + } 24 + /day/ { 25 + print $1 26 + } 27 + /week/ { 28 + print $1 29 + } 30 + /month/ { 31 + print $1 32 + } 33 + /year/ { 34 + print $1 35 + } 36 + ') 37 + 38 + if [ -n "$CONTAINERS_TO_REMOVE" ]; then 39 + echo "Found containers to remove: $CONTAINERS_TO_REMOVE" 40 + echo "$CONTAINERS_TO_REMOVE" | xargs -r ${pkgs.docker}/bin/docker rm -f 41 + else 42 + echo "No containers running for 15+ minutes found" 43 + fi 44 + 45 + # remove stopped containers 46 + echo "Removing stopped containers..." 47 + ${pkgs.docker}/bin/docker container prune -f || true 48 + 49 + # remove unused networks (excluding default networks) 50 + echo "Removing unused networks..." 51 + ${pkgs.docker}/bin/docker network prune -f || true 52 + 53 + # remove unused images (dangling images only by default) 54 + echo "Removing dangling images..." 55 + ${pkgs.docker}/bin/docker image prune -f || true 56 + 57 + # remove unused volumes 58 + echo "Removing unused volumes..." 59 + ${pkgs.docker}/bin/docker volume prune -f || true 60 + 61 + echo "Docker cleanup completed at $(date)" 62 + ''; 63 + 64 + PrivateNetwork = false; # Needs network access for Docker 65 + ProtectSystem = "strict"; 66 + ProtectHome = true; 67 + NoNewPrivileges = true; 68 + 69 + # Logging 70 + StandardOutput = "journal"; 71 + StandardError = "journal"; 72 + }; 73 + 74 + # ensure docker is running before cleanup 75 + after = [ "docker.service" ]; 76 + requires = [ "docker.service" ]; 77 + 78 + # don't restart on failure 79 + restartIfChanged = false; 80 + }; 81 + 82 + # timer to run the cleanup service every n minutes 83 + systemd.timers.docker-cleanup = { 84 + description = "Timer for Docker cleanup service"; 85 + timerConfig = { 86 + OnCalendar = "*:0/15"; # run every 15 minutes 87 + Persistent = true; # persist timer across reboots 88 + WakeSystem = false; # run immediately if the system was powered off when timer should have run 89 + }; 90 + wantedBy = [ "timers.target" ]; 91 + }; 92 + 93 + virtualisation.docker.enable = true; 94 + }