DockerSpawner API

Contents

DockerSpawner API#

Module: dockerspawner#

DockerSpawner#

class dockerspawner.DockerSpawner(**kwargs: Any)#

A Spawner for JupyterHub that runs each user’s server in a separate docker container

allowed_images c.DockerSpawner.allowed_images = Union({})#

List or dict of images that users can run.

If specified, users will be presented with a form from which they can select an image to run.

If a dictionary, the keys will be the options presented to users and the values the actual images that will be launched.

If a list, will be cast to a dictionary where keys and values are the same (i.e. a shortcut for presenting the actual images directly to users).

If a callable, will be called with the Spawner instance as its only argument. The user is accessible as spawner.user. The callable should return a dict or list or None as above.

If empty (default), the value from image is used and any attempt to specify the image via user_options will result in an error.

Changed in version 13: Empty allowed_images means no user-specified images are allowed. This is the default. Prior to 13, restricting to single image required a length-1 list, e.g. allowed_images = [image].

New in version 13: To allow any image, specify allowed_images = "*".

Changed in version 12.0: DockerSpawner.image_whitelist renamed to allowed_images

args c.DockerSpawner.args = List()#

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!

auth_state_hook c.DockerSpawner.auth_state_hook = Any(None)#

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
certs_volume_name c.DockerSpawner.certs_volume_name = Unicode('{prefix}ssl-{username}')#

Volume name

The same string-templating applies to this as other volume names.

property client#

single global client instance

client_kwargs c.DockerSpawner.client_kwargs = Dict()#

Extra keyword arguments to pass to the docker.Client constructor.

cmd c.DockerSpawner.cmd = Command()#

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!

consecutive_failure_limit c.DockerSpawner.consecutive_failure_limit = Int(0)#

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.

property container_id#

alias for object_id

container_image c.DockerSpawner.container_image = Unicode('quay.io/jupyterhub/singleuser:4.0')#

Deprecated, use DockerSpawner.image.

container_ip c.DockerSpawner.container_ip = Unicode('127.0.0.1')#

Deprecated, use DockerSpawner.host_ip

property container_name#

alias for object_name

container_name_template c.DockerSpawner.container_name_template = Unicode('')#

Deprecated, use DockerSpawner.name_template.

container_port c.DockerSpawner.container_port = Int(8888)#

Deprecated, use DockerSpawner.port.

container_prefix c.DockerSpawner.container_prefix = Unicode('')#

Deprecated, use DockerSpawner.prefix.

cpu_guarantee c.DockerSpawner.cpu_guarantee = Float(None)#

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.

cpu_limit c.DockerSpawner.cpu_limit = Union()#

CPU limit for containers

Will set cpu_quota = cpu_limit * cpu_period

The default cpu_period of 100ms will be used, unless overridden in extra_host_config.

Alternatively to a single float, cpu_limit can also be a callable that takes the spawner as the only argument and returns a float:

def per_user_cpu_limit(spawner):

username = spawner.user.name cpu_limits = {‘alice’: 2.5, ‘bob’: 2} return cpu_limits.get(username, 1)

c.DockerSpawner.cpu_limit = per_user_cpu_limit

async create_object()#

Create the container/service object

debug c.DockerSpawner.debug = Bool(False)#

Enable debug-logging of the single-user server

default_url c.DockerSpawner.default_url = Unicode('')#

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.

disable_user_config c.DockerSpawner.disable_user_config = Bool(False)#

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.

docker(method, *args, **kwargs)#

Call a docker method in a background thread

returns a Future

env_keep c.DockerSpawner.env_keep = List()#

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.

environment c.DockerSpawner.environment = Dict()#

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!

Changed in version 1.2: environment from this configuration has highest priority, allowing override of ‘default’ env variables, such as JUPYTERHUB_API_URL.

escape c.DockerSpawner.escape = Any(None)#

Override escaping with any callable of the form escape(str)->str

This is used to ensure docker-safe container names, etc.

The default escaping should ensure safety and validity, but can produce cumbersome strings in cases.

Set c.DockerSpawner.escape = ‘legacy’ to preserve the earlier, unsafe behavior if it worked for you.

New in version 12.0.

Changed in version 12.0: Escaping has changed in 12.0 to ensure safety, but existing deployments will get different container and volume names.

property escaped_name#

Escape the username so it’s safe for docker objects

property executor#

single global executor

extra_create_kwargs c.DockerSpawner.extra_create_kwargs = Union()#

Additional args to pass for container create

For example, to change the user the container is started as:

c.DockerSpawner.extra_create_kwargs = {
    "user": "root" # Can also be an integer UID
}

The above is equivalent to docker run --user root.

If a callable, will be called with the Spawner as the only argument, must return the same dictionary structure, and may be async.

Changed in version 13: Added callable support.

extra_host_config c.DockerSpawner.extra_host_config = Union()#

Additional args to create_host_config for container create.

If a callable, will be called with the Spawner as the only argument, must return the same dictionary structure, and may be async.

Changed in version 13: Added callable support.

format_volume_name c.DockerSpawner.format_volume_name = Any(None)#

Any callable that accepts a string template and a DockerSpawner instance as parameters in that order and returns a string.

Reusable implementations should go in dockerspawner.VolumeNamingStrategy, tests should go in …

async get_command()#

Get the command to run (full command + args)

get_env()#

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.

async get_ip_and_port()#

Queries Docker daemon for container’s IP and port.

If you are using network_mode=host, you will need to override this method as follows:

async def get_ip_and_port(self):
    return self.host_ip, self.port

You will need to make sure host_ip and port are correct, which depends on the route to the container and the port it opens.

get_state()#

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 – a JSONable dict of state

Return type:

dict

host_ip c.DockerSpawner.host_ip = Unicode('127.0.0.1')#

The ip address on the host on which to expose the container’s port

