def post(self): parser = reqparse.RequestParser() parser.add_argument('username', type=str, required=True, help='Username') parser.add_argument('org', type=str, required=True, help='Org for user membership') parser.add_argument('email', type=str, required=True, help='Email address for user') parser.add_argument('parentuser', type=str, required=False, help='Parent user in form of user@org') args = parser.parse_args() try: session = CassandraCluster.getSession( config['cassandra']['auth_keyspace']) checkUserExistsQuery = CassandraCluster.getPreparedStatement( """ SELECT username, org FROM users WHERE org = ? AND username = ? """, keyspace=session.keyspace) results = session.execute(checkUserExistsQuery, (args['org'], args['username']) ).current_rows if len(results) == 0: checkOrgSetting = CassandraCluster.getPreparedStatement( """ SELECT value FROM orgsettings WHERE org = ? AND setting = ? """, keyspace=session.keyspace) results = session.execute(checkOrgSetting, (args['org'], 'registrationOpen') ).current_rows if len(results) == 0 or results[0].value == 0: return {'Message': 'Cannot create user "%s@%s". Organization is ' % (args['username'], args['org']) + 'closed for registrations or does not exist.'}, 400 else: createUserQuery = CassandraCluster.getPreparedStatement( """ INSERT INTO users ( org, username, email, parentuser, createdate ) VALUES ( ?, ?, ?, ?, dateof(now()) ) """, keyspace=session.keyspace) createUserQuery.consistency_level = ConsistencyLevel.QUORUM session.execute(createUserQuery, (args['org'], args['username'], args['email'], args['parentuser']) ) else: return {'Message': 'Cannot create user "%s@%s", as it already exists.' % (args['username'], args['org'])}, 400 except Exception as e: log.error('Exception in Users.Post: %s' % (e,)) return {'ServerError': 500, 'Message': 'There was an error fulfiling your request'}, 500 return {'Message': 'User "%s@%s" created.' % (args['username'], args['org'])}
def setupDB(keyspace, replication_class='SimpleStrategy', replication_factor=1): try: DB.createDB(keyspace, replication_class, replication_factor) except cassandra.AlreadyExists: log.info('Keyspace "%s" already exists (skipping)' % (keyspace,)) session = CassandraCluster.getSession(keyspace) if not DB.tableExists(session.keyspace, 'schema_migrations'): # Create the schema_migrations table. This table stores the history # of schema update scripts that have been run against the # keyspace. try: log.info('Creating Schema Migrations table') session.execute(SimpleStatement( """ CREATE TABLE schema_migrations ( scriptname text, time timestamp, run boolean, failed boolean, error text, content text, PRIMARY KEY (scriptname, time) ) """, consistency_level=ConsistencyLevel.QUORUM)) except Exception as e: log.info('Failed to create Schema Migrations table (Ignoring)') log.debug(str(e)) if not DB.tableExists(session.keyspace, 'schema_migration_requests'): # Create schema_migration_requests table. This table is used to # manage and coordinate multiple nodes requesting schema # update/migrations in order to ensure only one attempts to alter # schema at any time. try: log.info('Creating Schema Migration Requests table') session.execute(SimpleStatement( """ CREATE TABLE schema_migration_requests ( reqid uuid, reqtime timestamp, inprogress boolean, failed boolean, lastupdate timestamp, PRIMARY KEY (reqid) ) """, consistency_level=ConsistencyLevel.QUORUM)) except Exception as e: log.info('Failed to create Schema Migration Requests ' + 'table (Ignoring)') log.debug(str(e)) # Just to prevent race conditions on creation and read time.sleep(1) # Request migration tasks DB.requestMigration(session)
def createDB(keyspace, replication_class, replication_factor, consistency=ConsistencyLevel.QUORUM): session = CassandraCluster.getSession() log.info('Creating Keyspace "%s"' % (keyspace,)) session.execute(SimpleStatement( """ CREATE KEYSPACE %s WITH replication = {'class': '%s', 'replication_factor': %s}; """ % (keyspace, replication_class, replication_factor), consistency_level=consistency))
def tableExists(keyspace, table): """ Determine if the given table exists in the keyspace :keyspace: The keyspace to check for the table :table: Table to check for """ if keyspace is None or table is None: return False session = CassandraCluster.getSession('system') lookuptable = CassandraCluster.getPreparedStatement(""" SELECT columnfamily_name FROM schema_columnfamilies WHERE keyspace_name=? and columnfamily_name=? """, keyspace=session.keyspace) table_count = len(session.execute(lookuptable, (keyspace, table)) .current_rows) return table_count == 1
def get(self, username, org): """ Retrieve basic user record information. """ try: session = CassandraCluster.getSession( config['cassandra']['auth_keyspace']) getUserQuery = CassandraCluster.getPreparedStatement( """ SELECT username, org, parentuser, createdate FROM users WHERE org = ? AND username = ? """, keyspace=session.keyspace) results = session.execute(getUserQuery, (org, username)).current_rows except Exception as e: log.error('Exception on User/get: %s' % str(e)) return {'ServerError': 500, 'Message': 'There was an error fulfiling your request'}, 500 if len(results) == 0: return {'Message': 'No user matched "%s"@"%s"' % (username, org)}, 404 elif len(results) == 1: # dict(zip(n._fields, list(n))) user = { 'username': results[0].username, 'org': results[0].org, 'parentuser': str(results[0].parentuser), 'createdate': str(results[0].createdate) } if results[0].parentuser is not None: user['parentuser'] = results[0].parentuser return user else: return {'RequestError': 400, 'Message': 'Request returned too many results'}, 400
def func_wrapper(*args, **kwargs): return func(*args, session=CassandraCluster.getSession(keyspace), **kwargs)