def init_db(fname: str, path: str = None): if path: db_path = pathlib.Path(path) / fname else: db_path = pathlib.Path(fname) if db_path.exists(): db_path.unlink() db_url = f"sqlite:///{db_path}" session_factory = new_session_factory(url=db_url) db = session_factory() users = [ User(name="Alice", admin=True), User(name="Bob", admin=False), User(name="Charlie", admin=False), ] groups = [ Group(name="group1", users=[users[0], users[1]]), Group(name="group2", users=[users[0], users[2]]), Group(name="group3", users=[users[1], users[2]]), ] projects = [ Project(name="project1", groups=[groups[0], groups[1]]), Project(name="project2", groups=[groups[1], groups[2]]), ] items = users + groups + projects for item in items: db.add(item) db.commit() return db
def init_db(self): """Create the database connection""" urlinfo = urlparse(self.db_url) if urlinfo.password: # avoid logging the database password urlinfo = urlinfo._replace(netloc='{}:[redacted]@{}:{}'.format( urlinfo.username, urlinfo.hostname, urlinfo.port)) db_log_url = urlinfo.geturl() else: db_log_url = self.db_url self.log.debug("Connecting to db: %s", db_log_url) try: self.session_factory = jhorm.new_session_factory( self.db_url, reset=self.reset_db, echo=self.debug_db, **self.db_kwargs) self.db = self.session_factory() except OperationalError as e: self.log.error("Failed to connect to db: %s", db_log_url) self.log.debug("Database error was:", exc_info=True) if self.db_url.startswith('sqlite:///'): self._check_db_path(self.db_url.split(':///', 1)[1]) self.log.critical('\n'.join([ "If you recently upgraded JupyterHub, try running", " jupyterhub upgrade-db", "to upgrade your JupyterHub database schema", ])) self.exit(1) except jhorm.DatabaseSchemaMismatch as e: self.exit(e)
def __init__(self, db_url='sqlite:////srv/jupyterhub/jupyterhub.sqlite', db=None): if db is not None: self.session = db else: session_factory = orm.new_session_factory(db_url) self.session = session_factory()
def get_db(): """Get a db session""" db = orm.new_session_factory('sqlite:///:memory:', echo=True)() user = orm.User( name=getuser(), server=orm.Server(), ) hub = orm.Hub( server=orm.Server(), ) db.add(user) db.add(hub) db.commit() return db
def init_db(self): """Create the database connection""" self.log.debug("Connecting to db: %s", self.db_url) try: self.session_factory = orm.new_session_factory(self.db_url, reset=self.reset_db, echo=self.debug_db, **self.db_kwargs) # trigger constructing thread local db property _ = self.db except OperationalError as e: self.log.error("Failed to connect to db: %s", self.db_url) self.log.debug("Database error was:", exc_info=True) if self.db_url.startswith('sqlite:///'): self._check_db_path(self.db_url.split(':///', 1)[1]) self.log.critical('\n'.join([ "If you recently upgraded JupyterHub, try running", " jupyterhub upgrade-db", "to upgrade your JupyterHub database schema", ])) self.exit(1)
def populate_db(url): """Populate a jupyterhub database""" connect_args = {} if 'mysql' in url: connect_args['auth_plugin'] = 'mysql_native_password' db = orm.new_session_factory(url, connect_args=connect_args)() # create some users admin = orm.User(name='admin', admin=True) db.add(admin) user = orm.User(name='has-server') db.add(user) db.commit() # create a group g = orm.Group(name='group') db.add(g) db.commit() g.users.append(user) db.commit() service = orm.Service(name='service') db.add(service) db.commit() # create some API tokens user.new_api_token() admin.new_api_token() # services got API tokens in 0.7 if jupyterhub.version_info >= (0, 7): # create a group service.new_api_token() # Create a Spawner for user if jupyterhub.version_info >= (0, 8): # create spawner for user spawner = orm.Spawner(name='', user=user) db.add(spawner) db.commit() spawner.server = orm.Server() db.commit() # admin's spawner is not running spawner = orm.Spawner(name='', user=admin) db.add(spawner) db.commit() else: user.server = orm.Server() db.commit() # create some oauth objects client = orm.OAuthClient(identifier='oauth-client') db.add(client) db.commit() code = orm.OAuthCode(client_id=client.identifier) db.add(code) db.commit() if jupyterhub.version_info < (2, 0): Token = partial( orm.OAuthAccessToken, grant_type=orm.GrantType.authorization_code, ) else: Token = orm.APIToken access_token = Token( client_id=client.identifier, user_id=user.id, ) db.add(access_token) db.commit() # set some timestamps added in 0.9 assert user.created assert admin.created # set last_activity user.last_activity = datetime.utcnow() spawner = user.orm_spawners[''] spawner.started = datetime.utcnow() spawner.last_activity = datetime.utcnow() db.commit()
def populate_db(url): """Populate a jupyterhub database""" connect_args = {} if 'mysql' in url: connect_args['auth_plugin'] = 'mysql_native_password' db = orm.new_session_factory(url, connect_args=connect_args)() # create some users admin = orm.User(name='admin', admin=True) db.add(admin) user = orm.User(name='has-server') db.add(user) db.commit() # create a group g = orm.Group(name='group') db.add(g) db.commit() g.users.append(user) db.commit() service = orm.Service(name='service') db.add(service) db.commit() # create some API tokens user.new_api_token() admin.new_api_token() # services got API tokens in 0.7 if jupyterhub.version_info >= (0, 7): # create a group service.new_api_token() # Create a Spawner for user if jupyterhub.version_info >= (0, 8): # create spawner for user spawner = orm.Spawner(name='', user=user) db.add(spawner) db.commit() spawner.server = orm.Server() db.commit() # admin's spawner is not running spawner = orm.Spawner(name='', user=admin) db.add(spawner) db.commit() else: user.server = orm.Server() db.commit() # create some oauth objects if jupyterhub.version_info >= (0, 8): # create oauth client client = orm.OAuthClient(identifier='oauth-client') db.add(client) db.commit() code = orm.OAuthCode(client_id=client.identifier) db.add(code) db.commit() access_token = orm.OAuthAccessToken( client_id=client.identifier, user_id=user.id, grant_type=orm.GrantType.authorization_code, ) db.add(access_token) db.commit() # set some timestamps added in 0.9 if jupyterhub.version_info >= (0, 9): assert user.created assert admin.created # set last_activity user.last_activity = datetime.utcnow() spawner = user.orm_spawners[''] spawner.started = datetime.utcnow() spawner.last_activity = datetime.utcnow() db.commit()
def populate_db(url): """Populate a jupyterhub database""" connect_args = {} if 'mysql' in url: connect_args['auth_plugin'] = 'mysql_native_password' db = orm.new_session_factory(url, connect_args=connect_args)() if jupyterhub.version_info >= (2, ): if (not db.query(orm.OAuthClient).filter_by( identifier="jupyterhub").one_or_none()): # create the oauth client for jupyterhub itself # this allows us to distinguish between orphaned tokens # (failed cascade deletion) and tokens issued by the hub # it has no client_secret, which means it cannot be used # to make requests client = orm.OAuthClient( identifier="jupyterhub", secret="", redirect_uri="", description="JupyterHub", ) db.add(client) db.commit() from jupyterhub import roles for role in roles.get_default_roles(): roles.create_role(db, role) # create some users admin = orm.User(name='admin', admin=True) db.add(admin) user = orm.User(name='has-server') db.add(user) db.commit() # create a group g = orm.Group(name='group') db.add(g) db.commit() g.users.append(user) db.commit() service = orm.Service(name='service') db.add(service) db.commit() # create some API tokens user.new_api_token() admin.new_api_token() # services got API tokens in 0.7 if jupyterhub.version_info >= (0, 7): # create a group service.new_api_token() # Create a Spawner for user if jupyterhub.version_info >= (0, 8): # create spawner for user spawner = orm.Spawner(name='', user=user) db.add(spawner) db.commit() spawner.server = orm.Server() db.commit() # admin's spawner is not running spawner = orm.Spawner(name='', user=admin) db.add(spawner) db.commit() else: user.server = orm.Server() db.commit() # create some oauth objects client = orm.OAuthClient(identifier='oauth-client') db.add(client) db.commit() code = orm.OAuthCode(client_id=client.identifier) db.add(code) db.commit() if jupyterhub.version_info < (2, 0): Token = partial( orm.OAuthAccessToken, grant_type=orm.GrantType.authorization_code, ) else: Token = orm.APIToken access_token = Token( client_id=client.identifier, user_id=user.id, ) if jupyterhub.version_info >= (2, ): if jupyterhub.version_info < (2, 2): access_token.roles = [ db.query(orm.Role).filter_by(name="server").one() ] else: access_token.scopes = [f"read:users!user={user.name}"] db.add(access_token) db.commit() # set some timestamps added in 0.9 assert user.created assert admin.created # set last_activity user.last_activity = datetime.utcnow() spawner = user.orm_spawners[''] spawner.started = datetime.utcnow() spawner.last_activity = datetime.utcnow() db.commit()