Typically 127.0.0.1, but can be public interfaces as well in cases where the Hub and/or proxy are on different machines from the user containers.

Only used when use_internal_ip = False.

http_timeout c.DockerSpawner.http_timeout = Int(30)#

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.

hub_connect_url c.DockerSpawner.hub_connect_url = Unicode(None)#

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.

hub_ip_connect c.DockerSpawner.hub_ip_connect = Unicode('')#

DEPRECATED since JupyterHub 0.8. Use c.JupyterHub.hub_connect_ip.

image c.DockerSpawner.image = Unicode('quay.io/jupyterhub/singleuser:4.0')#

The image to use for single-user servers.

This image should have the same version of jupyterhub as the Hub itself installed.

If the default command of the image does not launch jupyterhub-singleuser, set c.Spawner.cmd to launch jupyterhub-singleuser, e.g.

Any of the jupyter docker-stacks should work without additional config, as long as the version of jupyterhub in the image is compatible.

image_whitelist c.DockerSpawner.image_whitelist = Union()#

Deprecated, use DockerSpawner.allowed_images.

property internal_hostname#

Return our hostname

used with internal SSL

ip c.DockerSpawner.ip = Unicode('127.0.0.1')#

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’.

Changed in version 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’.

Specify docker link mapping to add to the container, e.g.

links = {‘jupyterhub’: ‘jupyterhub’}

If the Hub is running in a Docker container, this can simplify routing because all traffic will be using docker hostnames.

load_state(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().

mem_guarantee c.DockerSpawner.mem_guarantee = ByteSpecification(None)#

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.

mem_limit c.DockerSpawner.mem_limit = Union()#

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.

Alternatively to a string it can also be a callable that takes the spawner as the only argument and returns a string:

def per_user_mem_limit(spawner):

username = spawner.user.name ram_limits = {‘alice’: ‘4G’, ‘bob’: ‘2G’} return ram_limits.get(username, ‘1G’)

c.DockerSpawner.mem_limit = per_user_mem_limit

property mount_binds#

A different way of specifying docker volumes using more advanced spec. Converts mounts list of dict to a list of docker.types.Mount

mounts c.DockerSpawner.mounts = List()#

List of dict with keys to match docker.types.Mount for more advanced configuration of mouted volumes. As with volumes, if the default format_volume_name is in use, you can use {username} in the source or target paths, and it will be replaced with the current user’s name.

async move_certs(paths)#

Takes certificate paths and makes them available to the notebook server

Parameters:

paths (dict) – a list of paths for key, cert, and CA. These paths will be resolvable and readable by the Hub process, but not necessarily by the notebook server.

Returns:

a list (potentially altered) of paths for key, cert, and CA.

These paths should be resolvable and readable by the notebook server to be launched.

Return type:

dict

.move_certs is called after certs for the singleuser notebook have been created by create_certs.

By default, certs are created in a standard, central location defined by internal_certs_location. For a local, single-host deployment of JupyterHub, this should suffice. If, however, singleuser notebooks are spawned on other hosts, .move_certs should be overridden to move these files appropriately. This could mean using scp to copy them to another host, moving them to a volume mounted in a docker container, or exporting them as a secret in kubernetes.

move_certs_image c.DockerSpawner.move_certs_image = Unicode('busybox:1.30.1')#

The image used to stage internal SSL certificates.

Busybox is used because we just need an empty container that waits while we stage files into the volume via .put_archive.

name_template c.DockerSpawner.name_template = Unicode('')#

Name of the container or service: with {username}, {imagename}, {prefix}, {servername} replacements. {raw_username} can be used for the original, not escaped username (may contain uppercase, special characters). It is important to include {servername} if JupyterHub’s “named servers” are enabled (JupyterHub.allow_named_servers = True). If the server is named, the default name_template is “{prefix}-{username}–{servername}”. If it is unnamed, the default name_template is “{prefix}-{username}”.

Note: when using named servers, it is important that the separator between {username} and {servername} is not a character that can occur in an escaped {username}, and also not the single escape character ‘-‘.

network_name c.DockerSpawner.network_name = Unicode('bridge')#

Run the containers on this docker network. If it is an internal docker network, the Hub should be on the same network, as internal docker IP addresses will be used. For bridge networking, external ports will be bound.

notebook_dir c.DockerSpawner.notebook_dir = Unicode('')#

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.

oauth_client_allowed_scopes c.DockerSpawner.oauth_client_allowed_scopes = Union()#

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.

oauth_roles c.DockerSpawner.oauth_roles = Union()#

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.

options_form c.DockerSpawner.options_form = Union()#

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:

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.

options_from_form(formdata)#

Turn options formdata into user_options

async poll()#

Check for my id in docker ps

poll_interval c.DockerSpawner.poll_interval = Int(30)#

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.

port c.DockerSpawner.port = Int(0)#

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.

post_start_cmd c.DockerSpawner.post_start_cmd = UnicodeOrFalse(False)#

If specified, the command will be executed inside the container after starting. Similar to using ‘docker exec’

async post_start_exec()#

Execute additional command inside the container after starting it.

e.g. calling ‘docker exec’

post_stop_hook c.DockerSpawner.post_stop_hook = Any(None)#

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.

pre_spawn_hook c.DockerSpawner.pre_spawn_hook = Any(None)#

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:

from subprocess import check_call
def my_hook(spawner):
    username = spawner.user.name
    check_call(['./examples/bootstrap-script/bootstrap.sh', username])

c.Spawner.pre_spawn_hook = my_hook
prefix c.DockerSpawner.prefix = Unicode('jupyter')#

Prefix for container names. See name_template for full container name for a particular user’s server.

async pull_image(image)#

Pull the image, if needed

  • pulls it unconditionally if pull_policy == ‘always’

  • skipped entirely if pull_policy == ‘skip’ (default for swarm)

  • otherwise, checks if it exists, and - raises if pull_policy == ‘never’ - pulls if pull_policy == ‘ifnotpresent’

pull_policy c.DockerSpawner.pull_policy = CaselessStrEnum('ifnotpresent')#

The policy for pulling the user docker image.

Choices:

  • ifnotpresent: pull if the image is not already present (default)

  • always: always pull the image to check for updates, even if it is present

  • never: never perform a pull, raise if image is not present

  • skip: never perform a pull, skip the step entirely (like never, but without raising when images are not present; default for swarm)

read_only_volumes c.DockerSpawner.read_only_volumes = Dict()#

Map from host file/directory to container file/directory. Volumes specified here will be read-only in the container.

If format_volume_name is not set, default_format_volume_name is used for naming volumes. In this case, if you use {username} in either the host or guest file/directory path, it will be replaced with the current user’s name.

remove c.DockerSpawner.remove = Bool(False)#

If True, delete containers when servers are stopped.

This will destroy any data in the container not stored in mounted volumes.

remove_containers c.DockerSpawner.remove_containers = Bool(False)#

Deprecated, use DockerSpawner.remove.

server_token_scopes c.DockerSpawner.server_token_scopes = Union()#

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).

