Skip to content

Instantly share code, notes, and snippets.

@joehealy
Created November 14, 2017 01:29
Show Gist options
  • Select an option

  • Save joehealy/78b4c2939ac1a44ac026a8036ebda0d7 to your computer and use it in GitHub Desktop.

Select an option

Save joehealy/78b4c2939ac1a44ac026a8036ebda0d7 to your computer and use it in GitHub Desktop.

Revisions

  1. joehealy created this gist Nov 14, 2017.
    82 changes: 82 additions & 0 deletions auto-rollback.nix
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,82 @@
    {pkgs, lib, ... }:
    let

    pinRollback = pkgs.writeShellScriptBin "ar-pin-rollback"
    ''
    CURVERSION=$(nix-env --list-generations -p /nix/var/nix/profiles/system | grep -Po '([0-9]+)(?=\s+[0-9 -]+ [0-9 :]+\s*\(current\))')
    echo Setting /nix/var/nix/rollback-version to $CURVERSION
    echo $CURVERSION > /nix/var/nix/rollback-version
    '';


    showGenerations = pkgs.writeShellScriptBin "ar-show-generations"
    ''
    nix-env --list-generations -p /nix/var/nix/profiles/system
    '';

    showRollback = pkgs.writeShellScriptBin "ar-show-rollback"
    ''
    cat /nix/var/nix/rollback-version
    '';


    in

    {

    systemd.services.ar-rollback = {

    path = [ pkgs.nix ?????.nixos-rebuild ];

    environment = {
    HOME="/root";

    };

    script = ''
    CURVERSION=$(nix-env --list-generations -p /nix/var/nix/profiles/system | grep -Po '([0-9]+)(?=\s+[0-9 -]+ [0-9 :]+\s*\(current\))')
    CURVERSIONTIME=$(date -d "$(nix-env --list-generations -p /nix/var/nix/profiles/system | grep -Po '(([0-9-]+ [0-9 :]+))(?=\s*\(current\))')" +%s)
    TRIGGERTIME=$(date -d -20minutes +%s)
    if [ ! -f /nix/var/nix/rollback-version ]; then
    echo $CURVERSION > /nix/var/nix/rollback-version
    fi
    ROLLBACKVERSION=$(cat /nix/var/nix/rollback-version)
    if [[ "$CURVERSION" > `cat /nix/var/nix/rollback-version` ]] ; then
    if [ `nix-env --list-generations -p /nix/var/nix/profiles/system | wc -l` > 0 ]; then
    if [ $CURVERSIONTIME -lt $TRIGGERTIME ]; then
    echo "Rolling back from $CURVERSION towards $ROLLBACKVERSION"
    nixos-rebuild switch --rollback
    else
    echo "Not yet rolling back from $CURVERSION towards $ROLLBACKVERSION"
    fi
    fi
    fi
    '';

    };


    systemd.timers.ar-rollback = {
    timerConfig = { OnCalendar = "*:0/5";
    Unit = "ar-rollback.service";
    AccuracySec = "1sec";
    };
    wantedBy = [ "timers.target" ];
    };


    environment.systemPackages = [
    pinRollback
    showGenerations
    showRollback

    ];


    }