-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathconfig.py
270 lines (221 loc) · 9.81 KB
/
config.py
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""
Traitlets based configuration for jupyter_server_proxy
"""
from jupyter_server.utils import url_path_join as ujoin
from traitlets import Dict, List, Union, default, observe
from traitlets.config import Configurable
from warnings import warn
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, request_headers_override):
"""
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 _realize_rendered_template(self, attribute):
'''Call any callables, then render any templated values.'''
if callable(attribute):
attribute = self._render_template(
call_with_asked_args(attribute, self.process_args)
)
return self._render_template(attribute)
def get_cmd(self):
return self._realize_rendered_template(command)
def get_env(self):
return self._realize_rendered_template(environment)
def get_request_headers_override(self):
return self._realize_rendered_template(request_headers_override)
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,
sp.request_headers_override,
)
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', 'name', 'new_browser_tab', 'path'])
ServerProcess = namedtuple('ServerProcess', [
'name', 'command', 'environment', 'timeout', 'absolute_url', 'port', 'mappath', 'launcher_entries', 'request_headers_override'])
def make_server_process(name, server_process_config):
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_entries=[*make_launcher_entries(name, server_process_config)],
request_headers_override=server_process_config.get('request_headers_override', {})
)
def make_launcher_entries(name, server_process_config):
le = server_process_config.get('launcher_entry', {})
les = [le] if isinstance(le, dict) else le
new_browser_tab = server_process_config.get('new_browser_tab', True)
for le in les:
yield LauncherEntry(
name=le.get('name', 'default'),
enabled=le.get('enabled', True),
icon_path=le.get('icon_path'),
title=le.get('title', le.get('name', name)),
path=le.get('path', '/'),
new_browser_tab=le.get('new_browser_tab', new_browser_tab)
)
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 list.
environment
A dictionary of environment variable mappings. As with the command
traitlet, {{port}} and {{base_url}} will be substituted.
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.
new_browser_tab
Set to True (default) to make the proxied server interface opened as a new browser tab. Set to False
to have it open a new JupyterLab tab. This has no effect in classic notebook.
request_headers_override
A dictionary of additional HTTP headers for the proxy request. As with
the command traitlet, {{port}} and {{base_url}} will be substituted.
launcher_entry
A dictionary of various options for entries in classic notebook / jupyterlab launchers.
May also be a list of the same, where each must have a ``name`` key.
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.
new_browser_tab
Override the default tab behavior from the root config.
name:
A name (default: default) used for constructing URLs and DOM ids for the launcher
path:
A path (default: /) to open. May include ``?`` params and ``#`` fragments.
""",
config=True
)
host_allowlist = 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_allowlist(handler, host):
handler.log.info("Request to proxy to host " + host)
return host.startswith("10.")
c.ServerProxy.host_allowlist = host_allowlist
Defaults to a list of ["localhost", "127.0.0.1"].
""",
config=True
)
@default("host_allowlist")
def _host_allowlist_default(self):
return ["localhost", "127.0.0.1"]
host_whitelist = Union(
trait_types=[List(), Callable()],
help="Deprecated, use host_allowlist",
config=True)
@observe("host_whitelist")
def _host_whitelist_deprecated(self, change):
old_attr = change.name
if self.host_allowlist != change.new:
# only warn if different
# protects backward-compatible config from warnings
# if they set the same value under both names
# Configurable doesn't have a log
# https://github.com/ipython/traitlets/blob/5.0.5/traitlets/config/configurable.py#L181
warn(
"{cls}.{old} is deprecated in jupyter-server-proxy {version}, use {cls}.{new} instead".format(
cls=self.__class__.__name__,
old=old_attr,
new="host_allowlist",
version="3.0.0",
)
)
self.host_allowlist = change.new