New in version 4.0.

ssl_alt_names c.DockerSpawner.ssl_alt_names = List()#

List of SSL alt names

May be set in config if all spawners should have the same value(s), or set at runtime by Spawner that know their names.

ssl_alt_names_include_local c.DockerSpawner.ssl_alt_names_include_local = Bool(True)#

Whether to include DNS:localhost, IP:127.0.0.1 in alt names

async start()#

Start the single-user server in a docker container.

If the container exists and c.DockerSpawner.remove is True, then the container is removed first. Otherwise, the existing containers will be restarted.

async start_object()#

Actually start the container/service

e.g. calling docker start

start_timeout c.DockerSpawner.start_timeout = Int(60)#

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.

async stop(now=False)#

Stop the container

Will remove the container if c.DockerSpawner.remove is True.

Consider using pause/unpause when docker-py adds support.

async stop_object()#

Stop the container/service

e.g. calling docker stop. Does not remove the container.

template_namespace()#

Return the template namespace for format-string formatting.

Currently used on default_url and notebook_dir.

Subclasses may add items to the available namespace.

The default implementation includes:

{
  'username': user.name,
  'base_url': users_base_url,
}
Returns:

namespace for string formatting.

Return type:

ns (dict)

tls c.DockerSpawner.tls = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_assert_hostname c.DockerSpawner.tls_assert_hostname = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_ca c.DockerSpawner.tls_ca = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_cert c.DockerSpawner.tls_cert = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

property tls_client#

A tuple consisting of the TLS client certificate and key if they have been provided, otherwise None.

tls_config c.DockerSpawner.tls_config = Dict()#

Arguments to pass to docker TLS configuration.

See docker.client.TLSConfig constructor for options.

tls_key c.DockerSpawner.tls_key = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_verify c.DockerSpawner.tls_verify = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

use_docker_client_env c.DockerSpawner.use_docker_client_env = Bool(True)#

Deprecated. Docker env variables are always used if present.

use_internal_hostname c.DockerSpawner.use_internal_hostname = Bool(False)#

Use the docker hostname for connecting.

instead of an IP address. This should work in general when using docker networks, and must be used when internal_ssl is enabled. It is enabled by default if internal_ssl is enabled.

use_internal_ip c.DockerSpawner.use_internal_ip = Bool(False)#

Enable the usage of the internal docker ip. This is useful if you are running jupyterhub (as a container) and the user containers within the same docker network. E.g. by mounting the docker socket of the host into the jupyterhub container. Default is True if using a docker network, False if bridge or host networking is used.

property volume_binds#

The second half of declaring a volume with docker-py happens when you actually call start(). The required format is a dict of dicts that looks like:

{
    host_location: {'bind': container_location, 'mode': 'rw'}
}

Mode may be ‘ro’, ‘rw’, ‘z’, or ‘Z’.

property volume_mount_points#

Volumes are declared in docker-py in two stages. First, you declare all the locations where you’re going to mount volumes when you call create_container.

Returns a sorted list of all the values in self.volumes or self.read_only_volumes.

volumes c.DockerSpawner.volumes = Dict()#

Map from host file/directory to container (guest) file/directory mount point and (optionally) a mode. When specifying the guest mount point (bind) for the volume, you may use a dict or str. If a str, then the volume will default to a read-write (mode=”rw”). With a dict, the bind is identified by “bind” and the “mode” may be one of “rw” (default), “ro” (read-only), “z” (public/shared SELinux volume label), and “Z” (private/unshared SELinux volume label).

If format_volume_name is not set, default_format_volume_name is used for naming volumes. In this case, if you use {username} in either the host or guest file/directory path, it will be replaced with the current user’s name.

property will_resume#

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.

SwarmSpawner#

class dockerspawner.SwarmSpawner(**kwargs: Any)#

A Spawner for JupyterHub that runs each user’s server in a separate docker service

allowed_images c.SwarmSpawner.allowed_images = Union({})#

List or dict of images that users can run.

If specified, users will be presented with a form from which they can select an image to run.

If a dictionary, the keys will be the options presented to users and the values the actual images that will be launched.

If a list, will be cast to a dictionary where keys and values are the same (i.e. a shortcut for presenting the actual images directly to users).

If a callable, will be called with the Spawner instance as its only argument. The user is accessible as spawner.user. The callable should return a dict or list or None as above.

If empty (default), the value from image is used and any attempt to specify the image via user_options will result in an error.

Changed in version 13: Empty allowed_images means no user-specified images are allowed. This is the default. Prior to 13, restricting to single image required a length-1 list, e.g. allowed_images = [image].

