start-jupyter 10.9 KB
Newer Older
1
2
#!/bin/bash
#
3
# Copyright 2020 Deutsches Klimarechenzentrum GmbH
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following
#    disclaimer in the documentation and/or other materials provided
#    with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# start-jupyter
#
# This script is intended to be used on your local workstation running
# Ubuntu, Fedora Linux or macOS (tested). Other Unix flavors may work
# as well. It allows you to start jupyter notebook or lab on one of
# DKRZ's mistral nodes. The script then opens a ssh tunnel to connect
# your local browser to jupyter.
#
40
# If you indicate an account with the -A option, the script will run
41
42
43
44
45
# jupyter in a job on dedicated resources. Otherwise jupyter uses a
# shared interactive node.
#
# In case of problems contact Mathis Rosenhauer <rosenhauer@dkrz.de>.
#
Sofiane Bendoukha's avatar
Sofiane Bendoukha committed
46
# 2020, Oct. 7, S. Bendoukha, added support for singularity containers.
47
# 2021, Apr. 14, S. Bendoukha, added option to specify frontend.
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

set -eufo pipefail

# Default settings
#
# You can change the settings here or override them with command line
# options.

# Project account code.
#
# Jupyter is started on the frontend if this is not set.
SJ_ACCTCODE=""

# LDAP username
#
# Specify your username on the frontend if it is not your local
# username.
SJ_USERNAME="$(id -un)"

# Jupyter command
#
# You could change this to lab for example
SJ_COMMAND="notebook"

# Generate debugging output if set to 1
SJ_DEBUG=0

# Session run time in minutes
SJ_RUNTIME=240

# Ntasks for job
SJ_NTASKS=1

# Partition for job
SJ_PARTITION=shared

# Incfile
#
# If indicated, this file will be sourced prior to running jupyter
# notebook. It has to be located on mistral. Set up the environment
88
89
# for starting the correct jupyter here. If no SJ_INCFILE is given,
# the module python3/unstable is loaded.
90
91
92
93
94
95
SJ_INCFILE=""

# Frontend host
#
# Must be directly accessible from client. The frontend and the node
# where jupyter is running need a shared home file system.
96
SJ_FRONTEND_HOST="mistralpp.dkrz.de"
97

98
99
100
101
102
# Image
#
# start the jupyter notebook in a singularity container from a given 
# image name.
SJ_IMAGE=""
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

function clean_up () {
    trap - ERR EXIT
    set +e

    echo
    if [[ -n ${SJ_ACCTCODE} ]]; then
        if [[ -n ${jupyter_id:-} ]]; then
            echo "Removing job ${jupyter_id}."
            ssh_frontend "scancel -Q ${jupyter_id}"
        else
            echo "Job ID not available. Make sure the jupyter " \
                 "job is not running!"
            ssh_frontend "squeue -u ${SJ_USERNAME}"
        fi
    else
        if [[ -n ${jupyter_id:-} ]]; then
            echo "Killing jupyter process ${jupyter_id}..."
            ssh_frontend "kill ${jupyter_id}"
        fi
    fi

    ssh_frontend "rm -f ${jupyter_log}"
    ssh_frontend "" "-O exit"
    rmdir "${ssh_socket_dir}"

    exit
}

function usage () {
    cat <<EOF
Usage: $(basename "$0") [OPTION]

Available values for OPTION include:

  -A acctcode    start a job with acctcode
  -c command     invoke jupyter with command
  -d             check for presence of jupyter
141
  -f system      mistral, vader
142
143
144
  -i file        source file prior to running jupyter
  -n ntasks      request ntasks tasks for job
  -p partition   run job on partition
145
  -s image       singularity image
146
147
  -t time        job runtime
  -u username    use username for login
148
  
149
150
151
152
153
154

EOF
}

function parse_options () {
    local option
155
    while getopts 'A:c:di:f:n:p:t:u:s:' option; do
156
157
158
159
160
161
162
        case ${option} in
            A) SJ_ACCTCODE="$OPTARG"
               ;;
            c) SJ_COMMAND="$OPTARG"
               ;;
            d) SJ_DEBUG=1
               ;;
