-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathconfig.py
More file actions
253 lines (211 loc) · 8.1 KB
/
config.py
File metadata and controls
253 lines (211 loc) · 8.1 KB
1
2
3
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
40
41
42
43
44
45
46
47
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""
Traitlets based configuration for jupyter_server_proxy
"""
from notebook.utils import url_path_join as ujoin
from traitlets import Bool, Dict, List, Unicode, Union, default
from traitlets.config import Configurable
from .handlers import SuperviseAndProxyHandler, AddSlashHandler
import pkg_resources
from collections import namedtuple
from .utils import call_with_asked_args
try:
# Traitlets >= 4.3.3
from traitlets import Callable
except ImportError:
from .utils import Callable
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port, mappath):
"""
Create a SuperviseAndProxyHandler subclass with given parameters
"""
# FIXME: Set 'name' properly
class _Proxy(SuperviseAndProxyHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
self.proxy_base = name
self.absolute_url = absolute_url
self.requested_port = port
self.mappath = mappath
@property
def process_args(self):
return {
'port': self.port,
'base_url': self.base_url,
}
def _render_template(self, value):
args = self.process_args
if type(value) is str:
return value.format(**args)
elif type(value) is list:
return [self._render_template(v) for v in value]
elif type(value) is dict:
return {
self._render_template(k): self._render_template(v)
for k, v in value.items()
}
else:
raise ValueError('Value of unrecognized type {}'.format(type(value)))
def get_cmd(self):
if callable(command):
return self._render_template(call_with_asked_args(command, self.process_args))
else:
return self._render_template(command)
def get_env(self):
if callable(environment):
return self._render_template(call_with_asked_args(environment, self.process_args))
else:
return self._render_template(environment)
def get_timeout(self):
return timeout
return _Proxy
def get_entrypoint_server_processes():
sps = []
for entry_point in pkg_resources.iter_entry_points('jupyter_serverproxy_servers'):
sps.append(
make_server_process(entry_point.name, entry_point.load()())
)
return sps
def make_handlers(base_url, server_processes):
"""
Get tornado handlers for registered server_processes
"""
handlers = []
for sp in server_processes:
handler = _make_serverproxy_handler(
sp.name,
sp.command,
sp.environment,
sp.timeout,
sp.absolute_url,
sp.port,
sp.mappath,
)
handlers.append((
ujoin(base_url, sp.name, r'(.*)'), handler, dict(state={}),
))
handlers.append((
ujoin(base_url, sp.name), AddSlashHandler
))
return handlers
LauncherEntry = namedtuple('LauncherEntry', ['enabled', 'icon_path', 'title'])
ServerProcess = namedtuple('ServerProcess', [
'name', 'command', 'environment', 'timeout', 'absolute_url', 'port', 'mappath', 'launcher_entry'])
def make_server_process(name, server_process_config):
le = server_process_config.get('launcher_entry', {})
return ServerProcess(
name=name,
command=server_process_config['command'],
environment=server_process_config.get('environment', {}),
timeout=server_process_config.get('timeout', 5),
absolute_url=server_process_config.get('absolute_url', False),
port=server_process_config.get('port', 0),
mappath=server_process_config.get('mappath', {}),
launcher_entry=LauncherEntry(
enabled=le.get('enabled', True),
icon_path=le.get('icon_path'),
title=le.get('title', name)
)
)
class ServerProxy(Configurable):
servers = Dict(
{},
help="""
Dictionary of processes to supervise & proxy.
Key should be the name of the process. This is also used by default as
the URL prefix, and all requests matching this prefix are routed to this process.
Value should be a dictionary with the following keys:
command
A list of strings that should be the full command to be executed.
The optional template arguments {{port}} and {{base_url}} will be substituted with the
port the process should listen on and the base-url of the notebook.
Could also be a callable. It should return a dictionary.
environment
A dictionary of environment variable mappings. {{port}} and {{base_url}} will be
substituted as for command.
Could also be a callable. It should return a dictionary.
timeout
Timeout in seconds for the process to become ready, default 5s.
absolute_url
Proxy requests default to being rewritten to '/'. If this is True,
the absolute URL will be sent to the backend instead.
port
Set the port that the service will listen on. The default is to automatically select an unused port.
mappath
Map request paths to proxied paths.
Either a dictionary of request paths to proxied paths,
or a callable that takes parameter ``path`` and returns the proxied path.
launcher_entry
A dictionary of various options for entries in classic notebook / jupyterlab launchers.
Keys recognized are:
enabled
Set to True (default) to make an entry in the launchers. Set to False to have no
explicit entry.
icon_path
Full path to an svg icon that could be used with a launcher. Currently only used by the
JupyterLab launcher
title
Title to be used for the launcher entry. Defaults to the name of the server if missing.
""",
config=True
)
host_whitelist = Union(
trait_types=[List(), Callable()],
help="""
List of allowed hosts.
Can also be a function that decides whether a host can be proxied.
If implemented as a function, this should return True if a host should
be proxied and False if it should not. Such a function could verify
that the host matches a particular regular expression pattern or falls
into a specific subnet. It should probably not be a slow check against
some external service. Here is an example that could be placed in a
site-wide Jupyter notebook config:
def host_whitelist(handler, host):
handler.log.info("Request to proxy to host " + host)
return host.startswith("10.")
c.ServerProxy.host_whitelist = host_whitelist
Defaults to a list of ["localhost", "127.0.0.1"].
""",
config=True
)
@default("host_whitelist")
def _host_whitelist_default(self):
return ["localhost", "127.0.0.1"]
keyfile = Unicode(
"",
help="""
Path to optional SSL key.
Use with `https=True` and `certfile`.
""",
config=True
)
certfile = Unicode(
"",
help="""
Path to optional SSL cert.
Use with `https=True` and `keyfile`.
""",
config=True
)
cafile = Unicode(
"",
help="""
Path to optional CA file.
Use with `https=True`.
""",
config=True
)
https = Bool(
False,
help="""
Whether to use SSL for forwarded client requests.
If this is set to `True` then you should provide a path to an SSL key,
cert, and CA. Use this if the proxied service expects to service
requests over SSL.
""",
config=True
)
check_hostname = Bool(
False,
help="Whether to check hostname.",
config=True
)