New in version 13: To allow any image, specify allowed_images = "*".

Changed in version 12.0: DockerSpawner.image_whitelist renamed to allowed_images

args c.SwarmSpawner.args = List()#

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!

auth_state_hook c.SwarmSpawner.auth_state_hook = Any(None)#

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
certs_volume_name c.SwarmSpawner.certs_volume_name = Unicode('{prefix}ssl-{username}')#

Volume name

The same string-templating applies to this as other volume names.

client_kwargs c.SwarmSpawner.client_kwargs = Dict()#

Extra keyword arguments to pass to the docker.Client constructor.

cmd c.SwarmSpawner.cmd = Command()#

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!

consecutive_failure_limit c.SwarmSpawner.consecutive_failure_limit = Int(0)#

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.

container_image c.SwarmSpawner.container_image = Unicode('quay.io/jupyterhub/singleuser:4.0')#

Deprecated, use DockerSpawner.image.

container_ip c.SwarmSpawner.container_ip = Unicode('127.0.0.1')#

Deprecated, use DockerSpawner.host_ip

container_name_template c.SwarmSpawner.container_name_template = Unicode('')#

Deprecated, use DockerSpawner.name_template.

container_port c.SwarmSpawner.container_port = Int(8888)#

Deprecated, use DockerSpawner.port.

container_prefix c.SwarmSpawner.container_prefix = Unicode('')#

Deprecated, use DockerSpawner.prefix.

cpu_guarantee c.SwarmSpawner.cpu_guarantee = Float(None)#

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.

cpu_limit c.SwarmSpawner.cpu_limit = Union()#

CPU limit for containers

Will set cpu_quota = cpu_limit * cpu_period

The default cpu_period of 100ms will be used, unless overridden in extra_host_config.

Alternatively to a single float, cpu_limit can also be a callable that takes the spawner as the only argument and returns a float:

def per_user_cpu_limit(spawner):

username = spawner.user.name cpu_limits = {‘alice’: 2.5, ‘bob’: 2} return cpu_limits.get(username, 1)

c.DockerSpawner.cpu_limit = per_user_cpu_limit

async create_object()#

Start the single-user server in a docker service.

debug c.SwarmSpawner.debug = Bool(False)#

Enable debug-logging of the single-user server

default_url c.SwarmSpawner.default_url = Unicode('')#

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.

disable_user_config c.SwarmSpawner.disable_user_config = Bool(False)#

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.

env_keep c.SwarmSpawner.env_keep = List()#

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.

environment c.SwarmSpawner.environment = Dict()#

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!

Changed in version 1.2: environment from this configuration has highest priority, allowing override of ‘default’ env variables, such as JUPYTERHUB_API_URL.

escape c.SwarmSpawner.escape = Any(None)#

Override escaping with any callable of the form escape(str)->str

This is used to ensure docker-safe container names, etc.

The default escaping should ensure safety and validity, but can produce cumbersome strings in cases.

Set c.DockerSpawner.escape = ‘legacy’ to preserve the earlier, unsafe behavior if it worked for you.

New in version 12.0.

Changed in version 12.0: Escaping has changed in 12.0 to ensure safety, but existing deployments will get different container and volume names.

extra_container_spec c.SwarmSpawner.extra_container_spec = Dict()#

Keyword arguments to pass to the ContainerSpec constructor

extra_create_kwargs c.SwarmSpawner.extra_create_kwargs = Union()#

Additional args to pass for container create

For example, to change the user the container is started as:

c.DockerSpawner.extra_create_kwargs = {
    "user": "root" # Can also be an integer UID
}

The above is equivalent to docker run --user root.

If a callable, will be called with the Spawner as the only argument, must return the same dictionary structure, and may be async.

Changed in version 13: Added callable support.

extra_endpoint_spec c.SwarmSpawner.extra_endpoint_spec = Dict()#

Keyword arguments to pass to the Endpoint constructor

extra_host_config c.SwarmSpawner.extra_host_config = Union()#

Additional args to create_host_config for container create.

If a callable, will be called with the Spawner as the only argument, must return the same dictionary structure, and may be async.

Changed in version 13: Added callable support.

extra_placement_spec c.SwarmSpawner.extra_placement_spec = Dict()#

Keyword arguments to pass to the Placement constructor

extra_resources_spec c.SwarmSpawner.extra_resources_spec = Dict()#

Keyword arguments to pass to the Resources spec

extra_task_spec c.SwarmSpawner.extra_task_spec = Dict()#

Keyword arguments to pass to the TaskTemplate constructor

format_volume_name c.SwarmSpawner.format_volume_name = Any(None)#

Any callable that accepts a string template and a DockerSpawner instance as parameters in that order and returns a string.

Reusable implementations should go in dockerspawner.VolumeNamingStrategy, tests should go in …

async get_ip_and_port()#

Queries Docker daemon for service’s IP and port.

If you are using network_mode=host, you will need to override this method as follows:

async def get_ip_and_port(self):
    return self.host_ip, self.port

You will need to make sure host_ip and port are correct, which depends on the route to the service and the port it opens.

host_ip c.SwarmSpawner.host_ip = Unicode('127.0.0.1')#

The ip address on the host on which to expose the container’s port

Typically 127.0.0.1, but can be public interfaces as well in cases where the Hub and/or proxy are on different machines from the user containers.

Only used when use_internal_ip = False.

http_timeout c.SwarmSpawner.http_timeout = Int(30)#

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.

hub_connect_url c.SwarmSpawner.hub_connect_url = Unicode(None)#

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.

hub_ip_connect c.SwarmSpawner.hub_ip_connect = Unicode('')#

DEPRECATED since JupyterHub 0.8. Use c.JupyterHub.hub_connect_ip.

