Skip to content

Commit d778f08

Browse files
committed
BatchSpawnerBase: Extend connect_to_job for port forwarding approaches.
This allows to use {rport} inside the connect_to_job_cmd. If this is done, {port} is set to a random_port chosen locally on the Hub, and {rport} is set to the original remote port. This is useful e.g. for SSH port forwarding. If this is used, the {rport} of the notebook is saved into a new class variable in case it will be needed again.
1 parent 78ad46a commit d778f08

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

batchspawner/batchspawner.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from jupyterhub.spawner import Spawner
3333
from traitlets import Integer, Unicode, Float, Dict, default
3434

35+
from jupyterhub.utils import random_port
3536
from jupyterhub.spawner import set_user_setuid
3637

3738

@@ -190,8 +191,16 @@ def _req_keepvars_default(self):
190191
help="Command to connect to running batch job and forward the port "
191192
"of the running notebook to the Hub. If empty, direct connectivity is assumed. "
192193
"Uses self.job_id as {job_id} and the self.port as {port}."
194+
"If {rport} is used in this string, it is set to self.port, "
195+
"and a new random self.port is chosen locally and used as {port}."
196+
"This is useful e.g. for SSH port forwarding."
193197
).tag(config=True)
194198

199+
rport = Integer(0,
200+
help="Remote port of notebook, will be set if it differs from the self.port."
201+
"This is set by connect_to_job() if needed."
202+
)
203+
195204
# Raw output of job submission command unless overridden
196205
job_id = Unicode()
197206

@@ -223,12 +232,19 @@ def cmd_formatted_for_batch(self):
223232

224233
async def connect_to_job(self):
225234
"""This command ensures the port of the singleuser server is reachable from the
226-
Batchspawner machine. By default, it does nothing, i.e. direct connectivity
227-
is assumed.
235+
Batchspawner machine. Only called if connect_to_job_cmd is set.
236+
If the template string connect_to_job_cmd contains {rport},
237+
a new random self.port is chosen locally (useful e.g. for SSH port forwarding).
228238
"""
229239
subvars = self.get_req_subvars()
230240
subvars['job_id'] = self.job_id
231-
subvars['port'] = self.port
241+
if '{rport}' in self.connect_to_job_cmd:
242+
self.rport = self.port
243+
self.port = random_port()
244+
subvars['rport'] = self.rport
245+
subvars['port'] = self.port
246+
else:
247+
subvars['port'] = self.port
232248
cmd = ' '.join((format_template(self.exec_prefix, **subvars),
233249
format_template(self.connect_to_job_cmd, **subvars)))
234250
await self.run_background_command(cmd)

0 commit comments

Comments
 (0)