Skip to content

Commit 6c5e850

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 8f46940 commit 6c5e850

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

batchspawner/batchspawner.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -176,8 +176,16 @@ def _req_keepvars_default(self):
176176
help="Command to connect to running batch job and forward the port "
177177
"of the running notebook to the Hub. If empty, direct connectivity is assumed. "
178178
"Uses self.job_id as {job_id} and the self.port as {port}."
179+
"If {rport} is used in this string, it is set to self.port, "
180+
"and a new random self.port is chosen locally and used as {port}."
181+
"This is useful e.g. for SSH port forwarding."
179182
).tag(config=True)
180183

184+
rport = Integer(0,
185+
help="Remote port of notebook, will be set if it differs from the self.port."
186+
"This is set by connect_to_job() if needed."
187+
)
188+
181189
# Raw output of job submission command unless overridden
182190
job_id = Unicode()
183191

@@ -208,12 +216,19 @@ def cmd_formatted_for_batch(self):
208216

209217
async def connect_to_job(self):
210218
"""This command ensures the port of the singleuser server is reachable from the
211-
Batchspawner machine. By default, it does nothing, i.e. direct connectivity
212-
is assumed.
219+
Batchspawner machine. Only called if connect_to_job_cmd is set.
220+
If the template string connect_to_job_cmd contains {rport},
221+
a new random self.port is chosen locally (useful e.g. for SSH port forwarding).
213222
"""
214223
subvars = self.get_req_subvars()
215224
subvars['job_id'] = self.job_id
216-
subvars['port'] = self.port
225+
if '{rport}' in self.connect_to_job_cmd:
226+
self.rport = self.port
227+
self.port = random_port()
228+
subvars['rport'] = self.rport
229+
subvars['port'] = self.port
230+
else:
231+
subvars['port'] = self.port
217232
cmd = ' '.join((format_template(self.exec_prefix, **subvars),
218233
format_template(self.connect_to_job_cmd, **subvars)))
219234
await self.run_background_command(cmd)

0 commit comments

Comments
 (0)