image c.SwarmSpawner.image = Unicode('quay.io/jupyterhub/singleuser:4.0')#

The image to use for single-user servers.

This image should have the same version of jupyterhub as the Hub itself installed.

If the default command of the image does not launch jupyterhub-singleuser, set c.Spawner.cmd to launch jupyterhub-singleuser, e.g.

Any of the jupyter docker-stacks should work without additional config, as long as the version of jupyterhub in the image is compatible.

image_whitelist c.SwarmSpawner.image_whitelist = Union()#

Deprecated, use DockerSpawner.allowed_images.

property internal_hostname#

Return our hostname

used with internal SSL

ip c.SwarmSpawner.ip = Unicode('127.0.0.1')#

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’.

Changed in version 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’.

Specify docker link mapping to add to the container, e.g.

links = {‘jupyterhub’: ‘jupyterhub’}

If the Hub is running in a Docker container, this can simplify routing because all traffic will be using docker hostnames.

mem_guarantee c.SwarmSpawner.mem_guarantee = ByteSpecification(None)#

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.

mem_limit c.SwarmSpawner.mem_limit = Union()#

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.

Alternatively to a string it can also be a callable that takes the spawner as the only argument and returns a string:

def per_user_mem_limit(spawner):

username = spawner.user.name ram_limits = {‘alice’: ‘4G’, ‘bob’: ‘2G’} return ram_limits.get(username, ‘1G’)

c.DockerSpawner.mem_limit = per_user_mem_limit

property mounts#

List of dict with keys to match docker.types.Mount for more advanced configuration of mouted volumes. As with volumes, if the default format_volume_name is in use, you can use {username} in the source or target paths, and it will be replaced with the current user’s name.

move_certs_image c.SwarmSpawner.move_certs_image = Unicode('busybox:1.30.1')#

The image used to stage internal SSL certificates.

Busybox is used because we just need an empty container that waits while we stage files into the volume via .put_archive.

name_template c.SwarmSpawner.name_template = Unicode('')#

Name of the container or service: with {username}, {imagename}, {prefix}, {servername} replacements. {raw_username} can be used for the original, not escaped username (may contain uppercase, special characters). It is important to include {servername} if JupyterHub’s “named servers” are enabled (JupyterHub.allow_named_servers = True). If the server is named, the default name_template is “{prefix}-{username}–{servername}”. If it is unnamed, the default name_template is “{prefix}-{username}”.

Note: when using named servers, it is important that the separator between {username} and {servername} is not a character that can occur in an escaped {username}, and also not the single escape character ‘-‘.

network_name c.SwarmSpawner.network_name = Unicode('bridge')#

Run the containers on this docker network. If it is an internal docker network, the Hub should be on the same network, as internal docker IP addresses will be used. For bridge networking, external ports will be bound.

notebook_dir c.SwarmSpawner.notebook_dir = Unicode('')#

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.

oauth_client_allowed_scopes c.SwarmSpawner.oauth_client_allowed_scopes = Union()#

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.

oauth_roles c.SwarmSpawner.oauth_roles = Union()#

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.

options_form c.SwarmSpawner.options_form = Union()#

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:

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.

async poll()#

Check for my id in docker ps

poll_interval c.SwarmSpawner.poll_interval = Int(30)#

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.

port c.SwarmSpawner.port = Int(0)#

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.

post_start_cmd c.SwarmSpawner.post_start_cmd = UnicodeOrFalse(False)#

If specified, the command will be executed inside the container after starting. Similar to using ‘docker exec’

post_stop_hook c.SwarmSpawner.post_stop_hook = Any(None)#

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.

pre_spawn_hook c.SwarmSpawner.pre_spawn_hook = Any(None)#

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:

from subprocess import check_call
def my_hook(spawner):
    username = spawner.user.name
    check_call(['./examples/bootstrap-script/bootstrap.sh', username])

c.Spawner.pre_spawn_hook = my_hook
prefix c.SwarmSpawner.prefix = Unicode('jupyter')#

Prefix for container names. See name_template for full container name for a particular user’s server.

pull_policy c.SwarmSpawner.pull_policy = CaselessStrEnum('ifnotpresent')#

The policy for pulling the user docker image.

Choices:

  • ifnotpresent: pull if the image is not already present (default)

  • always: always pull the image to check for updates, even if it is present

  • never: never perform a pull, raise if image is not present

  • skip: never perform a pull, skip the step entirely (like never, but without raising when images are not present; default for swarm)

read_only_volumes c.SwarmSpawner.read_only_volumes = Dict()#

Map from host file/directory to container file/directory. Volumes specified here will be read-only in the container.

If format_volume_name is not set, default_format_volume_name is used for naming volumes. In this case, if you use {username} in either the host or guest file/directory path, it will be replaced with the current user’s name.

remove_containers c.SwarmSpawner.remove_containers = Bool(False)#

Deprecated, use DockerSpawner.remove.

server_token_scopes c.SwarmSpawner.server_token_scopes = Union()#

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).

New in version 4.0.

property service_id#

alias for object_id

property service_name#

alias for object_name

ssl_alt_names c.SwarmSpawner.ssl_alt_names = List()#

List of SSL alt names

May be set in config if all spawners should have the same value(s), or set at runtime by Spawner that know their names.

ssl_alt_names_include_local c.SwarmSpawner.ssl_alt_names_include_local = Bool(True)#

Whether to include DNS:localhost, IP:127.0.0.1 in alt names

async start_object()#

Not actually starting anything

but use this to wait for the container to be running.

Spawner.start shouldn’t return until the Spawner believes a server is running somewhere, not just requested.

start_timeout c.SwarmSpawner.start_timeout = Int(60)#

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.

async stop_object()#

Nothing to do here

There is no separate stop action for services

