From 11c4c4ae54bbef647358d2b6d6c3ddf0457f81f7 Mon Sep 17 00:00:00 2001
From: Eelco Dolstra <eelco.dolstra@logicblox.com>
Date: Tue, 18 Mar 2014 11:36:03 +0100
Subject: [PATCH] =?UTF-8?q?Add=20command=20=E2=80=98nixos-container-shell?=
 =?UTF-8?q?=E2=80=99=20for=20logging=20into=20a=20container?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 nixos/modules/virtualisation/containers.nix | 54 +++++++++++++++++++++
 1 file changed, 54 insertions(+)

diff --git a/nixos/modules/virtualisation/containers.nix b/nixos/modules/virtualisation/containers.nix
index ff17fcc1221d..28ee78e3fcce 100644
--- a/nixos/modules/virtualisation/containers.nix
+++ b/nixos/modules/virtualisation/containers.nix
@@ -14,6 +14,58 @@ let
     installPhase = "true";
   };
 
+  nixos-container-shell = pkgs.writeScriptBin "nixos-container-shell"
+    ''
+      #! ${pkgs.bash}/bin/sh -e
+
+      usage() {
+        echo "Usage: $0 <container-name>" >&2
+        echo "       $0 (-r|--root-shell) <container-name>" >&2
+      }
+
+      args="`getopt --options 'r' -l help -- "$@"`"
+      eval "set -- $args"
+      rootShell=
+      while [ $# -gt 0 ]; do
+        case "$1" in
+          (--help) usage; exit 0;;
+          (-r|--root-shell) rootShell=1;;
+          (--) shift; break;;
+          (*) break;;
+        esac
+        shift
+      done
+
+      container="$1"
+      if [ -z "$container" ]; then
+        usage
+        exit 1
+      fi
+      shift
+
+      root="/var/lib/containers/$container"
+      if ! [ -d "$root" ]; then
+        echo "$0: container ‘$container’ does not exist" >&2
+        exit 1
+      fi
+
+      if [ -n "$rootShell" ]; then
+        socket="$root/var/lib/root-shell.socket"
+      else
+        socket="$root/var/lib/login.socket"
+      fi
+      if ! [ -S "$socket" ]; then
+        echo "$0: socket ‘$socket’ does not exist" >&2
+        exit 1
+      fi
+
+      if [ -n "$rootShell" ]; then
+        exec ${pkgs.socat}/bin/socat "unix:$socket" -
+      else
+        exec ${pkgs.socat}/bin/socat "unix:$socket" -,echo=0,raw
+      fi
+    '';
+
 in
 
 {
@@ -246,5 +298,7 @@ in
         ${cfg.localAddress} ${name}.containers
       '') config.systemd.containers);
 
+    environment.systemPackages = optional (config.systemd.containers != {}) nixos-container-shell;
+
   };
 }