/
spawner.py
1889 lines (1495 loc) · 63.1 KB
/
spawner.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Contains base Spawner class & default implementation
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import ast
import json
import os
import shlex
import shutil
import signal
import sys
import warnings
from inspect import signature
from subprocess import Popen
from tempfile import mkdtemp
from textwrap import dedent
from urllib.parse import urlparse
from async_generator import aclosing
from sqlalchemy import inspect
from tornado.ioloop import PeriodicCallback
from traitlets import (
Any,
Bool,
Dict,
Float,
Instance,
Integer,
List,
Unicode,
Union,
default,
observe,
validate,
)
from traitlets.config import LoggingConfigurable
from . import orm
from .objects import Server
from .roles import roles_to_scopes
from .traitlets import ByteSpecification, Callable, Command
from .utils import (
AnyTimeoutError,
exponential_backoff,
maybe_future,
random_port,
url_escape_path,
url_path_join,
)
if os.name == 'nt':
import psutil
def _quote_safe(s):
"""pass a string that is safe on the command-line
traitlets may parse literals on the command-line, e.g. `--ip=123` will be the number 123 instead of the *string* 123.
wrap valid literals in repr to ensure they are safe
"""
try:
val = ast.literal_eval(s)
except Exception:
# not valid, leave it alone
return s
else:
# it's a valid literal, wrap it in repr (usually just quotes, but with proper escapes)
# to avoid getting interpreted by traitlets
return repr(s)
class Spawner(LoggingConfigurable):
"""Base class for spawning single-user notebook servers.
Subclass this, and override the following methods:
- load_state
- get_state
- start
- stop
- poll
As JupyterHub supports multiple users, an instance of the Spawner subclass
is created for each user. If there are 20 JupyterHub users, there will be 20
instances of the subclass.
"""
# private attributes for tracking status
_spawn_pending = False
_start_pending = False
_stop_pending = False
_proxy_pending = False
_check_pending = False
_waiting_for_response = False
_jupyterhub_version = None
_spawn_future = None
@property
def _log_name(self):
"""Return username:servername or username
Used in logging for consistency with named servers.
"""
if self.user:
user_name = self.user.name
else:
# no user, only happens in mock tests
user_name = "(no user)"
if self.name:
return f"{user_name}:{self.name}"
else:
return user_name
@property
def _failed(self):
"""Did the last spawn fail?"""
return (
not self.active
and self._spawn_future
and self._spawn_future.done()
and self._spawn_future.exception()
)
@property
def pending(self):
"""Return the current pending event, if any
Return False if nothing is pending.
"""
if self._spawn_pending:
return 'spawn'
elif self._stop_pending:
return 'stop'
elif self._check_pending:
return 'check'
return None
@property
def ready(self):
"""Is this server ready to use?
A server is not ready if an event is pending.
"""
if self.pending:
return False
if self.server is None:
return False
return True
@property
def active(self):
"""Return True if the server is active.
This includes fully running and ready or any pending start/stop event.
"""
return bool(self.pending or self.ready)
# options passed by constructor
authenticator = Any()
hub = Any()
orm_spawner = Any()
cookie_options = Dict()
public_url = Unicode(help="Public URL of this spawner's server")
public_hub_url = Unicode(help="Public URL of the Hub itself")
db = Any()
@default("db")
def _deprecated_db(self):
self.log.warning(
dedent(
"""
The shared database session at Spawner.db is deprecated, and will be removed.
Please manage your own database and connections.
Contact JupyterHub at https://github.com/jupyterhub/jupyterhub/issues/3700
if you have questions or ideas about direct database needs for your Spawner.
"""
),
)
return self._deprecated_db_session
_deprecated_db_session = Any()
@observe('orm_spawner')
def _orm_spawner_changed(self, change):
if change.new and change.new.server:
self._server = Server(orm_server=change.new.server)
else:
self._server = None
user = Any()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__()
missing = []
for attr in ('start', 'stop', 'poll'):
if getattr(Spawner, attr) is getattr(cls, attr):
missing.append(attr)
if missing:
raise NotImplementedError(
"class `{}` needs to redefine the `start`,"
"`stop` and `poll` methods. `{}` not redefined.".format(
cls.__name__, '`, `'.join(missing)
)
)
proxy_spec = Unicode()
@property
def last_activity(self):
return self.orm_spawner.last_activity
# Spawner.server is a wrapper of the ORM orm_spawner.server
# make sure it's always in sync with the underlying state
# this is harder to do with traitlets,
# which do not run on every access, only on set and first-get
_server = None
@property
def server(self):
# always check that we're in sync with orm_spawner
if not self.orm_spawner:
# no ORM spawner, nothing to check
return self._server
orm_server = self.orm_spawner.server
if orm_server is not None and (
self._server is None or orm_server is not self._server.orm_server
):
# self._server is not connected to orm_spawner
self._server = Server(orm_server=self.orm_spawner.server)
elif orm_server is None:
# no ORM server, clear it
self._server = None
return self._server
@server.setter
def server(self, server):
self._server = server
if self.orm_spawner is not None:
if server is not None and server.orm_server == self.orm_spawner.server:
# no change
return
if self.orm_spawner.server is not None:
# delete the old value
db = inspect(self.orm_spawner.server).session
db.delete(self.orm_spawner.server)
if server is None:
self.orm_spawner.server = None
else:
if server.orm_server is None:
self.log.warning(f"No ORM server for {self._log_name}")
self.orm_spawner.server = server.orm_server
elif server is not None:
self.log.warning(
f"Setting Spawner.server for {self._log_name} with no underlying orm_spawner"
)
@property
def name(self):
if self.orm_spawner:
return self.orm_spawner.name
return ''
internal_ssl = Bool(False)
internal_trust_bundles = Dict()
internal_certs_location = Unicode('')
cert_paths = Dict()
admin_access = Bool(False)
api_token = Unicode()
oauth_client_id = Unicode()
@property
def oauth_scopes(self):
warnings.warn(
"""Spawner.oauth_scopes is deprecated in JupyterHub 2.3.
Use Spawner.oauth_access_scopes
""",
DeprecationWarning,
stacklevel=2,
)
return self.oauth_access_scopes
oauth_access_scopes = List(
Unicode(),
help="""The scope(s) needed to access this server""",
)
@default("oauth_access_scopes")
def _default_access_scopes(self):
return [
f"access:servers!server={self.user.name}/{self.name}",
f"access:servers!user={self.user.name}",
]
handler = Any()
oauth_roles = Union(
[Callable(), List()],
help="""Allowed roles for oauth tokens.
Deprecated in 3.0: use oauth_client_allowed_scopes
This sets the maximum and default roles
assigned to oauth tokens issued by a single-user server's
oauth client (i.e. tokens stored in browsers after authenticating with the server),
defining what actions the server can take on behalf of logged-in users.
Default is an empty list, meaning minimal permissions to identify users,
no actions can be taken on their behalf.
""",
).tag(config=True)
oauth_client_allowed_scopes = Union(
[Callable(), List()],
help="""Allowed scopes for oauth tokens issued by this server's oauth client.
This sets the maximum and default scopes
assigned to oauth tokens issued by a single-user server's
oauth client (i.e. tokens stored in browsers after authenticating with the server),
defining what actions the server can take on behalf of logged-in users.
Default is an empty list, meaning minimal permissions to identify users,
no actions can be taken on their behalf.
If callable, will be called with the Spawner as a single argument.
Callables may be async.
""",
).tag(config=True)
async def _get_oauth_client_allowed_scopes(self):
"""Private method: get oauth allowed scopes
Handle:
- oauth_client_allowed_scopes
- callable config
- deprecated oauth_roles config
- access_scopes
"""
# cases:
# 1. only scopes
# 2. only roles
# 3. both! (conflict, favor scopes)
scopes = []
if self.oauth_client_allowed_scopes:
allowed_scopes = self.oauth_client_allowed_scopes
if callable(allowed_scopes):
allowed_scopes = allowed_scopes(self)
if inspect.isawaitable(allowed_scopes):
allowed_scopes = await allowed_scopes
scopes.extend(allowed_scopes)
if self.oauth_roles:
if scopes:
# both defined! Warn
warnings.warn(
f"Ignoring deprecated Spawner.oauth_roles={self.oauth_roles} in favor of Spawner.oauth_client_allowed_scopes.",
)
else:
role_names = self.oauth_roles
if callable(role_names):
role_names = role_names(self)
roles = list(
self.db.query(orm.Role).filter(orm.Role.name.in_(role_names))
)
if len(roles) != len(role_names):
missing_roles = set(role_names).difference(
{role.name for role in roles}
)
raise ValueError(f"No such role(s): {', '.join(missing_roles)}")
scopes.extend(roles_to_scopes(roles))
# always add access scope
scopes.append(f"access:servers!server={self.user.name}/{self.name}")
return sorted(set(scopes))
server_token_scopes = Union(
[List(Unicode()), Callable()],
help="""The list of scopes to request for $JUPYTERHUB_API_TOKEN
If not specified, the scopes in the `server` role will be used
(unchanged from pre-4.0).
If callable, will be called with the Spawner instance as its sole argument
(JupyterHub user available as spawner.user).
JUPYTERHUB_API_TOKEN will be assigned the _subset_ of these scopes
that are held by the user (as in oauth_client_allowed_scopes).
.. versionadded:: 4.0
""",
).tag(config=True)
will_resume = Bool(
False,
help="""Whether the Spawner will resume on next start
Default is False where each launch of the Spawner will be a new instance.
If True, an existing Spawner will resume instead of starting anew
(e.g. resuming a Docker container),
and API tokens in use when the Spawner stops will not be deleted.
""",
)
ip = Unicode(
'127.0.0.1',
help="""
The IP address (or hostname) the single-user server should listen on.
Usually either '127.0.0.1' (default) or '0.0.0.0'.
The JupyterHub proxy implementation should be able to send packets to this interface.
Subclasses which launch remotely or in containers
should override the default to '0.0.0.0'.
.. versionchanged:: 2.0
Default changed to '127.0.0.1', from ''.
In most cases, this does not result in a change in behavior,
as '' was interpreted as 'unspecified',
which used the subprocesses' own default, itself usually '127.0.0.1'.
""",
).tag(config=True)
port = Integer(
0,
help="""
The port for single-user servers to listen on.
Defaults to `0`, which uses a randomly allocated port number each time.
If set to a non-zero value, all Spawners will use the same port,
which only makes sense if each server is on a different address,
e.g. in containers.
New in version 0.7.
""",
).tag(config=True)
consecutive_failure_limit = Integer(
0,
help="""
Maximum number of consecutive failures to allow before
shutting down JupyterHub.
This helps JupyterHub recover from a certain class of problem preventing launch
in contexts where the Hub is automatically restarted (e.g. systemd, docker, kubernetes).
A limit of 0 means no limit and consecutive failures will not be tracked.
""",
).tag(config=True)
start_timeout = Integer(
60,
help="""
Timeout (in seconds) before giving up on starting of single-user server.
This is the timeout for start to return, not the timeout for the server to respond.
Callers of spawner.start will assume that startup has failed if it takes longer than this.
start should return when the server process is started and its location is known.
""",
).tag(config=True)
http_timeout = Integer(
30,
help="""
Timeout (in seconds) before giving up on a spawned HTTP server
Once a server has successfully been spawned, this is the amount of time
we wait before assuming that the server is unable to accept
connections.
""",
).tag(config=True)
poll_interval = Integer(
30,
help="""
Interval (in seconds) on which to poll the spawner for single-user server's status.
At every poll interval, each spawner's `.poll` method is called, which checks
if the single-user server is still running. If it isn't running, then JupyterHub modifies
its own state accordingly and removes appropriate routes from the configurable proxy.
""",
).tag(config=True)
poll_jitter = Float(
0.1,
min=0,
max=1,
help="""
Jitter fraction for poll_interval.
Avoids alignment of poll calls for many Spawners,
e.g. when restarting JupyterHub, which restarts all polls for running Spawners.
`poll_jitter=0` means no jitter, 0.1 means 10%, etc.
""",
).tag(config=True)
_callbacks = List()
_poll_callback = Any()
debug = Bool(False, help="Enable debug-logging of the single-user server").tag(
config=True
)
options_form = Union(
[Unicode(), Callable()],
help="""
An HTML form for options a user can specify on launching their server.
The surrounding `<form>` element and the submit button are already provided.
For example:
.. code:: html
Set your key:
<input name="key" val="default_key"></input>
<br>
Choose a letter:
<select name="letter" multiple="true">
<option value="A">The letter A</option>
<option value="B">The letter B</option>
</select>
The data from this form submission will be passed on to your spawner in `self.user_options`
Instead of a form snippet string, this could also be a callable that takes as one
parameter the current spawner instance and returns a string. The callable will
be called asynchronously if it returns a future, rather than a str. Note that
the interface of the spawner class is not deemed stable across versions,
so using this functionality might cause your JupyterHub upgrades to break.
""",
).tag(config=True)
async def get_options_form(self):
"""Get the options form
Returns:
Future (str): the content of the options form presented to the user
prior to starting a Spawner.
.. versionadded:: 0.9
"""
if callable(self.options_form):
options_form = await maybe_future(self.options_form(self))
else:
options_form = self.options_form
return options_form
options_from_form = Callable(
help="""
Interpret HTTP form data
Form data will always arrive as a dict of lists of strings.
Override this function to understand single-values, numbers, etc.
This should coerce form data into the structure expected by self.user_options,
which must be a dict, and should be JSON-serializeable,
though it can contain bytes in addition to standard JSON data types.
This method should not have any side effects.
Any handling of `user_options` should be done in `.start()`
to ensure consistent behavior across servers
spawned via the API and form submission page.
Instances will receive this data on self.user_options, after passing through this function,
prior to `Spawner.start`.
.. versionchanged:: 1.0
user_options are persisted in the JupyterHub database to be reused
on subsequent spawns if no options are given.
user_options is serialized to JSON as part of this persistence
(with additional support for bytes in case of uploaded file data),
and any non-bytes non-jsonable values will be replaced with None
if the user_options are re-used.
""",
).tag(config=True)
@default("options_from_form")
def _options_from_form(self):
return self._default_options_from_form
def _default_options_from_form(self, form_data):
return form_data
def run_options_from_form(self, form_data):
sig = signature(self.options_from_form)
if 'spawner' in sig.parameters:
return self.options_from_form(form_data, spawner=self)
else:
return self.options_from_form(form_data)
def options_from_query(self, query_data):
"""Interpret query arguments passed to /spawn
Query arguments will always arrive as a dict of unicode strings.
Override this function to understand single-values, numbers, etc.
By default, options_from_form is called from this function. You can however override
this function if you need to process the query arguments differently.
This should coerce form data into the structure expected by self.user_options,
which must be a dict, and should be JSON-serializeable,
though it can contain bytes in addition to standard JSON data types.
This method should not have any side effects.
Any handling of `user_options` should be done in `.start()`
to ensure consistent behavior across servers
spawned via the API and form submission page.
Instances will receive this data on self.user_options, after passing through this function,
prior to `Spawner.start`.
.. versionadded:: 1.2
user_options are persisted in the JupyterHub database to be reused
on subsequent spawns if no options are given.
user_options is serialized to JSON as part of this persistence
(with additional support for bytes in case of uploaded file data),
and any non-bytes non-jsonable values will be replaced with None
if the user_options are re-used.
"""
return self.options_from_form(query_data)
user_options = Dict(
help="""
Dict of user specified options for the user's spawned instance of a single-user server.
These user options are usually provided by the `options_form` displayed to the user when they start
their server.
"""
)
env_keep = List(
[
'PATH',
'PYTHONPATH',
'CONDA_ROOT',
'CONDA_DEFAULT_ENV',
'VIRTUAL_ENV',
'LANG',
'LC_ALL',
'JUPYTERHUB_SINGLEUSER_APP',
],
help="""
List of environment variables for the single-user server to inherit from the JupyterHub process.
This list is used to ensure that sensitive information in the JupyterHub process's environment
(such as `CONFIGPROXY_AUTH_TOKEN`) is not passed to the single-user server's process.
""",
).tag(config=True)
env = Dict(
help="""Deprecated: use Spawner.get_env or Spawner.environment
- extend Spawner.get_env for adding required env in Spawner subclasses
- Spawner.environment for config-specified env
"""
)
environment = Dict(
help="""
Extra environment variables to set for the single-user server's process.
Environment variables that end up in the single-user server's process come from 3 sources:
- This `environment` configurable
- The JupyterHub process' environment variables that are listed in `env_keep`
- Variables to establish contact between the single-user notebook and the hub (such as JUPYTERHUB_API_TOKEN)
The `environment` configurable should be set by JupyterHub administrators to add
installation specific environment variables. It is a dict where the key is the name of the environment
variable, and the value can be a string or a callable. If it is a callable, it will be called
with one parameter (the spawner instance), and should return a string fairly quickly (no blocking
operations please!).
Note that the spawner class' interface is not guaranteed to be exactly same across upgrades,
so if you are using the callable take care to verify it continues to work after upgrades!
.. versionchanged:: 1.2
environment from this configuration has highest priority,
allowing override of 'default' env variables,
such as JUPYTERHUB_API_URL.
"""
).tag(config=True)
cmd = Command(
['jupyterhub-singleuser'],
allow_none=True,
help="""
The command used for starting the single-user server.
Provide either a string or a list containing the path to the startup script command. Extra arguments,
other than this path, should be provided via `args`.
This is usually set if you want to start the single-user server in a different python
environment (with virtualenv/conda) than JupyterHub itself.
Some spawners allow shell-style expansion here, allowing you to use environment variables.
Most, including the default, do not. Consult the documentation for your spawner to verify!
""",
).tag(config=True)
args = List(
Unicode(),
help="""
Extra arguments to be passed to the single-user server.
Some spawners allow shell-style expansion here, allowing you to use environment variables here.
Most, including the default, do not. Consult the documentation for your spawner to verify!
""",
).tag(config=True)
notebook_dir = Unicode(
help="""
Path to the notebook directory for the single-user server.
The user sees a file listing of this directory when the notebook interface is started. The
current interface does not easily allow browsing beyond the subdirectories in this directory's
tree.
`~` will be expanded to the home directory of the user, and {username} will be replaced
with the name of the user.
Note that this does *not* prevent users from accessing files outside of this path! They
can do so with many other means.
"""
).tag(config=True)
default_url = Unicode(
help="""
The URL the single-user server should start in.
`{username}` will be expanded to the user's username
Example uses:
- You can set `notebook_dir` to `/` and `default_url` to `/tree/home/{username}` to allow people to
navigate the whole filesystem from their notebook server, but still start in their home directory.
- Start with `/notebooks` instead of `/tree` if `default_url` points to a notebook instead of a directory.
- You can set this to `/lab` to have JupyterLab start by default, rather than Jupyter Notebook.
"""
).tag(config=True)
@validate('notebook_dir', 'default_url')
def _deprecate_percent_u(self, proposal):
v = proposal['value']
if '%U' in v:
self.log.warning(
"%%U for username in %s is deprecated in JupyterHub 0.7, use {username}",
proposal['trait'].name,
)
v = v.replace('%U', '{username}')
self.log.warning("Converting %r to %r", proposal['value'], v)
return v
disable_user_config = Bool(
False,
help="""
Disable per-user configuration of single-user servers.
When starting the user's single-user server, any config file found in the user's $HOME directory
will be ignored.
Note: a user could circumvent this if the user modifies their Python environment, such as when
they have their own conda environments / virtualenvs / containers.
""",
).tag(config=True)
mem_limit = ByteSpecification(
None,
help="""
Maximum number of bytes a single-user notebook server is allowed to use.
Allows the following suffixes:
- K -> Kilobytes
- M -> Megabytes
- G -> Gigabytes
- T -> Terabytes
If the single user server tries to allocate more memory than this,
it will fail. There is no guarantee that the single-user notebook server
will be able to allocate this much memory - only that it can not
allocate more than this.
**This is a configuration setting. Your spawner must implement support
for the limit to work.** The default spawner, `LocalProcessSpawner`,
does **not** implement this support. A custom spawner **must** add
support for this setting for it to be enforced.
""",
).tag(config=True)
cpu_limit = Float(
None,
allow_none=True,
help="""
Maximum number of cpu-cores a single-user notebook server is allowed to use.
If this value is set to 0.5, allows use of 50% of one CPU.
If this value is set to 2, allows use of up to 2 CPUs.
The single-user notebook server will never be scheduled by the kernel to
use more cpu-cores than this. There is no guarantee that it can
access this many cpu-cores.
**This is a configuration setting. Your spawner must implement support
for the limit to work.** The default spawner, `LocalProcessSpawner`,
does **not** implement this support. A custom spawner **must** add
support for this setting for it to be enforced.
""",
).tag(config=True)
mem_guarantee = ByteSpecification(
None,
help="""
Minimum number of bytes a single-user notebook server is guaranteed to have available.
Allows the following suffixes:
- K -> Kilobytes
- M -> Megabytes
- G -> Gigabytes
- T -> Terabytes
**This is a configuration setting. Your spawner must implement support
for the limit to work.** The default spawner, `LocalProcessSpawner`,
does **not** implement this support. A custom spawner **must** add
support for this setting for it to be enforced.
""",
).tag(config=True)
cpu_guarantee = Float(
None,
allow_none=True,
help="""
Minimum number of cpu-cores a single-user notebook server is guaranteed to have available.
If this value is set to 0.5, allows use of 50% of one CPU.
If this value is set to 2, allows use of up to 2 CPUs.
**This is a configuration setting. Your spawner must implement support
for the limit to work.** The default spawner, `LocalProcessSpawner`,
does **not** implement this support. A custom spawner **must** add
support for this setting for it to be enforced.
""",
).tag(config=True)
progress_ready_hook = Any(
help="""
An optional hook function that you can implement to modify the
ready event, which will be shown to the user on the spawn progress page when their server
is ready.
This can be set independent of any concrete spawner implementation.
This maybe a coroutine.
Example::
async def my_ready_hook(spawner, ready_event):
ready_event["html_message"] = f"Server {spawner.name} is ready for {spawner.user.name}"
return ready_event
c.Spawner.progress_ready_hook = my_ready_hook
"""
).tag(config=True)
pre_spawn_hook = Any(
help="""
An optional hook function that you can implement to do some
bootstrapping work before the spawner starts. For example, create a
directory for your user or load initial content.
This can be set independent of any concrete spawner implementation.
This maybe a coroutine.
Example::
def my_hook(spawner):
username = spawner.user.name
spawner.environment["GREETING"] = f"Hello {username}"
c.Spawner.pre_spawn_hook = my_hook
"""
).tag(config=True)
post_stop_hook = Any(
help="""
An optional hook function that you can implement to do work after
the spawner stops.
This can be set independent of any concrete spawner implementation.
"""
).tag(config=True)
auth_state_hook = Any(
help="""
An optional hook function that you can implement to pass `auth_state`
to the spawner after it has been initialized but before it starts.
The `auth_state` dictionary may be set by the `.authenticate()`
method of the authenticator. This hook enables you to pass some
or all of that information to your spawner.
Example::
def userdata_hook(spawner, auth_state):
spawner.userdata = auth_state["userdata"]
c.Spawner.auth_state_hook = userdata_hook
"""
).tag(config=True)
hub_connect_url = Unicode(
None,
allow_none=True,
help="""
The URL the single-user server should connect to the Hub.
If the Hub URL set in your JupyterHub config is not reachable
from spawned notebooks, you can set differnt URL by this config.
Is None if you don't need to change the URL.
""",
).tag(config=True)
def load_state(self, state):
"""Restore state of spawner from database.
Called for each user's spawner after the hub process restarts.
`state` is a dict that'll contain the value returned by `get_state` of
the spawner, or {} if the spawner hasn't persisted any state yet.
Override in subclasses to restore any extra state that is needed to track
the single-user server for that user. Subclasses should call super().
"""
def get_state(self):
"""Save state of spawner into database.
A black box of extra state for custom spawners. The returned value of this is
passed to `load_state`.
Subclasses should call `super().get_state()`, augment the state returned from
there, and return that state.
Returns
-------
state: dict
a JSONable dict of state
"""
state = {}
return state
def clear_state(self):
"""Clear any state that should be cleared when the single-user server stops.
State that should be preserved across single-user server instances should not be cleared.
Subclasses should call super, to ensure that state is properly cleared.
"""
self.api_token = ''
def get_env(self):
"""Return the environment dict to use for the Spawner.
This applies things like `env_keep`, anything defined in `Spawner.environment`,
and adds the API token to the env.
When overriding in subclasses, subclasses must call `super().get_env()`, extend the
returned dict and return it.
Use this to access the env in Spawner.start to allow extension in subclasses.
"""
env = {}
if self.env:
warnings.warn(
"Spawner.env is deprecated, found %s" % self.env, DeprecationWarning
)
env.update(self.env)
for key in self.env_keep:
if key in os.environ:
env[key] = os.environ[key]
env['JUPYTERHUB_API_TOKEN'] = self.api_token