tls c.SwarmSpawner.tls = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_assert_hostname c.SwarmSpawner.tls_assert_hostname = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_ca c.SwarmSpawner.tls_ca = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_cert c.SwarmSpawner.tls_cert = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_config c.SwarmSpawner.tls_config = Dict()#

Arguments to pass to docker TLS configuration.

See docker.client.TLSConfig constructor for options.

tls_key c.SwarmSpawner.tls_key = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_verify c.SwarmSpawner.tls_verify = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

use_docker_client_env c.SwarmSpawner.use_docker_client_env = Bool(True)#

Deprecated. Docker env variables are always used if present.

use_internal_hostname c.SwarmSpawner.use_internal_hostname = Bool(False)#

Use the docker hostname for connecting.

instead of an IP address. This should work in general when using docker networks, and must be used when internal_ssl is enabled. It is enabled by default if internal_ssl is enabled.

use_internal_ip c.SwarmSpawner.use_internal_ip = Bool(False)#

Enable the usage of the internal docker ip. This is useful if you are running jupyterhub (as a container) and the user containers within the same docker network. E.g. by mounting the docker socket of the host into the jupyterhub container. Default is True if using a docker network, False if bridge or host networking is used.

volume_driver c.SwarmSpawner.volume_driver = Unicode('')#

Use this driver for mounting the notebook volumes. Note that this driver must support multiple hosts in order for it to work across the swarm. For a list of possible drivers, see https://docs.docker.com/engine/extend/legacy_plugins/#volume-plugins

volume_driver_options c.SwarmSpawner.volume_driver_options = Dict()#

Configuration options for the multi-host volume driver.

volumes c.SwarmSpawner.volumes = Dict()#

Map from host file/directory to container (guest) file/directory mount point and (optionally) a mode. When specifying the guest mount point (bind) for the volume, you may use a dict or str. If a str, then the volume will default to a read-write (mode=”rw”). With a dict, the bind is identified by “bind” and the “mode” may be one of “rw” (default), “ro” (read-only), “z” (public/shared SELinux volume label), and “Z” (private/unshared SELinux volume label).

If format_volume_name is not set, default_format_volume_name is used for naming volumes. In this case, if you use {username} in either the host or guest file/directory path, it will be replaced with the current user’s name.

SystemUserSpawner#

class dockerspawner.SystemUserSpawner(**kwargs: Any)#
allowed_images c.SystemUserSpawner.allowed_images = Union({})#

List or dict of images that users can run.

If specified, users will be presented with a form from which they can select an image to run.

If a dictionary, the keys will be the options presented to users and the values the actual images that will be launched.

If a list, will be cast to a dictionary where keys and values are the same (i.e. a shortcut for presenting the actual images directly to users).

If a callable, will be called with the Spawner instance as its only argument. The user is accessible as spawner.user. The callable should return a dict or list or None as above.

If empty (default), the value from image is used and any attempt to specify the image via user_options will result in an error.

Changed in version 13: Empty allowed_images means no user-specified images are allowed. This is the default. Prior to 13, restricting to single image required a length-1 list, e.g. allowed_images = [image].

New in version 13: To allow any image, specify allowed_images = "*".

Changed in version 12.0: DockerSpawner.image_whitelist renamed to allowed_images

args c.SystemUserSpawner.args = List()#

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!

auth_state_hook c.SystemUserSpawner.auth_state_hook = Any(None)#

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
certs_volume_name c.SystemUserSpawner.certs_volume_name = Unicode('{prefix}ssl-{username}')#

Volume name

The same string-templating applies to this as other volume names.

client_kwargs c.SystemUserSpawner.client_kwargs = Dict()#

Extra keyword arguments to pass to the docker.Client constructor.

cmd c.SystemUserSpawner.cmd = Command()#

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!

consecutive_failure_limit c.SystemUserSpawner.consecutive_failure_limit = Int(0)#

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.

container_image c.SystemUserSpawner.container_image = Unicode('quay.io/jupyterhub/singleuser:4.0')#

Deprecated, use DockerSpawner.image.

container_ip c.SystemUserSpawner.container_ip = Unicode('127.0.0.1')#

Deprecated, use DockerSpawner.host_ip

container_name_template c.SystemUserSpawner.container_name_template = Unicode('')#

Deprecated, use DockerSpawner.name_template.

container_port c.SystemUserSpawner.container_port = Int(8888)#

Deprecated, use DockerSpawner.port.

container_prefix c.SystemUserSpawner.container_prefix = Unicode('')#

Deprecated, use DockerSpawner.prefix.

cpu_guarantee c.SystemUserSpawner.cpu_guarantee = Float(None)#

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.

cpu_limit c.SystemUserSpawner.cpu_limit = Union()#

CPU limit for containers

Will set cpu_quota = cpu_limit * cpu_period

The default cpu_period of 100ms will be used, unless overridden in extra_host_config.

Alternatively to a single float, cpu_limit can also be a callable that takes the spawner as the only argument and returns a float:

def per_user_cpu_limit(spawner):

username = spawner.user.name cpu_limits = {‘alice’: 2.5, ‘bob’: 2} return cpu_limits.get(username, 1)

c.DockerSpawner.cpu_limit = per_user_cpu_limit

debug c.SystemUserSpawner.debug = Bool(False)#

Enable debug-logging of the single-user server

default_url c.SystemUserSpawner.default_url = Unicode('')#

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.

disable_user_config c.SystemUserSpawner.disable_user_config = Bool(False)#

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.

env_keep c.SystemUserSpawner.env_keep = List()#

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.

environment c.SystemUserSpawner.environment = Dict()#

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!

Changed in version 1.2: environment from this configuration has highest priority, allowing override of ‘default’ env variables, such as JUPYTERHUB_API_URL.

escape c.SystemUserSpawner.escape = Any(None)#

Override escaping with any callable of the form escape(str)->str