163
164
            f) SJ_FRONTEND_HOST="$OPTARG"
               ;;
165
166
167
168
169
170
            i) SJ_INCFILE="$OPTARG"
               ;;
            n) SJ_NTASKS="$OPTARG"
               ;;
            p) SJ_PARTITION="$OPTARG"
               ;;
171
172
            s) SJ_IMAGE="$OPTARG"
               ;;
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
            t) SJ_RUNTIME="$OPTARG"
               ;;
            u) SJ_USERNAME="$OPTARG"
               ;;
            ?) usage
            exit 1
            ;;
        esac
    done
    readonly SJ_ACCTCODE
    readonly SJ_COMMAND
    readonly SJ_DEBUG
    readonly SJ_INCFILE
    readonly SJ_NTASKS
    readonly SJ_PARTITION
    readonly SJ_RUNTIME
    readonly SJ_USERNAME
190
    readonly SJ_IMAGE
191
    readonly SJ_FRONTEND_HOST
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
}

function ssh_frontend () {
    # Run command on frontend with ssh
    local command="$1"
    local extra_options="${2:-}"
    local options
    options="${extra_options} -o ForwardX11=no \
            -o ControlPath=${ssh_socket_dir}/control:%h:%p:%r"
    ssh ${options} "${SJ_USERNAME}@${SJ_FRONTEND_HOST}" "${command}"
}

function source_incfile() {
    # Add sourcing of incfile to commandline if an incfile was
    # specified
    local commandline="$1"
    if [[ -n ${SJ_INCFILE} ]]; then
        local incfile="${SJ_INCFILE}"
        if [[ ${incfile:0:1} != "/" ]]; then
            incfile="\${HOME}/${incfile}"
        fi
        commandline="source ${incfile}; ${commandline}"
214
    else
215
        commandline="module use /sw/spack-rhel6/spack/modules/linux-rhel6-haswell/; module load python3/unstable; ${commandline}"
216
217
218
219
220
221
222
223
224
    fi
    echo "${commandline}"
}

function which_jupyter() {
    echo "Looking for Jupyter."
    local which
    which="$(source_incfile "which jupyter")"
    ssh_frontend "/bin/bash -lc \"${which}\""
225
}  
226
227
228
229

function assemble_commandline () {
    local logfile="$1"

230
    local commandline="jupyter ${SJ_COMMAND} --no-browser 2>> ${logfile}" 
231
232
233
234
    # If we are not running a job, we have to perform our own scheduling
    if [[ -z ${SJ_ACCTCODE} ]]; then
        commandline="nohup ${commandline} > /dev/null & echo \$!"
    fi
235
236
237
    if [[ -n ${SJ_IMAGE} ]]; then
        commandline="singularity exec ${SJ_IMAGE} ${commandline}"
    fi 
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
    commandline="$(source_incfile "${commandline}")"
    echo "${commandline}"
}

function submit_jupyter_job () {
    local commandline="$1"
    local logfile="$2"

    ssh_frontend "sbatch" <<EOF
#!/bin/bash -l
#SBATCH --job-name=Jupyter
#SBATCH --partition=${SJ_PARTITION}
#SBATCH --ntasks=${SJ_NTASKS}
#SBATCH --time=${SJ_RUNTIME}
#SBATCH --account=${SJ_ACCTCODE}
#SBATCH --output=/dev/null
#SBATCH --parsable
#SBATCH --dkrzepilog=0
cd \${HOME}
echo "NODE:\${SLURM_JOB_NODELIST}" > ${logfile}
${commandline}
EOF
}

function run_jupyter () {
    local logfile="$1"

    local commandline
    commandline="$(assemble_commandline "${jupyter_log}")"
    # Run commandline in job or directly on frontend
    if [[ -n ${SJ_ACCTCODE} ]]; then
        submit_jupyter_job "${commandline}" "${logfile}"
    else
        ssh_frontend "/bin/bash -ls" <<< "${commandline}"
    fi
}

