How to use the jupyterhub.utils.maybe_future function in jupyterhub

To help you get started, we’ve selected a few jupyterhub examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jupyterhub / jupyterhub / jupyterhub / crypto.py View on Github external
def decrypt(self, encrypted):
        """Decrypt an object with cryptography"""
        self.check_available()
        return maybe_future(self.executor.submit(self._decrypt, encrypted))
github jupyterhub / jupyterhub / jupyterhub / user.py View on Github external
# if left uncaught (see https://github.com/jupyterhub/jupyterhub/issues/2683)
                await maybe_future(authenticator.pre_spawn_start(self, spawner))

            spawner._start_pending = True
            # update spawner start time, and activity for both spawner and user
            self.last_activity = (
                spawner.orm_spawner.started
            ) = spawner.orm_spawner.last_activity = datetime.utcnow()
            db.commit()
            # wait for spawner.start to return
            # run optional preparation work to bootstrap the notebook
            await maybe_future(spawner.run_pre_spawn_hook())
            if self.settings.get('internal_ssl'):
                self.log.debug("Creating internal SSL certs for %s", spawner._log_name)
                hub_paths = await maybe_future(spawner.create_certs())
                spawner.cert_paths = await maybe_future(spawner.move_certs(hub_paths))
            self.log.debug("Calling Spawner.start for %s", spawner._log_name)
            f = maybe_future(spawner.start())
            # commit any changes in spawner.start (always commit db changes before yield)
            db.commit()
            url = await gen.with_timeout(timedelta(seconds=spawner.start_timeout), f)
            if url:
                # get ip, port info from return value of start()
                if isinstance(url, str):
                    # >= 0.9 can return a full URL string
                    pass
                else:
                    # >= 0.7 returns (ip, port)
                    proto = 'https' if self.settings['internal_ssl'] else 'http'
                    url = '%s://%s:%i' % ((proto,) + url)
                urlinfo = urlparse(url)
                server.proto = urlinfo.scheme
github jupyterhub / jupyterhub / jupyterhub / user.py View on Github external
spawner.oauth_client_id.split('-', 1)[1],
                )
                for oauth_client in self.db.query(orm.OAuthClient).filter(
                    orm.OAuthClient.identifier.in_(client_ids)
                ):
                    self.log.debug("Deleting oauth client %s", oauth_client.identifier)
                    self.db.delete(oauth_client)
            self.db.commit()
            self.log.debug("Finished stopping %s", spawner._log_name)
            RUNNING_SERVERS.dec()
        finally:
            spawner.server = None
            spawner.orm_spawner.started = None
            self.db.commit()
            # trigger post-stop hook
            await maybe_future(spawner.run_post_stop_hook())
            # trigger post-spawner hook on authenticator
            auth = spawner.authenticator
            try:
                if auth:
                    await maybe_future(auth.post_spawn_stop(self, spawner))
            except Exception:
                self.log.exception(
                    "Error in Authenticator.post_spawn_stop for %s", self
                )
            spawner._stop_pending = False
            if not (
                spawner._spawn_future
                and (
                    not spawner._spawn_future.done()
                    or spawner._spawn_future.exception()
                )
github NERSC / sshspawner / sshspawner / sshspawner.py View on Github external
async def select_remote_host(self):
        """TBD"""
        if self.remote_host_selector:
            remote_host = await maybe_future(self.remote_host_selector(self))
        else:
            remote_host = random.choice(self.remote_hosts)
        return remote_host
github bluedatainc / jupyterhub-samlauthenticator / samlauthenticator / samlauthenticator.py View on Github external
async def _shutdown_servers(self, user):
                active_servers = [
                    name
                    for (name, spawner) in user.spawners.items()
                    if spawner.active and not spawner.pending
                ]
                if active_servers:
                    self.log.debug("Shutting down %s's servers", user.name)
                    futures = []
                    for server_name in active_servers:
                        futures.append(maybe_future(self.stop_single_user(user, server_name)))
                    await asyncio.gather(*futures)
github jupyterhub / jupyterhub / jupyterhub / handlers / base.py View on Github external
self.log.exception("Failed to add %s to proxy!", user_server_name)
                self.log.error("Stopping %s to avoid inconsistent state", user_server_name)
                await user.stop()
                PROXY_ADD_DURATION_SECONDS.labels(
                    status='failure'
                ).observe(
                    time.perf_counter() - proxy_add_start_time
                )
            else:
                spawner.add_poll_callback(self.user_stopped, user, server_name)
            finally:
                spawner._proxy_pending = False

        # hook up spawner._spawn_future so that other requests can await
        # this result
        finish_spawn_future = spawner._spawn_future = maybe_future(finish_user_spawn())

        def _clear_spawn_future(f):
            # clear spawner._spawn_future when it's done
            # keep an exception around, though, to prevent repeated implicit spawns
            # if spawn is failing
            if f.exception() is None:
                spawner._spawn_future = None
            # Now we're all done. clear _spawn_pending flag
            spawner._spawn_pending = False

        finish_spawn_future.add_done_callback(_clear_spawn_future)

        # when spawn finishes (success or failure)
        # update failure count and abort if consecutive failure limit
        # is reached
        def _track_failure_count(f):
github jupyterhub / jupyterhub / jupyterhub / auth.py View on Github external
async def add_user(self, user):
        """Hook called whenever a new user is added

        If self.create_system_users, the user will attempt to be created if it doesn't exist.
        """
        user_exists = await maybe_future(self.system_user_exists(user))
        if not user_exists:
            if self.create_system_users:
                await maybe_future(self.add_system_user(user))
            else:
                raise KeyError(
                    "User {} does not exist on the system."
                    " Set LocalAuthenticator.create_system_users=True"
                    " to automatically create system users from jupyterhub users.".format(
                        user.name
                    )
                )

        await maybe_future(super().add_user(user))
github jupyterhub / jupyterhub / jupyterhub / apihandlers / users.py View on Github external
raise web.HTTPError(404)
        if user.name == self.current_user.name:
            raise web.HTTPError(400, "Cannot delete yourself!")
        if user.spawner._stop_pending:
            raise web.HTTPError(
                400, "%s's server is in the process of stopping, please wait." % name
            )
        if user.running:
            await self.stop_single_user(user)
            if user.spawner._stop_pending:
                raise web.HTTPError(
                    400,
                    "%s's server is in the process of stopping, please wait." % name,
                )

        await maybe_future(self.authenticator.delete_user(user))
        # remove from registry
        self.users.delete(user)

        self.set_status(204)
github jupyterhub / jupyterhub / jupyterhub / auth.py View on Github external
async def add_user(self, user):
        """Hook called whenever a new user is added

        If self.create_system_users, the user will attempt to be created if it doesn't exist.
        """
        user_exists = await maybe_future(self.system_user_exists(user))
        if not user_exists:
            if self.create_system_users:
                await maybe_future(self.add_system_user(user))
            else:
                raise KeyError(
                    "User {} does not exist on the system."
                    " Set LocalAuthenticator.create_system_users=True"
                    " to automatically create system users from jupyterhub users.".format(
                        user.name
                    )
                )

        await maybe_future(super().add_user(user))
github jupyterhub / jupyterhub / jupyterhub / handlers / base.py View on Github external
def authenticate(self, data):
        return maybe_future(self.authenticator.get_authenticated_user(self, data))