This is used to ensure docker-safe container names, etc.

The default escaping should ensure safety and validity, but can produce cumbersome strings in cases.

Set c.DockerSpawner.escape = ‘legacy’ to preserve the earlier, unsafe behavior if it worked for you.

New in version 12.0.

Changed in version 12.0: Escaping has changed in 12.0 to ensure safety, but existing deployments will get different container and volume names.

extra_create_kwargs c.SystemUserSpawner.extra_create_kwargs = Union()#

Additional args to pass for container create

For example, to change the user the container is started as:

c.DockerSpawner.extra_create_kwargs = {
    "user": "root" # Can also be an integer UID
}

The above is equivalent to docker run --user root.

If a callable, will be called with the Spawner as the only argument, must return the same dictionary structure, and may be async.

Changed in version 13: Added callable support.

extra_host_config c.SystemUserSpawner.extra_host_config = Union()#

Additional args to create_host_config for container create.

If a callable, will be called with the Spawner as the only argument, must return the same dictionary structure, and may be async.

Changed in version 13: Added callable support.

format_volume_name c.SystemUserSpawner.format_volume_name = Any(None)#

Any callable that accepts a string template and a DockerSpawner instance as parameters in that order and returns a string.

Reusable implementations should go in dockerspawner.VolumeNamingStrategy, tests should go in …

get_env()#

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.

get_state()#

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 – a JSONable dict of state

Return type:

dict

group_id Int(-1)#

If system users are being used, then we need to know their group id in order to mount the home directory with correct group permissions.

Group IDs are looked up in two ways:

  1. stored in the state dict (authenticator can write here)

  2. lookup via pwd

property homedir#

Path to the user’s home directory in the docker image.

property host_homedir#

Path to the volume containing the user’s home directory on the host. Looked up from pwd if an empty format string or None has been specified.

host_homedir_format_string c.SystemUserSpawner.host_homedir_format_string = Unicode('/home/{username}')#

Format string for the path to the user’s home directory on the host. The format string should include a username variable, which will be formatted with the user’s username.

If the string is empty or None, the user’s home directory will be looked up via the pwd database.

host_ip c.SystemUserSpawner.host_ip = Unicode('127.0.0.1')#

The ip address on the host on which to expose the container’s port

Typically 127.0.0.1, but can be public interfaces as well in cases where the Hub and/or proxy are on different machines from the user containers.

Only used when use_internal_ip = False.

http_timeout c.SystemUserSpawner.http_timeout = Int(30)#

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.

hub_connect_url c.SystemUserSpawner.hub_connect_url = Unicode(None)#

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.

hub_ip_connect c.SystemUserSpawner.hub_ip_connect = Unicode('')#

DEPRECATED since JupyterHub 0.8. Use c.JupyterHub.hub_connect_ip.

image c.SystemUserSpawner.image = Unicode('quay.io/jupyterhub/singleuser:4.0')#

The image to use for single-user servers.

This image should have the same version of jupyterhub as the Hub itself installed.

If the default command of the image does not launch jupyterhub-singleuser, set c.Spawner.cmd to launch jupyterhub-singleuser, e.g.

Any of the jupyter docker-stacks should work without additional config, as long as the version of jupyterhub in the image is compatible.

image_homedir_format_string c.SystemUserSpawner.image_homedir_format_string = Unicode('/home/{username}')#

Format string for the path to the user’s home directory inside the image. The format string should include a username variable, which will be formatted with the user’s username.

image_whitelist c.SystemUserSpawner.image_whitelist = Union()#

Deprecated, use DockerSpawner.allowed_images.

ip c.SystemUserSpawner.ip = Unicode('127.0.0.1')#

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’.

Changed in version 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’.

Specify docker link mapping to add to the container, e.g.

links = {‘jupyterhub’: ‘jupyterhub’}

If the Hub is running in a Docker container, this can simplify routing because all traffic will be using docker hostnames.

