|
32 | 32 | from jupyterhub.spawner import Spawner |
33 | 33 | from traitlets import Integer, Unicode, Float, Dict, default |
34 | 34 |
|
| 35 | +from jupyterhub.utils import random_port |
35 | 36 | from jupyterhub.spawner import set_user_setuid |
36 | 37 |
|
37 | 38 |
|
@@ -190,8 +191,16 @@ def _req_keepvars_default(self): |
190 | 191 | help="Command to connect to running batch job and forward the port " |
191 | 192 | "of the running notebook to the Hub. If empty, direct connectivity is assumed. " |
192 | 193 | "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." |
193 | 197 | ).tag(config=True) |
194 | 198 |
|
| 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 | + |
195 | 204 | # Raw output of job submission command unless overridden |
196 | 205 | job_id = Unicode() |
197 | 206 |
|
@@ -223,12 +232,19 @@ def cmd_formatted_for_batch(self): |
223 | 232 |
|
224 | 233 | async def connect_to_job(self): |
225 | 234 | """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). |
228 | 238 | """ |
229 | 239 | subvars = self.get_req_subvars() |
230 | 240 | 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 |
232 | 248 | cmd = ' '.join((format_template(self.exec_prefix, **subvars), |
233 | 249 | format_template(self.connect_to_job_cmd, **subvars))) |
234 | 250 | await self.run_background_command(cmd) |
|
0 commit comments