Skip to content

Instantly share code, notes, and snippets.

@mmerickel
Last active May 11, 2020 01:20
Show Gist options
  • Select an option

  • Save mmerickel/26e85ecc33705f4b325626bb46122f0a to your computer and use it in GitHub Desktop.

Select an option

Save mmerickel/26e85ecc33705f4b325626bb46122f0a to your computer and use it in GitHub Desktop.

Revisions

  1. mmerickel revised this gist May 11, 2020. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions tunnel.sh
    Original file line number Diff line number Diff line change
    @@ -31,7 +31,7 @@ is_running() {

    start() {
    info "starting tunnel ..."
    rm -f docker.sock
    rm -f "$SOCKET_PATH" "$CONTROL_PATH"
    ssh $SSH_TRACE \
    -M -S "$CONTROL_PATH" -o ControlPersist=no \
    -fNT -L "$SOCKET_PATH:/var/run/docker.sock" \
    @@ -56,8 +56,8 @@ sub_stop() {
    if ! is_running; then
    abort "tunnel is not running"
    fi
    rm -f "$SOCKET_PATH"
    ssh $SSH_TRACE -S "$CONTROL_PATH" -O exit "$SSH_TARGET"
    rm -f "$SOCKET_PATH" "$CONTROL_PATH"
    }

    sub_check() {
  2. mmerickel created this gist May 10, 2020.
    87 changes: 87 additions & 0 deletions tunnel.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,87 @@
    #!/usr/bin/env bash
    set -eEo pipefail

    SSH_TRACE=
    [[ "$TRACE" = "1" ]] && set -x && SSH_TRACE="-vvv"

    SSH_TARGET=merickel.org
    CONTROL_PATH=$(pwd)/.ssh-${SSH_TARGET}
    SOCKET_PATH=$(pwd)/docker.sock

    log() {
    echo "$@" 1>&2
    }

    info() {
    log "[info]" "$@"
    }

    debug() {
    log "[debug]" "$@"
    }

    abort() {
    log "[error]" "$@"
    exit 1
    }

    is_running() {
    ssh -S "$CONTROL_PATH" -O check "$SSH_TARGET" > /dev/null 2>&1
    }

    start() {
    info "starting tunnel ..."
    rm -f docker.sock
    ssh $SSH_TRACE \
    -M -S "$CONTROL_PATH" -o ControlPersist=no \
    -fNT -L "$SOCKET_PATH:/var/run/docker.sock" \
    "$SSH_TARGET"
    debug "tunnel started"
    }

    start_if_needed() {
    if ! is_running; then
    start
    fi
    }

    sub_start() {
    if is_running; then
    abort "tunnel is already running"
    fi
    start
    }

    sub_stop() {
    if ! is_running; then
    abort "tunnel is not running"
    fi
    rm -f "$SOCKET_PATH"
    ssh $SSH_TRACE -S "$CONTROL_PATH" -O exit "$SSH_TARGET"
    }

    sub_check() {
    if is_running; then
    info "tunnel is running"
    else
    abort "tunnel is not running"
    fi
    }

    sub_env() {
    start_if_needed
    echo "export DOCKER_HOST=unix://$SOCKET_PATH"
    }

    sub_exec() {
    # shellcheck source=/dev/null
    source <(sub_env)
    exec "$@"
    }

    subcommand=$1
    shift
    if ! declare -f "sub_$subcommand" > /dev/null 2>&1; then
    abort "\"$subcommand\" is not a valid subcommand"
    fi
    "sub_${subcommand}" "$@"