function extract_from_logs () {
    local pattern="$1"
    local haystack="$2"
    ssh_frontend "/bin/bash -s" <<EOF
while [[ -z \${needle} ]]; do
    sleep 1
    if [[ -f ${haystack} ]]; then
        needle="\$(grep -Pom 1 "${pattern}" "${haystack}")"
    fi
    printf "." >&2
done
printf "\n" >&2
echo "\${needle}"
EOF
}

function get_jupyter_node () {
    local logfile="$1"

    if [[ -n ${SJ_ACCTCODE} ]]; then
        printf "Waiting for job to start" >&2
        extract_from_logs "NODE:\K\w+" "${logfile}"
    else
298
        ssh_frontend "hostname"
299
300
301
302
303
304
305
306
307
    fi
}

function open_tunnel () {
    local node="$1"
    local port="$2"

    if [[ -n ${SJ_ACCTCODE} ]]; then
        # Tunnel to notebook in job needs jump host since nodes
308
309
310
311
312
313
314
315
316
317
        # usually have no direct external access. Unfortunately, ssh
        # doesn't seem to support connection sharing for the jump host
        if ! ssh -o ForwardX11=no \
               -o StrictHostKeyChecking=accept-new \
               -J "${SJ_USERNAME}@${SJ_FRONTEND_HOST}" \
               -L "${port}:localhost:${port}" \
               -Nf \
               "${SJ_USERNAME}@${node}"; then
            echo "Please consider updating your local ssh client!"
            ssh -o ForwardX11=no \
318
                -o StrictHostKeyChecking=ask \
319
320
321
322
323
                -o ProxyCommand="ssh ${SJ_USERNAME}@${SJ_FRONTEND_HOST} nc ${node} 22" \
                -L "${port}:localhost:${port}" \
                -Nf \
                "${SJ_USERNAME}@${node}"
        fi
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    else
        ssh_frontend "" "-O forward -L${port}:localhost:${port}"
    fi
}

function show_url() {
    local url="$1"

    echo "Open the following URL with your browser"
    echo "${url}"
}

function launch_browser() {
    local url="$1"

    case "$(uname -s)" in
        Darwin)
            open "${url}" || show_url "${url}"
            ;;
        Linux)
344
            case "$(uname -a)" in
345
                *[Mm]icrosoft*|*WSL*)
346
347
348
349
350
351
                    cmd.exe /c start "${url}" || show_url "${url}"
                    ;;
                *)
                    xdg-open "${url}" || show_url "${url}"
                    ;;
            esac
352
353
354
355
356
357
358
359
360
361
362
363
364
            ;;
        *)
            show_url "${url}"
            ;;
    esac
}

function main () {
    parse_options "$@"
    trap clean_up INT QUIT TERM ERR EXIT

    echo "Establishing ssh master connection."
    # Set up control master for connection sharing
365
    mkdir -p "${HOME}/.ssh"
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
    ssh_socket_dir="$(mktemp -d "${HOME}/.ssh/socket.XXXXX")"
    ssh_frontend "" "-MNf"

    # Create unique output file for jupyter notebook
    jupyter_log="$(ssh_frontend "mkdir -p \${HOME}/.jupyter \
                                && mktemp \${HOME}/.jupyter/jupyter.XXXXX")"
    ssh_frontend "chmod 600 ${jupyter_log}"

    # Check for jupyter
    [[ ${SJ_DEBUG} == 1 ]] && which_jupyter

    jupyter_id="$(run_jupyter "${jupyter_log}")"
    local node
    node="$(get_jupyter_node "${jupyter_log}")"

    # Get notebook url and token from output
    printf "Starting jupyter server" >&2
    local url
    url="$(extract_from_logs "^.*\Khttp://localhost:.+" "${jupyter_log}")"

    local port
    port=${url#*t:}
    port=${port%%/*}

    open_tunnel "${node}" "${port}"
    echo "Established tunnel to ${node}:${port}."

    launch_browser "${url}"
    echo "Press Ctrl-C to stop jupyter and shut down tunnel."

    sleep 604800
}

main "$@"