load_state(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().

mem_guarantee c.SystemUserSpawner.mem_guarantee = ByteSpecification(None)#

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.

mem_limit c.SystemUserSpawner.mem_limit = Union()#

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.

Alternatively to a string it can also be a callable that takes the spawner as the only argument and returns a string:

def per_user_mem_limit(spawner):

username = spawner.user.name ram_limits = {‘alice’: ‘4G’, ‘bob’: ‘2G’} return ram_limits.get(username, ‘1G’)

c.DockerSpawner.mem_limit = per_user_mem_limit

mounts c.SystemUserSpawner.mounts = List()#

List of dict with keys to match docker.types.Mount for more advanced configuration of mouted volumes. As with volumes, if the default format_volume_name is in use, you can use {username} in the source or target paths, and it will be replaced with the current user’s name.

move_certs_image c.SystemUserSpawner.move_certs_image = Unicode('busybox:1.30.1')#

The image used to stage internal SSL certificates.

Busybox is used because we just need an empty container that waits while we stage files into the volume via .put_archive.

name_template c.SystemUserSpawner.name_template = Unicode('')#

Name of the container or service: with {username}, {imagename}, {prefix}, {servername} replacements. {raw_username} can be used for the original, not escaped username (may contain uppercase, special characters). It is important to include {servername} if JupyterHub’s “named servers” are enabled (JupyterHub.allow_named_servers = True). If the server is named, the default name_template is “{prefix}-{username}–{servername}”. If it is unnamed, the default name_template is “{prefix}-{username}”.

Note: when using named servers, it is important that the separator between {username} and {servername} is not a character that can occur in an escaped {username}, and also not the single escape character ‘-‘.

network_name c.SystemUserSpawner.network_name = Unicode('bridge')#

Run the containers on this docker network. If it is an internal docker network, the Hub should be on the same network, as internal docker IP addresses will be used. For bridge networking, external ports will be bound.

notebook_dir c.SystemUserSpawner.notebook_dir = Unicode('')#

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.

oauth_client_allowed_scopes c.SystemUserSpawner.oauth_client_allowed_scopes = Union()#

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.

oauth_roles c.SystemUserSpawner.oauth_roles = Union()#

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.

options_form c.SystemUserSpawner.options_form = Union()#

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:

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.

poll_interval c.SystemUserSpawner.poll_interval = Int(30)#

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.

port c.SystemUserSpawner.port = Int(0)#

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.

post_start_cmd c.SystemUserSpawner.post_start_cmd = UnicodeOrFalse(False)#

If specified, the command will be executed inside the container after starting. Similar to using ‘docker exec’

post_stop_hook c.SystemUserSpawner.post_stop_hook = Any(None)#

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.

pre_spawn_hook c.SystemUserSpawner.pre_spawn_hook = Any(None)#

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:

from subprocess import check_call
def my_hook(spawner):
    username = spawner.user.name
    check_call(['./examples/bootstrap-script/bootstrap.sh', username])

c.Spawner.pre_spawn_hook = my_hook
prefix c.SystemUserSpawner.prefix = Unicode('jupyter')#

Prefix for container names. See name_template for full container name for a particular user’s server.

pull_policy c.SystemUserSpawner.pull_policy = CaselessStrEnum('ifnotpresent')#

The policy for pulling the user docker image.

Choices:

  • ifnotpresent: pull if the image is not already present (default)

  • always: always pull the image to check for updates, even if it is present

  • never: never perform a pull, raise if image is not present

  • skip: never perform a pull, skip the step entirely (like never, but without raising when images are not present; default for swarm)

read_only_volumes c.SystemUserSpawner.read_only_volumes = Dict()#

Map from host file/directory to container file/directory. Volumes specified here will be read-only in the container.

If format_volume_name is not set, default_format_volume_name is used for naming volumes. In this case, if you use {username} in either the host or guest file/directory path, it will be replaced with the current user’s name.

remove c.SystemUserSpawner.remove = Bool(False)#

If True, delete containers when servers are stopped.

This will destroy any data in the container not stored in mounted volumes.

remove_containers c.SystemUserSpawner.remove_containers = Bool(False)#

Deprecated, use DockerSpawner.remove.

run_as_root c.SystemUserSpawner.run_as_root = Bool(False)#

Run the container as root

Relies on the image itself having handling of $NB_UID and $NB_GID options to switch.

This was the default behavior prior to 0.12, but has become opt-in. This enables images to nicely map usernames to userids inside the container.

New in version 0.12.

server_token_scopes c.SystemUserSpawner.server_token_scopes = Union()#

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).

New in version 4.0.

ssl_alt_names c.SystemUserSpawner.ssl_alt_names = List()#

List of SSL alt names

May be set in config if all spawners should have the same value(s), or set at runtime by Spawner that know their names.

ssl_alt_names_include_local c.SystemUserSpawner.ssl_alt_names_include_local = Bool(True)#

Whether to include DNS:localhost, IP:127.0.0.1 in alt names

start(*, image=None, extra_create_kwargs=None, extra_host_config=None)#

start the single-user server in a docker container

start_timeout c.SystemUserSpawner.start_timeout = Int(60)#

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.

tls c.SystemUserSpawner.tls = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_assert_hostname c.SystemUserSpawner.tls_assert_hostname = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_ca c.SystemUserSpawner.tls_ca = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_cert c.SystemUserSpawner.tls_cert = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_config c.SystemUserSpawner.tls_config = Dict()#

Arguments to pass to docker TLS configuration.

See docker.client.TLSConfig constructor for options.

tls_key c.SystemUserSpawner.tls_key = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

tls_verify c.SystemUserSpawner.tls_verify = Any(None)#

Deprecated, use DockerSpawner.tls_config dict to set any TLS options.

use_docker_client_env c.SystemUserSpawner.use_docker_client_env = Bool(True)#

Deprecated. Docker env variables are always used if present.

use_internal_hostname c.SystemUserSpawner.use_internal_hostname = Bool(False)#

Use the docker hostname for connecting.

instead of an IP address. This should work in general when using docker networks, and must be used when internal_ssl is enabled. It is enabled by default if internal_ssl is enabled.

use_internal_ip c.SystemUserSpawner.use_internal_ip = Bool(False)#

Enable the usage of the internal docker ip. This is useful if you are running jupyterhub (as a container) and the user containers within the same docker network. E.g. by mounting the docker socket of the host into the jupyterhub container. Default is True if using a docker network, False if bridge or host networking is used.

user_id Int(-1)#

If system users are being used, then we need to know their user id in order to mount the home directory.

User IDs are looked up in two ways:

  1. stored in the state dict (authenticator can write here)

  2. lookup via pwd

property volume_binds#

The second half of declaring a volume with docker-py happens when you actually call start(). The required format is a dict of dicts that looks like:

{
    host_location: {'bind': container_location, 'ro': True}
}
property volume_mount_points#

Volumes are declared in docker-py in two stages. First, you declare all the locations where you’re going to mount volumes when you call create_container.

Returns a list of all the values in self.volumes or self.read_only_volumes.

volumes c.SystemUserSpawner.volumes = Dict()#

Map from host file/directory to container (guest) file/directory mount point and (optionally) a mode. When specifying the guest mount point (bind) for the volume, you may use a dict or str. If a str, then the volume will default to a read-write (mode=”rw”). With a dict, the bind is identified by “bind” and the “mode” may be one of “rw” (default), “ro” (read-only), “z” (public/shared SELinux volume label), and “Z” (private/unshared SELinux volume label).

If format_volume_name is not set, default_format_volume_name is used for naming volumes. In this case, if you use {username} in either the host or guest file/directory path, it will be replaced with the current user’s name.