OmniSciDB  cde582ebc3
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Catalog_Namespace::SysCatalog Class Reference

#include <SysCatalog.h>

+ Inheritance diagram for Catalog_Namespace::SysCatalog:
+ Collaboration diagram for Catalog_Namespace::SysCatalog:

Public Member Functions

void init (const std::string &basePath, std::shared_ptr< Data_Namespace::DataMgr > dataMgr, const AuthMetadata &authMetadata, std::shared_ptr< Calcite > calcite, bool is_new_db, bool aggregator, const std::vector< LeafHostInfo > &string_dict_hosts)
 
std::shared_ptr< Cataloglogin (std::string &db, std::string &username, const std::string &password, UserMetadata &user_meta, bool check_password=true)
 
std::shared_ptr< CatalogswitchDatabase (std::string &dbname, const std::string &username)
 
UserMetadata createUser (std::string const &name, UserAlterations alts, bool is_temporary)
 
void dropUser (const std::string &name)
 
UserMetadata alterUser (std::string const &name, UserAlterations alts)
 
void renameUser (std::string const &old_name, std::string const &new_name)
 
void createDatabase (const std::string &dbname, int owner)
 
void renameDatabase (std::string const &old_name, std::string const &new_name)
 
void dropDatabase (const DBMetadata &db)
 
std::optional< UserMetadatagetUser (std::string const &uname)
 
std::optional< UserMetadatagetUser (int32_t const uid)
 
std::optional< DBMetadatagetDB (std::string const &dbname)
 
std::optional< DBMetadatagetDB (int32_t const dbid)
 
bool getMetadataForUser (const std::string &name, UserMetadata &user)
 
bool getMetadataForUserById (const int32_t idIn, UserMetadata &user)
 
bool checkPasswordForUser (const std::string &passwd, std::string &name, UserMetadata &user)
 
bool getMetadataForDB (const std::string &name, DBMetadata &db)
 
bool getMetadataForDBById (const int32_t idIn, DBMetadata &db)
 
Data_Namespace::DataMgrgetDataMgr () const
 
CalcitegetCalciteMgr () const
 
const std::string & getCatalogBasePath () const
 
SqliteConnectorgetSqliteConnector ()
 
std::list< DBMetadatagetAllDBMetadata ()
 
std::list< UserMetadatagetAllUserMetadata ()
 
std::list< UserMetadatagetAllUserMetadata (const int64_t dbId)
 
DBSummaryList getDatabaseListForUser (const UserMetadata &user)
 
void createDBObject (const UserMetadata &user, const std::string &objectName, DBObjectType type, const Catalog_Namespace::Catalog &catalog, int32_t objectId=-1)
 
void renameDBObject (const std::string &objectName, const std::string &newName, DBObjectType type, int32_t objectId, const Catalog_Namespace::Catalog &catalog)
 
void grantDBObjectPrivileges (const std::string &grantee, const DBObject &object, const Catalog_Namespace::Catalog &catalog)
 
void grantDBObjectPrivilegesBatch (const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivileges (const std::string &grantee, const DBObject &object, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivilegesBatch (const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivilegesFromAll (DBObject object, Catalog *catalog)
 
void revokeDBObjectPrivilegesFromAll_unsafe (DBObject object, Catalog *catalog)
 
void revokeDBObjectPrivilegesFromAllBatch (std::vector< DBObject > &objects, Catalog *catalog)
 
void revokeDBObjectPrivilegesFromAllBatch_unsafe (std::vector< DBObject > &objects, Catalog *catalog)
 
void getDBObjectPrivileges (const std::string &granteeName, DBObject &object, const Catalog_Namespace::Catalog &catalog) const
 
bool verifyDBObjectOwnership (const UserMetadata &user, DBObject object, const Catalog_Namespace::Catalog &catalog)
 
void changeDBObjectOwnership (const UserMetadata &new_owner, const UserMetadata &previous_owner, DBObject object, const Catalog_Namespace::Catalog &catalog, bool revoke_privileges=true)
 
void createRole (const std::string &roleName, const bool user_private_role, const bool is_temporary=false)
 
void dropRole (const std::string &roleName, const bool is_temporary=false)
 
void grantRoleBatch (const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
 
void grantRole (const std::string &role, const std::string &grantee, const bool is_temporary=false)
 
void revokeRoleBatch (const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
 
void revokeRole (const std::string &role, const std::string &grantee, const bool is_temporary=false)
 
bool hasAnyPrivileges (const UserMetadata &user, std::vector< DBObject > &privObjects)
 
bool checkPrivileges (const UserMetadata &user, const std::vector< DBObject > &privObjects) const
 
bool checkPrivileges (const std::string &userName, const std::vector< DBObject > &privObjects) const
 
GranteegetGrantee (const std::string &name) const
 
RolegetRoleGrantee (const std::string &name) const
 
UsergetUserGrantee (const std::string &name) const
 
std::vector
< ObjectRoleDescriptor * > 
getMetadataForObject (int32_t dbId, int32_t dbType, int32_t objectId) const
 
std::vector< ObjectRoleDescriptorgetMetadataForAllObjects () const
 
bool isRoleGrantedToGrantee (const std::string &granteeName, const std::string &roleName, bool only_direct) const
 
std::vector< std::string > getRoles (const std::string &user_name, bool effective=true)
 
std::vector< std::string > getRoles (bool include_user_private_role, bool is_super, const std::string &user_name, bool ignore_deleted_user=false)
 
std::vector< std::string > getRoles (const std::string &userName, const int32_t dbId)
 
std::set< std::string > getCreatedRoles () const
 
bool isAggregator () const
 
void populateRoleDbObjects (const std::vector< DBObject > &objects)
 
std::string name () const
 
void renameObjectsInDescriptorMap (DBObject &object, const Catalog_Namespace::Catalog &cat)
 
void syncUserWithRemoteProvider (const std::string &user_name, std::vector< std::string > idp_roles, UserAlterations alts)
 
std::unordered_map
< std::string, std::vector
< std::string > > 
getGranteesOfSharedDashboards (const std::vector< std::string > &dashboard_ids)
 
void check_for_session_encryption (const std::string &pki_cert, std::string &session)
 
std::vector< Catalog * > getCatalogsForAllDbs ()
 
std::shared_ptr< CataloggetCatalog (const std::string &dbName)
 
std::shared_ptr< CataloggetCatalog (const int32_t db_id)
 
std::shared_ptr< CataloggetCatalog (const DBMetadata &curDB, bool is_new_db)
 
void removeCatalog (const std::string &dbName)
 
virtual ~SysCatalog ()
 
void reassignObjectOwners (const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects, int32_t new_owner_id, const Catalog_Namespace::Catalog &catalog)
 
bool hasExecutedMigration (const std::string &migration_name) const
 

Static Public Member Functions

static SysCataloginstance ()
 
static void destroy ()
 

Public Attributes

std::unique_ptr
< heavyai::DistributedSharedMutex
dcatalogMutex_
 
std::unique_ptr
< heavyai::DistributedSharedMutex
dsqliteMutex_
 
std::mutex sqliteMutex_
 
heavyai::shared_mutex sharedMutex_
 
std::atomic< std::thread::id > thread_holding_sqlite_lock
 
std::atomic< std::thread::id > thread_holding_write_lock
 
std::shared_ptr< CatalogdummyCatalog_
 
std::unordered_map
< std::string, std::shared_ptr
< UserMetadata > > 
temporary_users_by_name_
 
std::unordered_map< int32_t,
std::shared_ptr< UserMetadata > > 
temporary_users_by_id_
 
int32_t next_temporary_user_id_ {shared::kTempUserIdRange}
 

Static Public Attributes

static thread_local bool thread_holds_read_lock = false
 

Private Types

using GranteeMap = std::map< std::string, std::unique_ptr< Grantee >>
 
using ObjectRoleDescriptorMap = std::multimap< std::string, std::unique_ptr< ObjectRoleDescriptor >>
 
using dbid_to_cat_map = tbb::concurrent_hash_map< std::string, std::shared_ptr< Catalog >>
 

Private Member Functions

 SysCatalog ()
 
void initDB ()
 
void buildMaps (bool is_new_db=false)
 
void buildMapsUnlocked (bool is_new_db=false)
 
void buildRoleMapUnlocked ()
 
void buildUserRoleMapUnlocked ()
 
void buildObjectDescriptorMapUnlocked ()
 
void rebuildObjectMapsUnlocked ()
 
void checkAndExecuteMigrations ()
 
void importDataFromOldMapdDB ()
 
void createRoles ()
 
void fixRolesMigration ()
 
void addAdminUserRole ()
 
void migratePrivileges ()
 
void migratePrivileged_old ()
 
void updateUserSchema ()
 
void updatePasswordsToHashes ()
 
void updateBlankPasswordsToRandom ()
 
void updateSupportUserDeactivation ()
 
void migrateDBAccessPrivileges ()
 
void loginImpl (std::string &username, const std::string &password, UserMetadata &user_meta)
 
bool checkPasswordForUserImpl (const std::string &passwd, std::string &name, UserMetadata &user)
 
void grantDefaultPrivilegesToRole_unsafe (const std::string &name, bool issuper)
 
void createRole_unsafe (const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
 
void dropRole_unsafe (const std::string &roleName, const bool is_temporary)
 
void grantRoleBatch_unsafe (const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
 
void grantRole_unsafe (const std::string &roleName, const std::string &granteeName, const bool is_temporary)
 
void revokeRoleBatch_unsafe (const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
 
void revokeRole_unsafe (const std::string &roleName, const std::string &granteeName, const bool is_temporary)
 
void updateObjectDescriptorMap (const std::string &roleName, DBObject &object, bool roleType, const Catalog_Namespace::Catalog &cat)
 
void deleteObjectDescriptorMap (const std::string &roleName)
 
void deleteObjectDescriptorMap (const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &cat)
 
void grantDBObjectPrivilegesBatch_unsafe (const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
 
void grantDBObjectPrivileges_unsafe (const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivilegesBatch_unsafe (const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivileges_unsafe (const std::string &granteeName, DBObject object, const Catalog_Namespace::Catalog &catalog)
 
void grantAllOnDatabase_unsafe (const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &catalog)
 
void revokeAllOnDatabase_unsafe (const std::string &roleName, int32_t dbId, Grantee *grantee)
 
bool isDashboardSystemRole (const std::string &roleName) const
 
void updateUserRoleName (const std::string &roleName, const std::string &newName)
 
void getMetadataWithDefaultDB (std::string &dbname, const std::string &username, Catalog_Namespace::DBMetadata &db_meta, UserMetadata &user_meta)
 
bool allowLocalLogin () const
 
template<typename F , typename... Args>
void execInTransaction (F &&f, Args &&...args)
 
void initializeInformationSchemaDb ()
 
void recordExecutedMigration (const std::string &migration_name) const
 
bool hasVersionHistoryTable () const
 
void createVersionHistoryTable () const
 
auto yieldTransactionStreamer ()
 
- Private Member Functions inherited from Catalog_Namespace::CommonFileOperations
 CommonFileOperations (std::string const &base_path)
 
void removeCatalogByFullPath (std::string const &full_path)
 
void removeCatalogByName (std::string const &name)
 
auto duplicateAndRenameCatalog (std::string const &current_name, std::string const &new_name)
 
auto assembleCatalogName (std::string const &name)
 

Private Attributes

std::string basePath_
 
GranteeMap granteeMap_
 
ObjectRoleDescriptorMap objectDescriptorMap_
 
std::unique_ptr< SqliteConnectorsqliteConnector_
 
std::shared_ptr
< Data_Namespace::DataMgr
dataMgr_
 
std::unique_ptr< PkiServerpki_server_
 
const AuthMetadataauthMetadata_
 
std::shared_ptr< CalcitecalciteMgr_
 
std::vector< LeafHostInfostring_dict_hosts_
 
bool aggregator_
 
dbid_to_cat_map cat_map_
 

Static Private Attributes

static std::unique_ptr
< SysCatalog
instance_
 

Detailed Description

Definition at line 166 of file SysCatalog.h.

Member Typedef Documentation

using Catalog_Namespace::SysCatalog::dbid_to_cat_map = tbb::concurrent_hash_map<std::string, std::shared_ptr<Catalog>>
private

Definition at line 497 of file SysCatalog.h.

using Catalog_Namespace::SysCatalog::GranteeMap = std::map<std::string, std::unique_ptr<Grantee>>
private

Definition at line 386 of file SysCatalog.h.

using Catalog_Namespace::SysCatalog::ObjectRoleDescriptorMap = std::multimap<std::string, std::unique_ptr<ObjectRoleDescriptor>>
private

Definition at line 388 of file SysCatalog.h.

Constructor & Destructor Documentation

Catalog_Namespace::SysCatalog::~SysCatalog ( )
virtual

Definition at line 268 of file SysCatalog.cpp.

References cat_map_, granteeMap_, and objectDescriptorMap_.

268  {
269  // TODO(sy): Need to lock here to wait for other threads to complete before pulling out
270  // the rug from under them. Unfortunately this lock was seen to deadlock because the
271  // HeavyDB shutdown sequence needs cleanup. Do we even need these clear()'s anymore?
272  // sys_write_lock write_lock(this);
273  granteeMap_.clear();
274  objectDescriptorMap_.clear();
275  cat_map_.clear();
276 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
Catalog_Namespace::SysCatalog::SysCatalog ( )
private

Definition at line 260 of file SysCatalog.cpp.

References basePath_.

Referenced by instance().

262  , aggregator_{false}
263  , sqliteMutex_{}
264  , sharedMutex_{}
265  , thread_holding_sqlite_lock{std::thread::id()}
266  , thread_holding_write_lock{std::thread::id()} {}
std::atomic< std::thread::id > thread_holding_sqlite_lock
Definition: SysCatalog.h:507
heavyai::shared_mutex sharedMutex_
Definition: SysCatalog.h:506
CommonFileOperations(std::string const &base_path)
Definition: SysCatalog.h:149
std::atomic< std::thread::id > thread_holding_write_lock
Definition: SysCatalog.h:508

+ Here is the caller graph for this function:

Member Function Documentation

void Catalog_Namespace::SysCatalog::addAdminUserRole ( )
private

Definition at line 619 of file SysCatalog.cpp.

References createRole_unsafe(), shared::kRootUsername, and sqliteConnector_.

Referenced by checkAndExecuteMigrations().

619  {
620  sys_sqlite_lock sqlite_lock(this);
621  sqliteConnector_->query("BEGIN TRANSACTION");
622  try {
623  sqliteConnector_->query(
624  "SELECT roleName FROM mapd_object_permissions WHERE roleName = \'" +
625  shared::kRootUsername + "\'");
626  if (sqliteConnector_->getNumRows() != 0) {
627  // already done
628  sqliteConnector_->query("END TRANSACTION");
629  return;
630  }
631 
633  shared::kRootUsername, /*userPrivateRole=*/true, /*is_temporary=*/false);
634  } catch (const std::exception&) {
635  sqliteConnector_->query("ROLLBACK TRANSACTION");
636  throw;
637  }
638  sqliteConnector_->query("END TRANSACTION");
639 }
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
const std::string kRootUsername

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::allowLocalLogin ( ) const
private

For servers configured to use external authentication providers, determine whether users will be allowed to fallback to local login accounts. If no external providers are configured, returns true.

UserMetadata Catalog_Namespace::SysCatalog::alterUser ( std::string const &  name,
UserAlterations  alts 
)

Definition at line 1138 of file SysCatalog.cpp.

References Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::append_with_commas, Catalog_Namespace::UserMetadata::can_login, Catalog_Namespace::UserAlterations::can_login, CHECK, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::UserAlterations::default_db, Catalog_Namespace::UserMetadata::defaultDbId, Catalog_Namespace::g_log_user_id, getMetadataForDB(), getMetadataForUser(), getUser(), anonymous_namespace{SysCatalog.cpp}::hash_with_bcrypt(), Catalog_Namespace::UserAlterations::is_super, Catalog_Namespace::UserMetadata::is_temporary, Catalog_Namespace::UserMetadata::isSuper, name(), Catalog_Namespace::UserAlterations::passwd, Catalog_Namespace::UserMetadata::passwd_hash, sqliteConnector_, temporary_users_by_name_, to_string(), Catalog_Namespace::UserMetadata::userId, VLOG, and Catalog_Namespace::UserAlterations::wouldChange().

Referenced by syncUserWithRemoteProvider().

1138  {
1139  sys_write_lock write_lock(this);
1140  sys_sqlite_lock sqlite_lock(this);
1141 
1142  UserMetadata user;
1143  if (!getMetadataForUser(name, user)) {
1144  std::string const loggable = g_log_user_id ? std::string("") : name + ' ';
1145  throw runtime_error("Cannot alter user. User " + loggable + "does not exist.");
1146  }
1147  if (!alts.wouldChange(user)) {
1148  return user;
1149  }
1150 
1151  // Temporary user.
1152  if (user.is_temporary) {
1153  if (alts.passwd) {
1154  user.passwd_hash = hash_with_bcrypt(*alts.passwd);
1155  }
1156  if (alts.is_super) {
1157  user.isSuper = *alts.is_super;
1158  }
1159  if (alts.default_db) {
1160  if (!alts.default_db->empty()) {
1161  DBMetadata db;
1162  if (!getMetadataForDB(*alts.default_db, db)) {
1163  throw runtime_error(string("DEFAULT_DB ") + *alts.default_db + " not found.");
1164  }
1165  user.defaultDbId = db.dbId;
1166  } else {
1167  user.defaultDbId = -1;
1168  }
1169  }
1170  if (alts.can_login) {
1171  user.can_login = *alts.can_login;
1172  }
1173  *temporary_users_by_name_[name] = user;
1174  return user;
1175  }
1176 
1177  // Normal user.
1178  sqliteConnector_->query("BEGIN TRANSACTION");
1179  try {
1180  string sql;
1181  std::vector<std::string> values;
1182  if (alts.passwd) {
1183  append_with_commas(sql, "passwd_hash = ?");
1184  values.push_back(hash_with_bcrypt(*alts.passwd));
1185  }
1186  if (alts.is_super) {
1187  append_with_commas(sql, "issuper = ?");
1188  values.push_back(std::to_string(*alts.is_super));
1189  }
1190  if (alts.default_db) {
1191  if (!alts.default_db->empty()) {
1192  append_with_commas(sql, "default_db = ?");
1193  DBMetadata db;
1194  if (!getMetadataForDB(*alts.default_db, db)) {
1195  throw runtime_error(string("DEFAULT_DB ") + *alts.default_db + " not found.");
1196  }
1197  values.push_back(std::to_string(db.dbId));
1198  } else {
1199  append_with_commas(sql, "default_db = NULL");
1200  }
1201  }
1202  if (alts.can_login) {
1203  append_with_commas(sql, "can_login = ?");
1204  values.push_back(std::to_string(*alts.can_login));
1205  }
1206 
1207  sql = "UPDATE mapd_users SET " + sql + " WHERE userid = ?";
1208  values.push_back(std::to_string(user.userId));
1209 
1210  sqliteConnector_->query_with_text_params(sql, values);
1211  } catch (const std::exception& e) {
1212  sqliteConnector_->query("ROLLBACK TRANSACTION");
1213  throw;
1214  }
1215  sqliteConnector_->query("END TRANSACTION");
1216  auto u = getUser(name);
1217  CHECK(u);
1218  VLOG(1) << "Altered user: " << u->userLoggable();
1219  return *u;
1220 }
std::optional< UserMetadata > getUser(std::string const &uname)
Definition: SysCatalog.h:197
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string name() const
Definition: SysCatalog.h:350
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:512
std::string hash_with_bcrypt(const std::string &pwd)
Definition: SysCatalog.cpp:71
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
#define CHECK(condition)
Definition: Logger.h:222
#define VLOG(n)
Definition: Logger.h:316
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::buildMaps ( bool  is_new_db = false)
private

Definition at line 207 of file SysCatalog.cpp.

207  {
209  sys_sqlite_lock sqlite_lock(this);
210 
211  buildMapsUnlocked(is_new_db);
212 }
heavyai::unique_lock< heavyai::shared_mutex > write_lock
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
void buildMapsUnlocked(bool is_new_db=false)
Definition: SysCatalog.cpp:214
void Catalog_Namespace::SysCatalog::buildMapsUnlocked ( bool  is_new_db = false)
private

Definition at line 214 of file SysCatalog.cpp.

References CHECK, shared::kSystemCatalogName, run_benchmark_import::result, to_upper(), Catalog_Namespace::UserMetadata::userName, and VLOG.

214  {
215  VLOG(2) << "reloading catalog caches for: " << shared::kSystemCatalogName;
216 
217  // Store permissions for temporary users.
218  std::map<std::string, std::vector<std::string>> tu_map;
219  for (auto& pair : temporary_users_by_name_) {
220  CHECK(pair.second);
221  UserMetadata& user = *pair.second;
222  auto it = granteeMap_.find(to_upper(user.userName));
223  CHECK(it != granteeMap_.end()) << to_upper(user.userName) << " not found";
224 
225  auto user_rl = dynamic_cast<User*>(it->second.get());
226  CHECK(user_rl);
227  std::vector<std::string> current_roles = user_rl->getRoles();
228  auto result = tu_map.emplace(user.userName, std::move(current_roles));
229  CHECK(result.second);
230  }
231 
232  // Forget permissions and reload them from file storage.
236  if (!is_new_db) {
237  // We don't want to create the information schema db during database initialization
238  // because we don't have the appropriate context to intialize the tables. For
239  // instance if the server is intended to run in distributed mode, initializing the
240  // table as part of initdb will be missing information such as the location of the
241  // string dictionary server.
243  }
244 
245  // Restore permissions for temporary users that were stored above.
246  for (auto& pair : temporary_users_by_name_) {
247  CHECK(pair.second);
248  UserMetadata& user = *pair.second;
249 
250  createRole_unsafe(user.userName, /*user_private_role*/ true, /*is_temporary*/ true);
251 
252  auto it = tu_map.find(user.userName);
253  CHECK(it != tu_map.end()) << user.userName << " not found";
254  for (const auto& r : it->second) {
255  grantRole_unsafe(r, user.userName, /*is_temporary*/ true);
256  }
257  }
258 }
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
const std::string kSystemCatalogName
Definition: Grantee.h:75
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:512
void grantRole_unsafe(const std::string &roleName, const std::string &granteeName, const bool is_temporary)
std::string to_upper(const std::string &str)
#define CHECK(condition)
Definition: Logger.h:222
#define VLOG(n)
Definition: Logger.h:316

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::buildObjectDescriptorMapUnlocked ( )
private

Definition at line 2667 of file SysCatalog.cpp.

References objectDescriptorMap_, sqliteConnector_, and to_string().

Referenced by rebuildObjectMapsUnlocked().

2667  {
2668  objectDescriptorMap_.clear();
2669  string objectQuery(
2670  "SELECT roleName, roleType, objectPermissionsType, dbId, objectId, "
2671  "objectPermissions, objectOwnerId, objectName "
2672  "from mapd_object_permissions");
2673  sqliteConnector_->query(objectQuery);
2674  size_t numRows = sqliteConnector_->getNumRows();
2675  for (size_t r = 0; r < numRows; ++r) {
2676  auto od = std::make_unique<ObjectRoleDescriptor>();
2677  od->roleName = sqliteConnector_->getData<string>(r, 0);
2678  od->roleType = sqliteConnector_->getData<bool>(r, 1);
2679  od->objectType = sqliteConnector_->getData<int>(r, 2);
2680  od->dbId = sqliteConnector_->getData<int>(r, 3);
2681  od->objectId = sqliteConnector_->getData<int>(r, 4);
2682  od->privs.privileges = sqliteConnector_->getData<int>(r, 5);
2683  od->objectOwnerId = sqliteConnector_->getData<int>(r, 6);
2684  od->objectName = sqliteConnector_->getData<string>(r, 7);
2685  objectDescriptorMap_.insert(ObjectRoleDescriptorMap::value_type(
2686  std::to_string(od->dbId) + ":" + std::to_string(od->objectType) + ":" +
2687  std::to_string(od->objectId),
2688  std::move(od)));
2689  }
2690 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
std::string to_string(char const *&&v)
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::buildRoleMapUnlocked ( )
private

Definition at line 2552 of file SysCatalog.cpp.

References DatabaseDBObjectType, DBObjectKey::fromString(), getGrantee(), granteeMap_, name(), AccessPrivileges::privileges, sqliteConnector_, and to_upper().

Referenced by rebuildObjectMapsUnlocked().

2552  {
2553  granteeMap_.clear();
2554  string roleQuery(
2555  "SELECT roleName, roleType, objectPermissionsType, dbId, objectId, "
2556  "objectPermissions, objectOwnerId, objectName "
2557  "from mapd_object_permissions");
2558  sqliteConnector_->query(roleQuery);
2559  size_t numRows = sqliteConnector_->getNumRows();
2560  std::vector<std::string> objectKeyStr(4);
2561  DBObjectKey objectKey;
2562  AccessPrivileges privs;
2563  bool userPrivateRole{false};
2564  for (size_t r = 0; r < numRows; ++r) {
2565  std::string roleName = sqliteConnector_->getData<string>(r, 0);
2566  userPrivateRole = sqliteConnector_->getData<bool>(r, 1);
2567  DBObjectType permissionType =
2568  static_cast<DBObjectType>(sqliteConnector_->getData<int>(r, 2));
2569  objectKeyStr[0] = sqliteConnector_->getData<string>(r, 2);
2570  objectKeyStr[1] = sqliteConnector_->getData<string>(r, 3);
2571  objectKeyStr[2] = sqliteConnector_->getData<string>(r, 4);
2572  objectKey = DBObjectKey::fromString(objectKeyStr, permissionType);
2573  privs.privileges = sqliteConnector_->getData<int>(r, 5);
2574  int32_t owner = sqliteConnector_->getData<int>(r, 6);
2575  std::string name = sqliteConnector_->getData<string>(r, 7);
2576 
2577  DBObject dbObject(objectKey, privs, owner);
2578  dbObject.setName(name);
2579  if (-1 == objectKey.objectId) {
2580  dbObject.setObjectType(DBObjectType::DatabaseDBObjectType);
2581  } else {
2582  dbObject.setObjectType(permissionType);
2583  }
2584 
2585  auto* rl = getGrantee(roleName);
2586  if (!rl) {
2587  std::unique_ptr<Grantee> g;
2588  if (userPrivateRole) {
2589  g.reset(new User(roleName));
2590  } else {
2591  g.reset(new Role(roleName));
2592  }
2593  rl = g.get();
2594  granteeMap_[to_upper(roleName)] = std::move(g);
2595  }
2596  rl->grantPrivileges(dbObject);
2597  }
2598 }
DBObjectType
Definition: DBObject.h:40
std::string name() const
Definition: SysCatalog.h:350
Definition: Grantee.h:75
Grantee * getGrantee(const std::string &name) const
Definition: Grantee.h:81
static DBObjectKey fromString(const std::vector< std::string > &key, const DBObjectType &type)
Definition: DBObject.cpp:270
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::string to_upper(const std::string &str)
int64_t privileges
Definition: DBObject.h:133

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::buildUserRoleMapUnlocked ( )
private

Definition at line 2623 of file SysCatalog.cpp.

References getGrantee(), shared::kRootUsername, and sqliteConnector_.

2623  {
2624  std::vector<std::pair<std::string, std::string>> granteeRoles;
2625  string userRoleQuery("SELECT roleName, userName from mapd_roles");
2626  sqliteConnector_->query(userRoleQuery);
2627  size_t numRows = sqliteConnector_->getNumRows();
2628  for (size_t r = 0; r < numRows; ++r) {
2629  std::string roleName = sqliteConnector_->getData<string>(r, 0);
2630  std::string userName = sqliteConnector_->getData<string>(r, 1);
2631  // required for declared nomenclature before v4.0.0
2632  if ((boost::equals(roleName, "mapd_default_suser_role") &&
2633  boost::equals(userName, shared::kRootUsername)) ||
2634  (boost::equals(roleName, "mapd_default_user_role") &&
2635  !boost::equals(userName, "mapd_default_user_role"))) {
2636  // grouprole already exists with roleName==userName in mapd_roles table
2637  // ignore duplicate instances of userRole which exists before v4.0.0
2638  continue;
2639  }
2640  auto* rl = getGrantee(roleName);
2641  if (!rl) {
2642  throw runtime_error("Data inconsistency when building role map. Role " + roleName +
2643  " from db not found in the map.");
2644  }
2645  std::pair<std::string, std::string> roleVecElem(roleName, userName);
2646  granteeRoles.push_back(roleVecElem);
2647  }
2648 
2649  for (const auto& [roleName, granteeName] : granteeRoles) {
2650  auto* grantee = getGrantee(granteeName);
2651  if (!grantee) {
2652  throw runtime_error("Data inconsistency when building role map. Grantee " +
2653  granteeName + " not found in the map.");
2654  }
2655  if (granteeName == roleName) {
2656  continue;
2657  }
2658  Role* rl = dynamic_cast<Role*>(getGrantee(roleName));
2659  if (!rl) {
2660  throw runtime_error("Data inconsistency when building role map. Role " + roleName +
2661  " not found in the map.");
2662  }
2663  grantee->grantRole(rl);
2664  }
2665 }
Grantee * getGrantee(const std::string &name) const
Definition: Grantee.h:81
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
const std::string kRootUsername

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::changeDBObjectOwnership ( const UserMetadata new_owner,
const UserMetadata previous_owner,
DBObject  object,
const Catalog_Namespace::Catalog catalog,
bool  revoke_privileges = true 
)

Change ownership of a DBObject

Parameters
new_owner- new owner of DBObject
previous_owner- previous owner of DBObject
object- DBObject to change ownership of
catalog- Catalog instance object exists in
revoke_privileges- if true, revoke previous_owner's privileges

Definition at line 2037 of file SysCatalog.cpp.

References AccessPrivileges::ALL_DASHBOARD, AccessPrivileges::ALL_DATABASE, AccessPrivileges::ALL_SERVER, AccessPrivileges::ALL_TABLE, AccessPrivileges::ALL_VIEW, DashboardDBObjectType, DatabaseDBObjectType, grantDBObjectPrivileges_unsafe(), granteeMap_, Catalog_Namespace::UserMetadata::is_temporary, Catalog_Namespace::UserMetadata::isSuper, objectDescriptorMap_, rebuildObjectMapsUnlocked(), revokeDBObjectPrivileges_unsafe(), ServerDBObjectType, sqliteConnector_, TableDBObjectType, to_string(), UNREACHABLE, Catalog_Namespace::UserMetadata::userId, Catalog_Namespace::UserMetadata::userName, and ViewDBObjectType.

2041  {
2042  sys_write_lock write_lock(this);
2043  if (new_owner.is_temporary || previous_owner.is_temporary) {
2044  throw std::runtime_error("ownership change not allowed for temporary user(s)");
2045  }
2046  sys_sqlite_lock sqlite_lock(this);
2047  object.loadKey(catalog);
2048  switch (object.getType()) {
2049  case TableDBObjectType:
2050  object.setPrivileges(AccessPrivileges::ALL_TABLE);
2051  break;
2052  case DashboardDBObjectType:
2053  object.setPrivileges(AccessPrivileges::ALL_DASHBOARD);
2054  break;
2055  case ServerDBObjectType:
2056  object.setPrivileges(AccessPrivileges::ALL_SERVER);
2057  break;
2058  case DatabaseDBObjectType:
2059  object.setPrivileges(AccessPrivileges::ALL_DATABASE);
2060  break;
2061  case ViewDBObjectType:
2062  object.setPrivileges(AccessPrivileges::ALL_VIEW);
2063  break;
2064  default:
2065  UNREACHABLE(); // unkown object type
2066  break;
2067  }
2068  sqliteConnector_->query("BEGIN TRANSACTION");
2069  try {
2070  if (!new_owner.isSuper) { // no need to grant to suser, has all privs by default
2071  grantDBObjectPrivileges_unsafe(new_owner.userName, object, catalog);
2072  }
2073  if (!previous_owner.isSuper && revoke_privileges) { // no need to revoke from suser
2074  revokeDBObjectPrivileges_unsafe(previous_owner.userName, object, catalog);
2075  }
2076  auto object_key = object.getObjectKey();
2077  sqliteConnector_->query_with_text_params(
2078  "UPDATE mapd_object_permissions SET objectOwnerId = ? WHERE dbId = ? AND "
2079  "objectId = ? AND objectPermissionsType = ?",
2080  std::vector<std::string>{std::to_string(new_owner.userId),
2081  std::to_string(object_key.dbId),
2082  std::to_string(object_key.objectId),
2083  std::to_string(object_key.permissionType)});
2084 
2085  for (const auto& [user_or_role, grantee] : granteeMap_) {
2086  grantee->reassignObjectOwner(object_key, new_owner.userId);
2087  }
2088 
2089  for (const auto& [map_object_key, map_object_descriptor] : objectDescriptorMap_) {
2090  if (map_object_descriptor->objectId == object_key.objectId &&
2091  map_object_descriptor->objectType == object_key.permissionType &&
2092  map_object_descriptor->dbId == object_key.dbId) {
2093  map_object_descriptor->objectOwnerId = new_owner.userId;
2094  }
2095  }
2096  } catch (std::exception& e) {
2097  sqliteConnector_->query("ROLLBACK TRANSACTION");
2099  throw;
2100  }
2101  sqliteConnector_->query("END TRANSACTION");
2102 }
static const AccessPrivileges ALL_DATABASE
Definition: DBObject.h:151
void revokeDBObjectPrivileges_unsafe(const std::string &granteeName, DBObject object, const Catalog_Namespace::Catalog &catalog)
#define UNREACHABLE()
Definition: Logger.h:266
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::string to_string(char const *&&v)
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
static const AccessPrivileges ALL_VIEW
Definition: DBObject.h:177
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
static const AccessPrivileges ALL_SERVER
Definition: DBObject.h:187
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:169
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:157

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::check_for_session_encryption ( const std::string &  pki_cert,
std::string &  session 
)

Definition at line 918 of file SysCatalog.cpp.

References pki_server_.

919  {
920  if (!pki_server_->inUse()) {
921  return;
922  }
923  pki_server_->encrypt_session(pki_cert, session);
924 }
std::unique_ptr< PkiServer > pki_server_
Definition: SysCatalog.h:487
void Catalog_Namespace::SysCatalog::checkAndExecuteMigrations ( )
private

Definition at line 321 of file SysCatalog.cpp.

References addAdminUserRole(), createRoles(), fixRolesMigration(), migrateDBAccessPrivileges(), migratePrivileged_old(), migratePrivileges(), updateBlankPasswordsToRandom(), updatePasswordsToHashes(), updateSupportUserDeactivation(), and updateUserSchema().

321  {
323  createRoles();
327  updateUserSchema(); // must come before updatePasswordsToHashes()
329  updateBlankPasswordsToRandom(); // must come after updatePasswordsToHashes()
332 }

+ Here is the call graph for this function:

bool Catalog_Namespace::SysCatalog::checkPasswordForUser ( const std::string &  passwd,
std::string &  name,
UserMetadata user 
)

Definition at line 1523 of file SysCatalog.cpp.

References checkPasswordForUserImpl().

Referenced by loginImpl().

1525  {
1526  return checkPasswordForUserImpl(passwd, name, user);
1527 }
std::string name() const
Definition: SysCatalog.h:350
bool checkPasswordForUserImpl(const std::string &passwd, std::string &name, UserMetadata &user)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::checkPasswordForUserImpl ( const std::string &  passwd,
std::string &  name,
UserMetadata user 
)
private

Definition at line 1529 of file SysCatalog.cpp.

References CHECK, getMetadataForUser(), LOG, Catalog_Namespace::UserMetadata::passwd_hash, and logger::WARNING.

Referenced by checkPasswordForUser().

1531  {
1532  sys_read_lock read_lock(this);
1533  if (!getMetadataForUser(name, user)) {
1534  // Check password against some fake hash just to waste time so that response times
1535  // for invalid password and invalid user are similar and a caller can't say the
1536  // difference
1537  char fake_hash[BCRYPT_HASHSIZE];
1538  CHECK(bcrypt_gensalt(-1, fake_hash) == 0);
1539  bcrypt_checkpw(passwd.c_str(), fake_hash);
1540  LOG(WARNING) << "Local login failed";
1541  return false;
1542  }
1543  int pwd_check_result = bcrypt_checkpw(passwd.c_str(), user.passwd_hash.c_str());
1544  // if the check fails there is a good chance that data on disc is broken
1545  CHECK(pwd_check_result >= 0);
1546  return pwd_check_result == 0;
1547 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
#define LOG(tag)
Definition: Logger.h:216
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string name() const
Definition: SysCatalog.h:350
#define CHECK(condition)
Definition: Logger.h:222
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::checkPrivileges ( const UserMetadata user,
const std::vector< DBObject > &  privObjects 
) const

Definition at line 2380 of file SysCatalog.cpp.

References getUserGrantee(), instance(), Catalog_Namespace::UserMetadata::isSuper, Catalog_Namespace::UserMetadata::userLoggable(), and Catalog_Namespace::UserMetadata::userName.

Referenced by Catalog_Namespace::SessionInfo::checkDBAccessPrivileges(), checkPrivileges(), getDatabaseListForUser(), and switchDatabase().

2381  {
2382  sys_read_lock read_lock(this);
2383  if (user.isSuper) {
2384  return true;
2385  }
2386 
2387  auto* user_rl = instance().getUserGrantee(user.userName);
2388  if (!user_rl) {
2389  throw runtime_error("Cannot check privileges. User " + user.userLoggable() +
2390  " does not exist.");
2391  }
2392  for (auto& object : privObjects) {
2393  if (!user_rl->checkPrivileges(object)) {
2394  return false;
2395  }
2396  }
2397  return true;
2398 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
static SysCatalog & instance()
Definition: SysCatalog.h:337
User * getUserGrantee(const std::string &name) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::checkPrivileges ( const std::string &  userName,
const std::vector< DBObject > &  privObjects 
) const

Definition at line 2400 of file SysCatalog.cpp.

References checkPrivileges(), Catalog_Namespace::g_log_user_id, getMetadataForUser(), and instance().

2401  {
2402  UserMetadata user;
2403  if (!instance().getMetadataForUser(userName, user)) {
2404  std::string const loggable = g_log_user_id ? std::string("") : userName + ' ';
2405  throw runtime_error("Request to check privileges for user " + loggable +
2406  "failed because user with this name does not exist.");
2407  }
2408  return (checkPrivileges(user, privObjects));
2409 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
bool checkPrivileges(const UserMetadata &user, const std::vector< DBObject > &privObjects) const
static SysCatalog & instance()
Definition: SysCatalog.h:337

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::createDatabase ( const std::string &  dbname,
int  owner 
)

Definition at line 1357 of file SysCatalog.cpp.

References basePath_, cat(), CHECK, DatabaseDBObjectType, g_enable_fsi, getCatalog(), Catalog_Namespace::Catalog::getCustomExpressionsSchema(), Catalog_Namespace::Catalog::getForeignServerSchema(), Catalog_Namespace::Catalog::getForeignTableSchema(), getMetadataForDB(), getMetadataForUserById(), grantAllOnDatabase_unsafe(), shared::kCatalogDirectoryName, shared::kRootUserId, shared::kSystemCatalogName, removeCatalog(), sqliteConnector_, to_string(), to_upper(), and Catalog_Namespace::UserMetadata::userName.

Referenced by initDB(), and initializeInformationSchemaDb().

1357  {
1358  sys_write_lock write_lock(this);
1359  sys_sqlite_lock sqlite_lock(this);
1360 
1361  DBMetadata db;
1362  if (getMetadataForDB(name, db)) {
1363  throw runtime_error("Database " + name + " already exists.");
1364  }
1366  throw runtime_error("Database name " + name + " is reserved.");
1367  }
1368 
1369  std::unique_ptr<SqliteConnector> dbConn(
1371  // NOTE(max): it's okay to run this in a separate transaction. If we fail later
1372  // we delete the database anyways.
1373  // If we run it in the same transaction as SysCatalog functions, then Catalog
1374  // constructor won't find the tables we have just created.
1375  dbConn->query("BEGIN TRANSACTION");
1376  try {
1377  dbConn->query(
1378  "CREATE TABLE mapd_tables (tableid integer primary key, name text unique, userid "
1379  "integer, ncolumns integer, "
1380  "isview boolean, "
1381  "fragments text, frag_type integer, max_frag_rows integer, max_chunk_size "
1382  "bigint, "
1383  "frag_page_size integer, "
1384  "max_rows bigint, partitions text, shard_column_id integer, shard integer, "
1385  "sort_column_id integer default 0, storage_type text default '', "
1386  "max_rollback_epochs integer default -1, "
1387  "is_system_table boolean default 0, "
1388  "num_shards integer, key_metainfo TEXT, version_num "
1389  "BIGINT DEFAULT 1) ");
1390  dbConn->query(
1391  "CREATE TABLE mapd_columns (tableid integer references mapd_tables, columnid "
1392  "integer, name text, coltype "
1393  "integer, colsubtype integer, coldim integer, colscale integer, is_notnull "
1394  "boolean, compression integer, "
1395  "comp_param integer, size integer, chunks text, is_systemcol boolean, "
1396  "is_virtualcol boolean, virtual_expr "
1397  "text, is_deletedcol boolean, version_num BIGINT, default_value text, "
1398  "primary key(tableid, columnid), unique(tableid, name))");
1399  dbConn->query(
1400  "CREATE TABLE mapd_views (tableid integer references mapd_tables, sql text)");
1401  dbConn->query(
1402  "CREATE TABLE mapd_dashboards (id integer primary key autoincrement, name text , "
1403  "userid integer references mapd_users, state text, image_hash text, update_time "
1404  "timestamp, "
1405  "metadata text, UNIQUE(userid, name) )");
1406  dbConn->query(
1407  "CREATE TABLE mapd_links (linkid integer primary key, userid integer references "
1408  "mapd_users, "
1409  "link text unique, view_state text, update_time timestamp, view_metadata text)");
1410  dbConn->query(
1411  "CREATE TABLE mapd_dictionaries (dictid integer primary key, name text unique, "
1412  "nbits int, is_shared boolean, "
1413  "refcount int, version_num BIGINT DEFAULT 1)");
1414  dbConn->query(
1415  "CREATE TABLE mapd_logical_to_physical(logical_table_id integer, "
1416  "physical_table_id "
1417  "integer)");
1418  dbConn->query("CREATE TABLE mapd_record_ownership_marker (dummy integer)");
1419  dbConn->query_with_text_params(
1420  "INSERT INTO mapd_record_ownership_marker (dummy) VALUES (?1)",
1421  std::vector<std::string>{std::to_string(owner)});
1422 
1423  if (g_enable_fsi) {
1424  dbConn->query(Catalog::getForeignServerSchema());
1425  dbConn->query(Catalog::getForeignTableSchema());
1426  }
1427  dbConn->query(Catalog::getCustomExpressionsSchema());
1428  } catch (const std::exception&) {
1429  dbConn->query("ROLLBACK TRANSACTION");
1430  boost::filesystem::remove(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
1431  name);
1432  throw;
1433  }
1434  dbConn->query("END TRANSACTION");
1435 
1436  std::shared_ptr<Catalog> cat;
1437  // Now update SysCatalog with privileges and the new database
1438  sqliteConnector_->query("BEGIN TRANSACTION");
1439  try {
1440  sqliteConnector_->query_with_text_param(
1441  "INSERT INTO mapd_databases (name, owner) VALUES (?, " + std::to_string(owner) +
1442  ")",
1443  name);
1444  CHECK(getMetadataForDB(name, db));
1445 
1446  cat = getCatalog(db, true);
1447 
1448  if (owner != shared::kRootUserId) {
1450  object.loadKey(*cat);
1451  UserMetadata user;
1452  CHECK(getMetadataForUserById(owner, user));
1453  grantAllOnDatabase_unsafe(user.userName, object, *cat);
1454  }
1455  } catch (const std::exception&) {
1456  sqliteConnector_->query("ROLLBACK TRANSACTION");
1457  boost::filesystem::remove(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
1458  name);
1459  throw;
1460  }
1461  sqliteConnector_->query("END TRANSACTION");
1462 
1463  // force a migration on the new database
1465  cat = getCatalog(db, false);
1466 
1467  if (g_enable_fsi) {
1468  try {
1469  cat->createDefaultServersIfNotExists();
1470  } catch (...) {
1471  boost::filesystem::remove(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
1472  name);
1473  throw;
1474  }
1475  }
1476 }
const int kRootUserId
std::string cat(Ts &&...args)
void removeCatalog(const std::string &dbName)
std::string name() const
Definition: SysCatalog.h:350
const std::string kSystemCatalogName
heavyai::unique_lock< heavyai::shared_mutex > write_lock
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
void grantAllOnDatabase_unsafe(const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &catalog)
static const std::string getForeignTableSchema(bool if_not_exists=false)
Definition: Catalog.cpp:772
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
static const std::string getForeignServerSchema(bool if_not_exists=false)
Definition: Catalog.cpp:765
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::string to_upper(const std::string &str)
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
static const std::string getCustomExpressionsSchema(bool if_not_exists=false)
Definition: Catalog.cpp:780
const std::string kCatalogDirectoryName
#define CHECK(condition)
Definition: Logger.h:222
bool g_enable_fsi
Definition: Catalog.cpp:96
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createDBObject ( const UserMetadata user,
const std::string &  objectName,
DBObjectType  type,
const Catalog_Namespace::Catalog catalog,
int32_t  objectId = -1 
)

Definition at line 1766 of file SysCatalog.cpp.

References AccessPrivileges::ALL_DASHBOARD, AccessPrivileges::ALL_DATABASE, AccessPrivileges::ALL_SERVER, AccessPrivileges::ALL_TABLE, DashboardDBObjectType, getUserGrantee(), grantDBObjectPrivileges_unsafe(), Grantee::grantPrivileges(), instance(), Catalog_Namespace::UserMetadata::isSuper, ServerDBObjectType, sqliteConnector_, TableDBObjectType, Catalog_Namespace::UserMetadata::userId, Catalog_Namespace::UserMetadata::userLoggable(), and Catalog_Namespace::UserMetadata::userName.

Referenced by CreateForeignServerCommand::execute(), CreateForeignTableCommand::execute(), and EmbeddedDatabase::DBEngineImpl::importArrowTable().

1770  {
1771  sys_write_lock write_lock(this);
1772  sys_sqlite_lock sqlite_lock(this);
1773 
1774  DBObject object =
1775  objectId == -1 ? DBObject(objectName, type) : DBObject(objectId, type);
1776  object.loadKey(catalog);
1777  switch (type) {
1778  case TableDBObjectType:
1779  object.setPrivileges(AccessPrivileges::ALL_TABLE);
1780  break;
1781  case DashboardDBObjectType:
1782  object.setPrivileges(AccessPrivileges::ALL_DASHBOARD);
1783  break;
1784  case ServerDBObjectType:
1785  object.setPrivileges(AccessPrivileges::ALL_SERVER);
1786  break;
1787  default:
1788  object.setPrivileges(AccessPrivileges::ALL_DATABASE);
1789  break;
1790  }
1791  object.setOwner(user.userId);
1792  sqliteConnector_->query("BEGIN TRANSACTION");
1793  try {
1794  if (!user.isSuper) { // no need to grant to suser, has all privs by default
1795  grantDBObjectPrivileges_unsafe(user.userName, object, catalog);
1796  auto* grantee = instance().getUserGrantee(user.userName);
1797  if (!grantee) {
1798  throw runtime_error("Cannot create DBObject. User " + user.userLoggable() +
1799  " does not exist.");
1800  }
1801  grantee->grantPrivileges(object);
1802  }
1803  } catch (std::exception& e) {
1804  sqliteConnector_->query("ROLLBACK TRANSACTION");
1805  throw;
1806  }
1807  sqliteConnector_->query("END TRANSACTION");
1808 }
static const AccessPrivileges ALL_DATABASE
Definition: DBObject.h:151
virtual void grantPrivileges(const DBObject &object)
Definition: Grantee.cpp:105
heavyai::unique_lock< heavyai::shared_mutex > write_lock
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
static SysCatalog & instance()
Definition: SysCatalog.h:337
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
static const AccessPrivileges ALL_SERVER
Definition: DBObject.h:187
User * getUserGrantee(const std::string &name) const
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
void loadKey()
Definition: DBObject.cpp:190
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:169
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:157

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createRole ( const std::string &  roleName,
const bool  user_private_role,
const bool  is_temporary = false 
)

Definition at line 2706 of file SysCatalog.cpp.

References createRole_unsafe(), and execInTransaction().

2708  {
2710  &SysCatalog::createRole_unsafe, roleName, user_private_role, is_temporary);
2711 }
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::createRole_unsafe ( const std::string &  roleName,
const bool  userPrivateRole,
const bool  is_temporary 
)
private

Definition at line 2126 of file SysCatalog.cpp.

References DatabaseDBObjectType, DBObjectKey::dbId, getGrantee(), granteeMap_, Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), shared::kDefaultDbName, DBObjectKey::permissionType, DBObject::setObjectKey(), sqliteConnector_, and to_upper().

Referenced by addAdminUserRole(), createRole(), createUser(), and initDB().

2128  {
2129  sys_write_lock write_lock(this);
2130 
2131  auto* grantee = getGrantee(roleName);
2132  if (grantee) {
2133  throw std::runtime_error("CREATE ROLE " + roleName +
2134  " failed because grantee with this name already exists.");
2135  }
2136  std::unique_ptr<Grantee> g;
2137  if (user_private_role) {
2138  g.reset(new User(roleName));
2139  } else {
2140  g.reset(new Role(roleName));
2141  }
2142  grantee = g.get();
2143  granteeMap_[to_upper(roleName)] = std::move(g);
2144 
2145  // NOTE (max): Why create an empty privileges record for a role?
2146  /* grant none privileges to this role and add it to sqlite DB */
2148  DBObjectKey objKey;
2149  // 0 is an id that does not exist
2150  objKey.dbId = 0;
2152  dbObject.setObjectKey(objKey);
2153  grantee->grantPrivileges(dbObject);
2154 
2155  if (!is_temporary) {
2156  sys_sqlite_lock sqlite_lock(this);
2158  sqliteConnector_, roleName, user_private_role, dbObject);
2159  }
2160 }
Definition: Grantee.h:75
Grantee * getGrantee(const std::string &name) const
Definition: Grantee.h:81
heavyai::unique_lock< heavyai::shared_mutex > write_lock
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:476
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
const std::string kDefaultDbName
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::string to_upper(const std::string &str)
int32_t dbId
Definition: DBObject.h:54
int32_t permissionType
Definition: DBObject.h:53

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createRoles ( )
private

Definition at line 407 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by checkAndExecuteMigrations().

407  {
408  sys_sqlite_lock sqlite_lock(this);
409  sqliteConnector_->query("BEGIN TRANSACTION");
410  try {
411  sqliteConnector_->query(
412  "SELECT name FROM sqlite_master WHERE type='table' AND name='mapd_roles'");
413  if (sqliteConnector_->getNumRows() != 0) {
414  // already done
415  sqliteConnector_->query("END TRANSACTION");
416  return;
417  }
418  sqliteConnector_->query(
419  "CREATE TABLE mapd_roles(roleName text, userName text, UNIQUE(roleName, "
420  "userName))");
421  } catch (const std::exception&) {
422  sqliteConnector_->query("ROLLBACK TRANSACTION");
423  throw;
424  }
425  sqliteConnector_->query("END TRANSACTION");
426 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the caller graph for this function:

UserMetadata Catalog_Namespace::SysCatalog::createUser ( std::string const &  name,
UserAlterations  alts,
bool  is_temporary 
)

Definition at line 926 of file SysCatalog.cpp.

References Catalog_Namespace::UserAlterations::can_login, CHECK, createRole_unsafe(), Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::UserAlterations::default_db, Catalog_Namespace::g_log_user_id, g_read_only, getGrantee(), getMetadataForDB(), getMetadataForUser(), getUser(), anonymous_namespace{SysCatalog.cpp}::hash_with_bcrypt(), Catalog_Namespace::UserAlterations::is_super, name(), next_temporary_user_id_, Catalog_Namespace::UserAlterations::passwd, sqliteConnector_, temporary_users_by_id_, temporary_users_by_name_, to_string(), Catalog_Namespace::UserMetadata::userLoggable(), and VLOG.

Referenced by syncUserWithRemoteProvider().

928  {
930  sys_sqlite_lock sqlite_lock(this);
931 
932  if (!alts.passwd) {
933  alts.passwd = "";
934  }
935  if (!alts.is_super) {
936  alts.is_super = false;
937  }
938  if (!alts.default_db) {
939  alts.default_db = "";
940  }
941  if (!alts.can_login) {
942  alts.can_login = true;
943  }
944 
945  UserMetadata user;
946  if (getMetadataForUser(name, user)) {
947  throw runtime_error("User " + user.userLoggable() + " already exists.");
948  }
949  if (getGrantee(name)) {
950  std::string const loggable = g_log_user_id ? std::string("") : name + ' ';
951  throw runtime_error(
952  "User " + loggable +
953  "is same as one of existing grantees. User and role names should be unique.");
954  }
955  DBMetadata db;
956  if (!alts.default_db->empty()) {
957  if (!getMetadataForDB(*alts.default_db, db)) {
958  throw runtime_error("DEFAULT_DB " + *alts.default_db + " not found.");
959  }
960  }
961 
962  // Temporary user.
963  if (is_temporary) {
964  if (!g_read_only) {
965  throw std::runtime_error("Temporary users require read-only mode.");
966  // NOTE(sy): We can remove this restriction when we're confident that
967  // nothing permanent can depend on a temporary user.
968  }
969  auto user2 = std::make_shared<UserMetadata>(next_temporary_user_id_++,
970  name,
971  hash_with_bcrypt(*alts.passwd),
972  *alts.is_super,
973  !alts.default_db->empty() ? db.dbId : -1,
974  *alts.can_login,
975  true);
977  temporary_users_by_id_[user2->userId] = user2;
978  createRole_unsafe(name, /*userPrivateRole=*/true, /*is_temporary=*/true);
979  VLOG(1) << "Created temporary user: " << user2->userLoggable();
980  return *user2;
981  }
982 
983  // Normal user.
984  sqliteConnector_->query("BEGIN TRANSACTION");
985  try {
986  std::vector<std::string> vals;
987  if (!alts.default_db->empty()) {
988  vals = {name,
989  hash_with_bcrypt(*alts.passwd),
990  std::to_string(*alts.is_super),
991  std::to_string(db.dbId),
992  std::to_string(*alts.can_login)};
993  sqliteConnector_->query_with_text_params(
994  "INSERT INTO mapd_users (name, passwd_hash, issuper, default_db, can_login) "
995  "VALUES (?, ?, ?, ?, ?)",
996  vals);
997  } else {
998  vals = {name,
999  hash_with_bcrypt(*alts.passwd),
1000  std::to_string(*alts.is_super),
1001  std::to_string(*alts.can_login)};
1002  sqliteConnector_->query_with_text_params(
1003  "INSERT INTO mapd_users (name, passwd_hash, issuper, can_login) "
1004  "VALUES (?, ?, ?, ?)",
1005  vals);
1006  }
1007  createRole_unsafe(name, /*userPrivateRole=*/true, /*is_temporary=*/false);
1008  } catch (const std::exception& e) {
1009  sqliteConnector_->query("ROLLBACK TRANSACTION");
1010  throw;
1011  }
1012  sqliteConnector_->query("END TRANSACTION");
1013  auto u = getUser(name);
1014  CHECK(u);
1015  VLOG(1) << "Created user: " << u->userLoggable();
1016  return *u;
1017 }
std::optional< UserMetadata > getUser(std::string const &uname)
Definition: SysCatalog.h:197
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string name() const
Definition: SysCatalog.h:350
Grantee * getGrantee(const std::string &name) const
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:512
std::string hash_with_bcrypt(const std::string &pwd)
Definition: SysCatalog.cpp:71
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
bool g_read_only
Definition: File.cpp:40
std::unordered_map< int32_t, std::shared_ptr< UserMetadata > > temporary_users_by_id_
Definition: SysCatalog.h:513
#define CHECK(condition)
Definition: Logger.h:222
#define VLOG(n)
Definition: Logger.h:316
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createVersionHistoryTable ( ) const
private

Definition at line 3039 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by recordExecutedMigration().

3039  {
3040  sys_sqlite_lock sqlite_lock(this);
3041  sqliteConnector_->query(
3042  "CREATE TABLE mapd_version_history(version integer, migration_history text "
3043  "unique)");
3044 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::deleteObjectDescriptorMap ( const std::string &  roleName)
private

Definition at line 2328 of file SysCatalog.cpp.

References objectDescriptorMap_.

Referenced by dropUser(), and revokeDBObjectPrivileges_unsafe().

2328  {
2329  sys_write_lock write_lock(this);
2330 
2331  for (auto d = objectDescriptorMap_.begin(); d != objectDescriptorMap_.end();) {
2332  if (d->second->roleName == roleName) {
2333  d = objectDescriptorMap_.erase(d);
2334  } else {
2335  d++;
2336  }
2337  }
2338 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
heavyai::unique_lock< heavyai::shared_mutex > write_lock
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::deleteObjectDescriptorMap ( const std::string &  roleName,
DBObject object,
const Catalog_Namespace::Catalog cat 
)
private

Definition at line 2341 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::Catalog::getCurrentDB(), objectDescriptorMap_, and to_string().

2343  {
2344  sys_write_lock write_lock(this);
2345  auto range = objectDescriptorMap_.equal_range(
2346  std::to_string(cat.getCurrentDB().dbId) + ":" +
2347  std::to_string(object.getObjectKey().permissionType) + ":" +
2348  std::to_string(object.getObjectKey().objectId));
2349  for (auto d = range.first; d != range.second;) {
2350  // remove the entry
2351  if (d->second->roleName == roleName) {
2352  d = objectDescriptorMap_.erase(d);
2353  } else {
2354  d++;
2355  }
2356  }
2357 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::string to_string(char const *&&v)
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:242
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122

+ Here is the call graph for this function:

static void Catalog_Namespace::SysCatalog::destroy ( )
inlinestatic

Definition at line 344 of file SysCatalog.h.

References migrations::MigrationMgr::destroy(), and instance_.

Referenced by main(), EmbeddedDatabase::DBEngineImpl::reset(), and DBHandler::shutdown().

344  {
345  instance_.reset();
347  }
static std::unique_ptr< SysCatalog > instance_
Definition: SysCatalog.h:500

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::dropDatabase ( const DBMetadata db)

Definition at line 1478 of file SysCatalog.cpp.

References cat(), DashboardDBObjectType, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, getCatalog(), granteeMap_, removeCatalog(), revokeAllOnDatabase_unsafe(), revokeDBObjectPrivilegesFromAll_unsafe(), sqliteConnector_, TableDBObjectType, run_benchmark_import::tables, and to_string().

Referenced by initializeInformationSchemaDb().

1478  {
1479  auto cat = getCatalog(db, false);
1480  cat->eraseDbPhysicalData();
1481  sys_write_lock write_lock(this);
1482  sys_sqlite_lock sqlite_lock(this);
1483  sqliteConnector_->query("BEGIN TRANSACTION");
1484  try {
1485  // remove this database ID from any users that have it set as their default database
1486  sqliteConnector_->query_with_text_param(
1487  "UPDATE mapd_users SET default_db = NULL WHERE default_db = ?",
1488  std::to_string(db.dbId));
1489  /* revoke object privileges to all tables of the database being dropped */
1490  const auto tables = cat->getAllTableMetadata();
1491  for (const auto table : tables) {
1492  if (table->shard >= 0) {
1493  // skip shards, they're not standalone tables
1494  continue;
1495  }
1497  DBObject(table->tableName, TableDBObjectType), cat.get());
1498  }
1499  const auto dashboards = cat->getAllDashboardsMetadata();
1500  for (const auto dashboard : dashboards) {
1502  DBObject(dashboard->dashboardId, DashboardDBObjectType), cat.get());
1503  }
1504  /* revoke object privileges to the database being dropped */
1505  for (const auto& grantee : granteeMap_) {
1506  if (grantee.second->hasAnyPrivilegesOnDb(db.dbId, true)) {
1508  grantee.second->getName(), db.dbId, grantee.second.get());
1509  }
1510  }
1511  sqliteConnector_->query_with_text_param("DELETE FROM mapd_databases WHERE dbid = ?",
1512  std::to_string(db.dbId));
1513  cat->eraseDbMetadata();
1514  removeCatalog(db.dbName);
1515  } catch (const std::exception&) {
1516  sqliteConnector_->query("ROLLBACK TRANSACTION");
1517  throw;
1518  }
1519  sqliteConnector_->query("END TRANSACTION");
1520 }
void revokeAllOnDatabase_unsafe(const std::string &roleName, int32_t dbId, Grantee *grantee)
std::string cat(Ts &&...args)
void removeCatalog(const std::string &dbName)
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
void revokeDBObjectPrivilegesFromAll_unsafe(DBObject object, Catalog *catalog)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::dropRole ( const std::string &  roleName,
const bool  is_temporary = false 
)

Definition at line 2713 of file SysCatalog.cpp.

References dropRole_unsafe(), and execInTransaction().

2713  {
2714  execInTransaction(&SysCatalog::dropRole_unsafe, roleName, is_temporary);
2715 }
void execInTransaction(F &&f, Args &&...args)
void dropRole_unsafe(const std::string &roleName, const bool is_temporary)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::dropRole_unsafe ( const std::string &  roleName,
const bool  is_temporary 
)
private

Definition at line 2162 of file SysCatalog.cpp.

References granteeMap_, objectDescriptorMap_, sqliteConnector_, and to_upper().

Referenced by dropRole(), and dropUser().

2162  {
2163  sys_write_lock write_lock(this);
2164 
2165  for (auto d = objectDescriptorMap_.begin(); d != objectDescriptorMap_.end();) {
2166  if (d->second->roleName == roleName) {
2167  d = objectDescriptorMap_.erase(d);
2168  } else {
2169  d++;
2170  }
2171  }
2172  // it may very well be a user "role", so keep it generic
2173  granteeMap_.erase(to_upper(roleName));
2174 
2175  if (!is_temporary) {
2176  sys_sqlite_lock sqlite_lock(this);
2177  sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE roleName = ?",
2178  roleName);
2179  sqliteConnector_->query_with_text_param(
2180  "DELETE FROM mapd_object_permissions WHERE roleName = ?", roleName);
2181  }
2182 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
heavyai::unique_lock< heavyai::shared_mutex > write_lock
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::string to_upper(const std::string &str)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::dropUser ( const std::string &  name)

Definition at line 1019 of file SysCatalog.cpp.

References CHECK, deleteObjectDescriptorMap(), dropRole_unsafe(), Catalog_Namespace::g_log_user_id, getMetadataForUser(), Catalog_Namespace::UserMetadata::is_temporary, sqliteConnector_, temporary_users_by_id_, temporary_users_by_name_, to_string(), and Catalog_Namespace::UserMetadata::userId.

1019  {
1020  sys_write_lock write_lock(this);
1021  sys_sqlite_lock sqlite_lock(this);
1022 
1023  UserMetadata user;
1024  if (!getMetadataForUser(name, user)) {
1025  std::string const loggable = g_log_user_id ? std::string("") : name + ' ';
1026  throw runtime_error("Cannot drop user. User " + loggable + "does not exist.");
1027  }
1028 
1029  // Temporary user.
1030  if (user.is_temporary) {
1031  auto it1 = temporary_users_by_name_.find(name);
1032  CHECK(it1 != temporary_users_by_name_.end());
1033  auto it2 = temporary_users_by_id_.find(it1->second->userId);
1034  CHECK(it2 != temporary_users_by_id_.end());
1035  dropRole_unsafe(name, /*is_temporary=*/true);
1037  temporary_users_by_name_.erase(it1);
1038  temporary_users_by_id_.erase(it2);
1039  return;
1040  }
1041 
1042  // Normal user.
1043 
1044  sqliteConnector_->query("BEGIN TRANSACTION");
1045  try {
1046  dropRole_unsafe(name, /*is_temporary=*/false);
1048  const std::string& roleName(name);
1049  sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE userName = ?",
1050  roleName);
1051  sqliteConnector_->query("DELETE FROM mapd_users WHERE userid = " +
1052  std::to_string(user.userId));
1053  sqliteConnector_->query("DELETE FROM mapd_privileges WHERE userid = " +
1054  std::to_string(user.userId));
1055  } catch (const std::exception& e) {
1056  sqliteConnector_->query("ROLLBACK TRANSACTION");
1057  throw;
1058  }
1059  sqliteConnector_->query("END TRANSACTION");
1060 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string name() const
Definition: SysCatalog.h:350
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:512
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
void dropRole_unsafe(const std::string &roleName, const bool is_temporary)
void deleteObjectDescriptorMap(const std::string &roleName)
std::unordered_map< int32_t, std::shared_ptr< UserMetadata > > temporary_users_by_id_
Definition: SysCatalog.h:513
#define CHECK(condition)
Definition: Logger.h:222

+ Here is the call graph for this function:

template<typename F , typename... Args>
void Catalog_Namespace::SysCatalog::execInTransaction ( F &&  f,
Args &&...  args 
)
private

Definition at line 2693 of file SysCatalog.cpp.

References run_benchmark_import::args, anonymous_namespace{Utm.h}::f, and sqliteConnector_.

Referenced by createRole(), dropRole(), grantDBObjectPrivileges(), grantDBObjectPrivilegesBatch(), grantRole(), grantRoleBatch(), revokeDBObjectPrivileges(), revokeDBObjectPrivilegesBatch(), revokeDBObjectPrivilegesFromAll(), revokeDBObjectPrivilegesFromAllBatch(), revokeRole(), and revokeRoleBatch().

2693  {
2694  sys_write_lock write_lock(this);
2695  sys_sqlite_lock sqlite_lock(this);
2696  sqliteConnector_->query("BEGIN TRANSACTION");
2697  try {
2698  (this->*f)(std::forward<Args>(args)...);
2699  } catch (std::exception&) {
2700  sqliteConnector_->query("ROLLBACK TRANSACTION");
2701  throw;
2702  }
2703  sqliteConnector_->query("END TRANSACTION");
2704 }
heavyai::unique_lock< heavyai::shared_mutex > write_lock
constexpr double f
Definition: Utm.h:31
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::fixRolesMigration ( )
private

Definition at line 434 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by checkAndExecuteMigrations().

434  {
435  sys_sqlite_lock sqlite_lock(this);
436  sqliteConnector_->query("BEGIN TRANSACTION");
437  try {
438  sqliteConnector_->query("SELECT name FROM mapd_users");
439  auto num_rows = sqliteConnector_->getNumRows();
440  std::vector<std::string> user_names;
441  for (size_t i = 0; i < num_rows; ++i) {
442  user_names.push_back(sqliteConnector_->getData<std::string>(i, 0));
443  }
444  for (const auto& user_name : user_names) {
445  sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE roleName = ?",
446  user_name);
447  }
448  } catch (const std::exception&) {
449  sqliteConnector_->query("ROLLBACK TRANSACTION");
450  throw;
451  }
452  sqliteConnector_->query("END TRANSACTION");
453 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the caller graph for this function:

list< DBMetadata > Catalog_Namespace::SysCatalog::getAllDBMetadata ( )

Definition at line 1611 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, and sqliteConnector_.

Referenced by getCatalogsForAllDbs(), and getDatabaseListForUser().

1611  {
1612  sys_sqlite_lock sqlite_lock(this);
1613  sqliteConnector_->query("SELECT dbid, name, owner FROM mapd_databases");
1614  int numRows = sqliteConnector_->getNumRows();
1615  list<DBMetadata> db_list;
1616  for (int r = 0; r < numRows; ++r) {
1617  DBMetadata db;
1618  db.dbId = sqliteConnector_->getData<int>(r, 0);
1619  db.dbName = sqliteConnector_->getData<string>(r, 1);
1620  db.dbOwner = sqliteConnector_->getData<int>(r, 2);
1621  db_list.push_back(db);
1622  }
1623  return db_list;
1624 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the caller graph for this function:

list< UserMetadata > Catalog_Namespace::SysCatalog::getAllUserMetadata ( )

Definition at line 1671 of file SysCatalog.cpp.

References Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::get_users(), and sqliteConnector_.

Referenced by Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_user_id_to_user_name_map(), and getDatabaseListForUser().

1671  {
1672  sys_sqlite_lock sqlite_lock(this);
1673  return get_users(*this, sqliteConnector_);
1674 }
auto get_users(SysCatalog &syscat, std::unique_ptr< SqliteConnector > &sqliteConnector, const int32_t dbId=-1)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

list< UserMetadata > Catalog_Namespace::SysCatalog::getAllUserMetadata ( const int64_t  dbId)

return the users associated with the given DB

Definition at line 1664 of file SysCatalog.cpp.

References Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::get_users(), and sqliteConnector_.

1664  {
1665  // this call is to return users that have some form of permissions to objects in the db
1666  // sadly mapd_object_permissions table is also misused to manage user roles.
1667  sys_sqlite_lock sqlite_lock(this);
1668  return get_users(*this, sqliteConnector_, dbId);
1669 }
auto get_users(SysCatalog &syscat, std::unique_ptr< SqliteConnector > &sqliteConnector, const int32_t dbId=-1)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

Calcite& Catalog_Namespace::SysCatalog::getCalciteMgr ( ) const
inline

Definition at line 229 of file SysCatalog.h.

References calciteMgr_.

229 { return *calciteMgr_; }
std::shared_ptr< Calcite > calciteMgr_
Definition: SysCatalog.h:489
std::shared_ptr< Catalog > Catalog_Namespace::SysCatalog::getCatalog ( const std::string &  dbName)

Definition at line 2880 of file SysCatalog.cpp.

References cat_map_, and getMetadataForDB().

Referenced by foreign_storage::anonymous_namespace{LogFileBufferParser.cpp}::add_nonce_values(), foreign_storage::cache_blocks(), createDatabase(), foreign_storage::ForeignDataWrapperFactory::createForeignTableProxy(), foreign_storage::AbstractTextFileDataWrapper::createRenderGroupAnalyzers(), foreign_storage::ParquetDataWrapper::createRenderGroupAnalyzers(), dropDatabase(), foreign_storage::ParquetDataWrapper::fetchChunkMetadata(), foreign_storage::ForeignTableSchema::ForeignTableSchema(), foreign_storage::anonymous_namespace{InternalMemoryStatsDataWrapper.cpp}::get_column_name(), foreign_storage::get_foreign_table_for_key(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_table_ddl(), foreign_storage::get_table_name(), foreign_storage::ParseBufferRequest::getCatalog(), getCatalogsForAllDbs(), foreign_storage::ParquetImportBatchResult::getChunksAndDictionaries(), lockmgr::TableLockMgrImpl< TableDataLockMgr >::getClusterTableMutex(), foreign_storage::ParquetDataWrapper::getColumnsToInitialize(), foreign_storage::init_chunk_for_column(), foreign_storage::Csv::init_chunk_for_column(), PersistentStorageMgr::isForeignStorage(), foreign_storage::ParquetDataWrapper::loadBuffersUsingLazyParquetChunkLoader(), login(), foreign_storage::AbstractTextFileDataWrapper::populateChunkBuffers(), foreign_storage::AbstractTextFileDataWrapper::populateChunkMetadata(), switchDatabase(), and foreign_storage::AbstractTextFileDataWrapper::updateMetadata().

2880  {
2881  dbid_to_cat_map::const_accessor cata;
2882  if (cat_map_.find(cata, dbName)) {
2883  return cata->second;
2884  } else {
2886  if (getMetadataForDB(dbName, db_meta)) {
2887  return getCatalog(db_meta, false);
2888  } else {
2889  return nullptr;
2890  }
2891  }
2892 }
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::shared_ptr< Catalog > Catalog_Namespace::SysCatalog::getCatalog ( const int32_t  db_id)

Definition at line 2894 of file SysCatalog.cpp.

References cat_map_.

2894  {
2895  dbid_to_cat_map::const_accessor cata;
2896  for (dbid_to_cat_map::iterator cat_it = cat_map_.begin(); cat_it != cat_map_.end();
2897  ++cat_it) {
2898  if (cat_it->second->getDatabaseId() == db_id) {
2899  return cat_it->second;
2900  }
2901  }
2902  return nullptr;
2903 }
std::shared_ptr< Catalog > Catalog_Namespace::SysCatalog::getCatalog ( const DBMetadata curDB,
bool  is_new_db 
)

Definition at line 2905 of file SysCatalog.cpp.

References basePath_, calciteMgr_, cat(), cat_map_, dataMgr_, Catalog_Namespace::DBMetadata::dbName, and string_dict_hosts_.

2905  {
2906  {
2907  dbid_to_cat_map::const_accessor cata;
2908  if (cat_map_.find(cata, curDB.dbName)) {
2909  return cata->second;
2910  }
2911  }
2912 
2913  // Catalog doesnt exist
2914  // has to be made outside of lock as migration uses cat
2915  auto cat = std::make_shared<Catalog>(
2916  basePath_, curDB, dataMgr_, string_dict_hosts_, calciteMgr_, is_new_db);
2917 
2918  dbid_to_cat_map::accessor cata;
2919 
2920  if (cat_map_.find(cata, curDB.dbName)) {
2921  return cata->second;
2922  }
2923 
2924  cat_map_.insert(cata, curDB.dbName);
2925  cata->second = cat;
2926 
2927  return cat;
2928 }
std::string cat(Ts &&...args)
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: SysCatalog.h:486
std::vector< LeafHostInfo > string_dict_hosts_
Definition: SysCatalog.h:490
std::shared_ptr< Calcite > calciteMgr_
Definition: SysCatalog.h:489

+ Here is the call graph for this function:

const std::string& Catalog_Namespace::SysCatalog::getCatalogBasePath ( ) const
inline

Definition at line 230 of file SysCatalog.h.

References basePath_.

230 { return basePath_; }
std::vector< Catalog * > Catalog_Namespace::SysCatalog::getCatalogsForAllDbs ( )

Definition at line 1062 of file SysCatalog.cpp.

References getAllDBMetadata(), and getCatalog().

1062  {
1063  std::vector<Catalog*> catalogs{};
1064  const auto& db_metadata_list = getAllDBMetadata();
1065  for (const auto& db_metadata : db_metadata_list) {
1066  catalogs.emplace_back(getCatalog(db_metadata, false).get());
1067  }
1068  return catalogs;
1069 }
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
std::list< DBMetadata > getAllDBMetadata()

+ Here is the call graph for this function:

std::set< std::string > Catalog_Namespace::SysCatalog::getCreatedRoles ( ) const

Definition at line 2541 of file SysCatalog.cpp.

References granteeMap_, and isDashboardSystemRole().

2541  {
2542  sys_read_lock read_lock(this);
2543  std::set<std::string> roles; // Sorted for human readers.
2544  for (const auto& [key, grantee] : granteeMap_) {
2545  if (!grantee->isUser() && !isDashboardSystemRole(grantee->getName())) {
2546  roles.emplace(grantee->getName());
2547  }
2548  }
2549  return roles;
2550 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
bool isDashboardSystemRole(const std::string &roleName) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

DBSummaryList Catalog_Namespace::SysCatalog::getDatabaseListForUser ( const UserMetadata user)

Definition at line 1742 of file SysCatalog.cpp.

References AccessPrivileges::ACCESS, checkPrivileges(), DatabaseDBObjectType, Catalog_Namespace::DBSummary::dbName, getAllDBMetadata(), getAllUserMetadata(), DBObject::loadKey(), and DBObject::setPrivileges().

Referenced by ShowDatabasesCommand::execute().

1742  {
1743  DBSummaryList ret;
1744 
1745  std::list<Catalog_Namespace::DBMetadata> db_list = getAllDBMetadata();
1746  std::list<Catalog_Namespace::UserMetadata> user_list = getAllUserMetadata();
1747 
1748  for (auto d : db_list) {
1749  DBObject dbObject(d.dbName, DatabaseDBObjectType);
1750  dbObject.loadKey();
1751  dbObject.setPrivileges(AccessPrivileges::ACCESS);
1752  if (!checkPrivileges(user, std::vector<DBObject>{dbObject})) {
1753  continue;
1754  }
1755  for (auto u : user_list) {
1756  if (d.dbOwner == u.userId) {
1757  ret.emplace_back(DBSummary{d.dbName, u.userName});
1758  break;
1759  }
1760  }
1761  }
1762 
1763  return ret;
1764 }
bool checkPrivileges(const UserMetadata &user, const std::vector< DBObject > &privObjects) const
std::list< UserMetadata > getAllUserMetadata()
std::list< DBMetadata > getAllDBMetadata()
static const AccessPrivileges ACCESS
Definition: DBObject.h:153
std::list< DBSummary > DBSummaryList
Definition: SysCatalog.h:145

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Data_Namespace::DataMgr& Catalog_Namespace::SysCatalog::getDataMgr ( ) const
inline

Definition at line 228 of file SysCatalog.h.

References dataMgr_.

Referenced by Executor::clearMemory(), Executor::getExecutor(), foreign_storage::InternalMemoryStatsDataWrapper::initializeObjectsForTable(), and foreign_storage::InternalStorageStatsDataWrapper::initializeObjectsForTable().

228 { return *dataMgr_; }
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: SysCatalog.h:486

+ Here is the caller graph for this function:

std::optional<DBMetadata> Catalog_Namespace::SysCatalog::getDB ( std::string const &  dbname)
inline

Definition at line 209 of file SysCatalog.h.

References getMetadataForDB().

209  {
210  if (DBMetadata db; getMetadataForDB(dbname, db)) {
211  return db;
212  }
213  return {};
214  }
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

std::optional<DBMetadata> Catalog_Namespace::SysCatalog::getDB ( int32_t const  dbid)
inline

Definition at line 215 of file SysCatalog.h.

References getMetadataForDBById().

215  {
216  if (DBMetadata db; getMetadataForDBById(dbid, db)) {
217  return db;
218  }
219  return {};
220  }
bool getMetadataForDBById(const int32_t idIn, DBMetadata &db)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::getDBObjectPrivileges ( const std::string &  granteeName,
DBObject object,
const Catalog_Namespace::Catalog catalog 
) const

Definition at line 2104 of file SysCatalog.cpp.

References getGrantee(), getMetadataForUser(), instance(), and Catalog_Namespace::UserMetadata::isSuper.

2106  {
2107  sys_read_lock read_lock(this);
2108  UserMetadata user_meta;
2109 
2110  if (instance().getMetadataForUser(granteeName, user_meta)) {
2111  if (user_meta.isSuper) {
2112  throw runtime_error(
2113  "Request to show privileges from " + granteeName +
2114  " failed because user is super user and has all privileges by default.");
2115  }
2116  }
2117  auto* grantee = instance().getGrantee(granteeName);
2118  if (!grantee) {
2119  throw runtime_error("Request to show privileges for " + granteeName +
2120  " failed because role or user with this name does not exist.");
2121  }
2122  object.loadKey(catalog);
2123  grantee->getPrivileges(object, true);
2124 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
bool getMetadataForUser(const std::string &name, UserMetadata &user)
Grantee * getGrantee(const std::string &name) const
static SysCatalog & instance()
Definition: SysCatalog.h:337
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

Grantee * Catalog_Namespace::SysCatalog::getGrantee ( const std::string &  name) const

Definition at line 2411 of file SysCatalog.cpp.

References granteeMap_, and to_upper().

Referenced by buildRoleMapUnlocked(), buildUserRoleMapUnlocked(), createRole_unsafe(), createUser(), getDBObjectPrivileges(), getRoleGrantee(), getRoles(), getUserGrantee(), grantDBObjectPrivileges_unsafe(), grantRole_unsafe(), renameDBObject(), renameUser(), revokeDBObjectPrivileges_unsafe(), and revokeRole_unsafe().

2411  {
2412  sys_read_lock read_lock(this);
2413  auto grantee = granteeMap_.find(to_upper(name));
2414  if (grantee == granteeMap_.end()) { // check to make sure role exists
2415  return nullptr;
2416  }
2417  return grantee->second.get(); // returns pointer to role
2418 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
std::string name() const
Definition: SysCatalog.h:350
std::string to_upper(const std::string &str)
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::unordered_map< std::string, std::vector< std::string > > Catalog_Namespace::SysCatalog::getGranteesOfSharedDashboards ( const std::vector< std::string > &  dashboard_ids)

Definition at line 2849 of file SysCatalog.cpp.

References DashboardDBObjectType, sqliteConnector_, and to_string().

Referenced by Catalog_Namespace::Catalog::createDashboardSystemRoles().

2849  {
2850  sys_sqlite_lock sqlite_lock(this);
2851  std::unordered_map<std::string, std::vector<std::string>> active_grantees;
2852  sqliteConnector_->query("BEGIN TRANSACTION");
2853  try {
2854  for (auto dash : dashboard_ids) {
2855  std::vector<std::string> grantees = {};
2856  sqliteConnector_->query_with_text_params(
2857  "SELECT roleName FROM mapd_object_permissions WHERE objectPermissions NOT IN "
2858  "(0,1) AND objectPermissionsType = ? AND objectId = ?",
2859  std::vector<std::string>{
2860  std::to_string(static_cast<int32_t>(DashboardDBObjectType)), dash});
2861  int num_rows = sqliteConnector_->getNumRows();
2862  if (num_rows == 0) {
2863  // no grantees
2864  continue;
2865  } else {
2866  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
2867  grantees.push_back(sqliteConnector_->getData<string>(i, 0));
2868  }
2869  active_grantees[dash] = grantees;
2870  }
2871  }
2872  } catch (const std::exception& e) {
2873  sqliteConnector_->query("ROLLBACK TRANSACTION");
2874  throw;
2875  }
2876  sqliteConnector_->query("END TRANSACTION");
2877  return active_grantees;
2878 }
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< ObjectRoleDescriptor > Catalog_Namespace::SysCatalog::getMetadataForAllObjects ( ) const

Definition at line 2442 of file SysCatalog.cpp.

References isDashboardSystemRole(), and objectDescriptorMap_.

2442  {
2443  sys_read_lock read_lock(this);
2444  std::vector<ObjectRoleDescriptor> objects;
2445  for (const auto& entry : objectDescriptorMap_) {
2446  auto object_role = entry.second.get();
2447  if (object_role->dbId != 0 && !isDashboardSystemRole(object_role->roleName)) {
2448  objects.emplace_back(*object_role);
2449  }
2450  }
2451  return objects;
2452 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
bool isDashboardSystemRole(const std::string &roleName) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

bool Catalog_Namespace::SysCatalog::getMetadataForDB ( const std::string &  name,
DBMetadata db 
)

Definition at line 1712 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, and sqliteConnector_.

Referenced by alterUser(), createDatabase(), createUser(), getCatalog(), getDB(), getMetadataWithDefaultDB(), initializeInformationSchemaDb(), migrateDBAccessPrivileges(), renameDatabase(), and Catalog_Namespace::UserAlterations::wouldChange().

1712  {
1713  sys_read_lock read_lock(this);
1714  sys_sqlite_lock sqlite_lock(this);
1715  sqliteConnector_->query_with_text_param(
1716  "SELECT dbid, name, owner FROM mapd_databases WHERE name = ?", name);
1717  int numRows = sqliteConnector_->getNumRows();
1718  if (numRows == 0) {
1719  return false;
1720  }
1721  db.dbId = sqliteConnector_->getData<int>(0, 0);
1722  db.dbName = sqliteConnector_->getData<string>(0, 1);
1723  db.dbOwner = sqliteConnector_->getData<int>(0, 2);
1724  return true;
1725 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
std::string name() const
Definition: SysCatalog.h:350
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::getMetadataForDBById ( const int32_t  idIn,
DBMetadata db 
)

Definition at line 1727 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, sqliteConnector_, and to_string().

Referenced by getDB(), and getMetadataWithDefaultDB().

1727  {
1728  sys_sqlite_lock sqlite_lock(this);
1729  sqliteConnector_->query_with_text_param(
1730  "SELECT dbid, name, owner FROM mapd_databases WHERE dbid = ?",
1731  std::to_string(idIn));
1732  int numRows = sqliteConnector_->getNumRows();
1733  if (numRows == 0) {
1734  return false;
1735  }
1736  db.dbId = sqliteConnector_->getData<int>(0, 0);
1737  db.dbName = sqliteConnector_->getData<string>(0, 1);
1738  db.dbOwner = sqliteConnector_->getData<int>(0, 2);
1739  return true;
1740 }
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< ObjectRoleDescriptor * > Catalog_Namespace::SysCatalog::getMetadataForObject ( int32_t  dbId,
int32_t  dbType,
int32_t  objectId 
) const

Definition at line 2429 of file SysCatalog.cpp.

References objectDescriptorMap_, and to_string().

Referenced by renameDBObject().

2429  {
2430  sys_read_lock read_lock(this);
2431  std::vector<ObjectRoleDescriptor*> objectsList;
2432 
2433  auto range = objectDescriptorMap_.equal_range(std::to_string(dbId) + ":" +
2434  std::to_string(dbType) + ":" +
2435  std::to_string(objectId));
2436  for (auto d = range.first; d != range.second; ++d) {
2437  objectsList.push_back(d->second.get());
2438  }
2439  return objectsList; // return pointers to objects
2440 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
std::string to_string(char const *&&v)
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::getMetadataForUser ( const std::string &  name,
UserMetadata user 
)

Definition at line 1572 of file SysCatalog.cpp.

References Catalog_Namespace::parseUserMetadataFromSQLite(), sqliteConnector_, and temporary_users_by_name_.

Referenced by alterUser(), checkPasswordForUserImpl(), checkPrivileges(), createUser(), dropUser(), getDBObjectPrivileges(), getMetadataWithDefaultDB(), getRoles(), getUser(), grantDBObjectPrivileges_unsafe(), grantRoleBatch_unsafe(), login(), renameUser(), revokeDBObjectPrivileges_unsafe(), and revokeRoleBatch_unsafe().

1572  {
1573  sys_read_lock read_lock(this);
1574  sys_sqlite_lock sqlite_lock(this);
1575  sqliteConnector_->query_with_text_param(
1576  "SELECT userid, name, passwd_hash, issuper, default_db, can_login FROM mapd_users "
1577  "WHERE name = ?",
1578  name);
1579  int numRows = sqliteConnector_->getNumRows();
1580  if (numRows == 0) {
1581  auto userit = temporary_users_by_name_.find(name);
1582  if (userit != temporary_users_by_name_.end()) {
1583  user = *userit->second;
1584  return true;
1585  } else {
1586  return false;
1587  }
1588  }
1590 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
static bool parseUserMetadataFromSQLite(const std::unique_ptr< SqliteConnector > &conn, UserMetadata &user, int row)
std::string name() const
Definition: SysCatalog.h:350
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:512
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::getMetadataForUserById ( const int32_t  idIn,
UserMetadata user 
)

Definition at line 1592 of file SysCatalog.cpp.

References Catalog_Namespace::parseUserMetadataFromSQLite(), sqliteConnector_, temporary_users_by_id_, and to_string().

Referenced by createDatabase(), getUser(), populateRoleDbObjects(), and reassignObjectOwners().

1592  {
1593  sys_sqlite_lock sqlite_lock(this);
1594  sqliteConnector_->query_with_text_param(
1595  "SELECT userid, name, passwd_hash, issuper, default_db, can_login FROM mapd_users "
1596  "WHERE userid = ?",
1597  std::to_string(idIn));
1598  int numRows = sqliteConnector_->getNumRows();
1599  if (numRows == 0) {
1600  auto userit = temporary_users_by_id_.find(idIn);
1601  if (userit != temporary_users_by_id_.end()) {
1602  user = *userit->second;
1603  return true;
1604  } else {
1605  return false;
1606  }
1607  }
1609 }
static bool parseUserMetadataFromSQLite(const std::unique_ptr< SqliteConnector > &conn, UserMetadata &user, int row)
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::unordered_map< int32_t, std::shared_ptr< UserMetadata > > temporary_users_by_id_
Definition: SysCatalog.h:513

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::getMetadataWithDefaultDB ( std::string &  dbname,
const std::string &  username,
Catalog_Namespace::DBMetadata db_meta,
UserMetadata user_meta 
)
private

Definition at line 1676 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::UserMetadata::defaultDbId, Catalog_Namespace::g_log_user_id, getMetadataForDB(), getMetadataForDBById(), getMetadataForUser(), shared::kDefaultDbName, to_string(), Catalog_Namespace::UserMetadata::userId, and Catalog_Namespace::UserMetadata::userName.

Referenced by login(), and switchDatabase().

1679  {
1680  sys_read_lock read_lock(this);
1681  if (!getMetadataForUser(username, user_meta)) {
1682  throw std::runtime_error("Invalid credentials.");
1683  }
1684 
1685  if (!dbname.empty()) {
1686  if (!getMetadataForDB(dbname, db_meta)) {
1687  throw std::runtime_error("Database name " + dbname + " does not exist.");
1688  }
1689  // loaded the requested database
1690  } else {
1691  if (user_meta.defaultDbId != -1) {
1692  if (!getMetadataForDBById(user_meta.defaultDbId, db_meta)) {
1693  std::string loggable = g_log_user_id ? std::string("") : ' ' + user_meta.userName;
1694  throw std::runtime_error(
1695  "Server error: User #" + std::to_string(user_meta.userId) + loggable +
1696  " has invalid default_db #" + std::to_string(user_meta.defaultDbId) +
1697  " which does not exist.");
1698  }
1699  dbname = db_meta.dbName;
1700  // loaded the user's default database
1701  } else {
1702  if (!getMetadataForDB(shared::kDefaultDbName, db_meta)) {
1703  throw std::runtime_error(std::string("Database ") + shared::kDefaultDbName +
1704  " does not exist.");
1705  }
1706  dbname = shared::kDefaultDbName;
1707  // loaded the mapd database by default
1708  }
1709  }
1710 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string to_string(char const *&&v)
const std::string kDefaultDbName
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122
bool getMetadataForDBById(const int32_t idIn, DBMetadata &db)
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Role * Catalog_Namespace::SysCatalog::getRoleGrantee ( const std::string &  name) const

Definition at line 2420 of file SysCatalog.cpp.

References getGrantee().

Referenced by Catalog_Namespace::Catalog::createDashboardSystemRoles(), grantRole_unsafe(), isRoleGrantedToGrantee(), revokeRole_unsafe(), and syncUserWithRemoteProvider().

2420  {
2421  return dynamic_cast<Role*>(getGrantee(name));
2422 }
std::string name() const
Definition: SysCatalog.h:350
Grantee * getGrantee(const std::string &name) const
Definition: Grantee.h:81

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< std::string > Catalog_Namespace::SysCatalog::getRoles ( const std::string &  user_name,
bool  effective = true 
)

Definition at line 2480 of file SysCatalog.cpp.

References getGrantee().

2481  {
2482  sys_read_lock read_lock(this);
2483  auto* grantee = getGrantee(user_name);
2484  if (!grantee) {
2485  throw std::runtime_error("user or role not found");
2486  }
2487  return grantee->getRoles(/*only_direct=*/!effective);
2488 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
Grantee * getGrantee(const std::string &name) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

std::vector< std::string > Catalog_Namespace::SysCatalog::getRoles ( bool  include_user_private_role,
bool  is_super,
const std::string &  user_name,
bool  ignore_deleted_user = false 
)

Definition at line 2511 of file SysCatalog.cpp.

References getMetadataForUser(), granteeMap_, isDashboardSystemRole(), and isRoleGrantedToGrantee().

2514  {
2515  sys_read_lock read_lock(this);
2516  if (ignore_deleted_user) {
2517  // In certain cases, it is possible to concurrently call this method while the user is
2518  // being dropped. In such a case, return an empty result.
2519  UserMetadata user;
2520  if (!getMetadataForUser(user_name, user)) {
2521  return {};
2522  }
2523  }
2524  std::vector<std::string> roles;
2525  for (auto& grantee : granteeMap_) {
2526  if (!include_user_private_role && grantee.second->isUser()) {
2527  continue;
2528  }
2529  if (!is_super &&
2530  !isRoleGrantedToGrantee(user_name, grantee.second->getName(), false)) {
2531  continue;
2532  }
2533  if (isDashboardSystemRole(grantee.second->getName())) {
2534  continue;
2535  }
2536  roles.push_back(grantee.second->getName());
2537  }
2538  return roles;
2539 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
bool getMetadataForUser(const std::string &name, UserMetadata &user)
bool isRoleGrantedToGrantee(const std::string &granteeName, const std::string &roleName, bool only_direct) const
bool isDashboardSystemRole(const std::string &roleName) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

std::vector< std::string > Catalog_Namespace::SysCatalog::getRoles ( const std::string &  userName,
const int32_t  dbId 
)

Definition at line 2490 of file SysCatalog.cpp.

References isDashboardSystemRole(), isRoleGrantedToGrantee(), sqliteConnector_, and to_string().

2491  {
2492  sys_sqlite_lock sqlite_lock(this);
2493  std::string sql =
2494  "SELECT DISTINCT roleName FROM mapd_object_permissions WHERE "
2495  "objectPermissions<>0 "
2496  "AND roleType=0 AND dbId=" +
2497  std::to_string(dbId);
2498  sqliteConnector_->query(sql);
2499  int numRows = sqliteConnector_->getNumRows();
2500  std::vector<std::string> roles(0);
2501  for (int r = 0; r < numRows; ++r) {
2502  auto roleName = sqliteConnector_->getData<string>(r, 0);
2503  if (isRoleGrantedToGrantee(userName, roleName, false) &&
2504  !isDashboardSystemRole(roleName)) {
2505  roles.push_back(roleName);
2506  }
2507  }
2508  return roles;
2509 }
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
bool isRoleGrantedToGrantee(const std::string &granteeName, const std::string &roleName, bool only_direct) const
bool isDashboardSystemRole(const std::string &roleName) const

+ Here is the call graph for this function:

SqliteConnector* Catalog_Namespace::SysCatalog::getSqliteConnector ( )
inline

Definition at line 231 of file SysCatalog.h.

References sqliteConnector_.

231 { return sqliteConnector_.get(); }
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::optional<UserMetadata> Catalog_Namespace::SysCatalog::getUser ( std::string const &  uname)
inline

Definition at line 197 of file SysCatalog.h.

References getMetadataForUser().

Referenced by alterUser(), createUser(), and syncUserWithRemoteProvider().

197  {
198  if (UserMetadata user; getMetadataForUser(uname, user)) {
199  return user;
200  }
201  return {};
202  }
bool getMetadataForUser(const std::string &name, UserMetadata &user)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::optional<UserMetadata> Catalog_Namespace::SysCatalog::getUser ( int32_t const  uid)
inline

Definition at line 203 of file SysCatalog.h.

References getMetadataForUserById().

203  {
204  if (UserMetadata user; getMetadataForUserById(uid, user)) {
205  return user;
206  }
207  return {};
208  }
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)

+ Here is the call graph for this function:

User * Catalog_Namespace::SysCatalog::getUserGrantee ( const std::string &  name) const

Definition at line 2424 of file SysCatalog.cpp.

References getGrantee().

Referenced by checkPrivileges(), createDBObject(), Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::get_users(), hasAnyPrivileges(), isRoleGrantedToGrantee(), populateRoleDbObjects(), syncUserWithRemoteProvider(), and verifyDBObjectOwnership().

2424  {
2425  return dynamic_cast<User*>(getGrantee(name));
2426 }
std::string name() const
Definition: SysCatalog.h:350
Definition: Grantee.h:75
Grantee * getGrantee(const std::string &name) const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantAllOnDatabase_unsafe ( const std::string &  roleName,
DBObject object,
const Catalog_Namespace::Catalog catalog 
)
private

Definition at line 1887 of file SysCatalog.cpp.

References AccessPrivileges::ACCESS, AccessPrivileges::ALL_DASHBOARD, AccessPrivileges::ALL_SERVER, AccessPrivileges::ALL_TABLE, AccessPrivileges::ALL_VIEW, DashboardDBObjectType, DatabaseDBObjectType, g_enable_fsi, grantDBObjectPrivileges_unsafe(), ServerDBObjectType, DBObject::setPermissionType(), DBObject::setPrivileges(), TableDBObjectType, AccessPrivileges::VIEW_SQL_EDITOR, and ViewDBObjectType.

Referenced by createDatabase(), and grantDBObjectPrivileges_unsafe().

1889  {
1890  // It's a separate use case because it's easier for implementation to convert ALL ON
1891  // DATABASE into ALL ON DASHBOARDS, ALL ON VIEWS and ALL ON TABLES
1892  // Add DB Access privileges
1893  DBObject tmp_object = object;
1896  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1899  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1902  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1904  tmp_object.setPermissionType(ViewDBObjectType);
1905  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1906 
1907  if (g_enable_fsi) {
1910  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1911  }
1912 
1915  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1916  return;
1917 }
static const AccessPrivileges VIEW_SQL_EDITOR
Definition: DBObject.h:152
void setPrivileges(const AccessPrivileges &privs)
Definition: DBObject.h:227
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
static const AccessPrivileges ALL_VIEW
Definition: DBObject.h:177
void setPermissionType(const DBObjectType &permissionType)
Definition: DBObject.cpp:160
static const AccessPrivileges ALL_SERVER
Definition: DBObject.h:187
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:169
static const AccessPrivileges ACCESS
Definition: DBObject.h:153
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:157
bool g_enable_fsi
Definition: Catalog.cpp:96

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantDBObjectPrivileges ( const std::string &  grantee,
const DBObject object,
const Catalog_Namespace::Catalog catalog 
)

Definition at line 2739 of file SysCatalog.cpp.

References execInTransaction(), and grantDBObjectPrivileges_unsafe().

2741  {
2743  &SysCatalog::grantDBObjectPrivileges_unsafe, grantee, object, catalog);
2744 }
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::grantDBObjectPrivileges_unsafe ( const std::string &  granteeName,
const DBObject  object,
const Catalog_Namespace::Catalog catalog 
)
private

Definition at line 1845 of file SysCatalog.cpp.

References DatabasePrivileges::ALL, CHECK, DatabaseDBObjectType, getGrantee(), getMetadataForUser(), grantAllOnDatabase_unsafe(), Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), instance(), Catalog_Namespace::UserMetadata::is_temporary, Catalog_Namespace::UserMetadata::isSuper, sqliteConnector_, and updateObjectDescriptorMap().

Referenced by changeDBObjectOwnership(), createDBObject(), grantAllOnDatabase_unsafe(), grantDBObjectPrivileges(), and grantDBObjectPrivilegesBatch_unsafe().

1848  {
1849  object.loadKey(catalog);
1850  CHECK(object.valid());
1851  if (object.getPrivileges().hasPermission(DatabasePrivileges::ALL) &&
1852  object.getObjectKey().permissionType == DatabaseDBObjectType) {
1853  return grantAllOnDatabase_unsafe(granteeName, object, catalog);
1854  }
1855 
1856  sys_write_lock write_lock(this);
1857 
1858  UserMetadata user_meta;
1859  bool is_temporary_user{false};
1860  if (instance().getMetadataForUser(granteeName, user_meta)) {
1861  if (user_meta.isSuper) {
1862  // super doesn't have explicit privileges so nothing to do
1863  return;
1864  }
1865  is_temporary_user = user_meta.is_temporary;
1866  }
1867  auto* grantee = instance().getGrantee(granteeName);
1868  if (!grantee) {
1869  throw runtime_error("Request to grant privileges to " + granteeName +
1870  " failed because role or user with this name does not exist.");
1871  }
1872  grantee->grantPrivileges(object);
1873 
1874  /* apply grant privileges statement to sqlite DB */
1875  std::vector<std::string> objectKey = object.toString();
1876  object.resetPrivileges();
1877  grantee->getPrivileges(object, true);
1878 
1879  if (!is_temporary_user) {
1880  sys_sqlite_lock sqlite_lock(this);
1882  sqliteConnector_, granteeName, grantee->isUser(), object);
1883  }
1884  updateObjectDescriptorMap(granteeName, object, grantee->isUser(), catalog);
1885 }
static const int32_t ALL
Definition: DBObject.h:77
bool getMetadataForUser(const std::string &name, UserMetadata &user)
Grantee * getGrantee(const std::string &name) const
heavyai::unique_lock< heavyai::shared_mutex > write_lock
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:476
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
static SysCatalog & instance()
Definition: SysCatalog.h:337
void grantAllOnDatabase_unsafe(const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &catalog)
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
void updateObjectDescriptorMap(const std::string &roleName, DBObject &object, bool roleType, const Catalog_Namespace::Catalog &cat)
#define CHECK(condition)
Definition: Logger.h:222

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantDBObjectPrivilegesBatch ( const std::vector< std::string > &  grantees,
const std::vector< DBObject > &  objects,
const Catalog_Namespace::Catalog catalog 
)

Definition at line 2746 of file SysCatalog.cpp.

References execInTransaction(), and grantDBObjectPrivilegesBatch_unsafe().

2748  {
2750  &SysCatalog::grantDBObjectPrivilegesBatch_unsafe, grantees, objects, catalog);
2751 }
void grantDBObjectPrivilegesBatch_unsafe(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::grantDBObjectPrivilegesBatch_unsafe ( const std::vector< std::string > &  grantees,
const std::vector< DBObject > &  objects,
const Catalog_Namespace::Catalog catalog 
)
private

Definition at line 1833 of file SysCatalog.cpp.

References grantDBObjectPrivileges_unsafe().

Referenced by grantDBObjectPrivilegesBatch(), and reassignObjectOwners().

1836  {
1837  for (const auto& grantee : grantees) {
1838  for (const auto& object : objects) {
1839  grantDBObjectPrivileges_unsafe(grantee, object, catalog);
1840  }
1841  }
1842 }
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantDefaultPrivilegesToRole_unsafe ( const std::string &  name,
bool  issuper 
)
private
void Catalog_Namespace::SysCatalog::grantRole ( const std::string &  role,
const std::string &  grantee,
const bool  is_temporary = false 
)

Definition at line 2722 of file SysCatalog.cpp.

References execInTransaction(), and grantRole_unsafe().

Referenced by syncUserWithRemoteProvider().

2724  {
2725  execInTransaction(&SysCatalog::grantRole_unsafe, role, grantee, is_temporary);
2726 }
void grantRole_unsafe(const std::string &roleName, const std::string &granteeName, const bool is_temporary)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantRole_unsafe ( const std::string &  roleName,
const std::string &  granteeName,
const bool  is_temporary 
)
private

Definition at line 2199 of file SysCatalog.cpp.

References getGrantee(), getRoleGrantee(), and sqliteConnector_.

Referenced by grantRole(), and grantRoleBatch_unsafe().

2201  {
2202  auto* rl = getRoleGrantee(roleName);
2203  if (!rl) {
2204  throw runtime_error("Request to grant role " + roleName +
2205  " failed because role with this name does not exist.");
2206  }
2207  auto* grantee = getGrantee(granteeName);
2208  if (!grantee) {
2209  throw runtime_error("Request to grant role " + roleName + " failed because grantee " +
2210  granteeName + " does not exist.");
2211  }
2212  sys_write_lock write_lock(this);
2213  if (!grantee->hasRole(rl, true)) {
2214  grantee->grantRole(rl);
2215  if (!is_temporary) {
2216  sys_sqlite_lock sqlite_lock(this);
2217  sqliteConnector_->query_with_text_params(
2218  "INSERT INTO mapd_roles(roleName, userName) VALUES (?, ?)",
2219  std::vector<std::string>{rl->getName(), grantee->getName()});
2220  }
2221  }
2222 }
Grantee * getGrantee(const std::string &name) const
heavyai::unique_lock< heavyai::shared_mutex > write_lock
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
Role * getRoleGrantee(const std::string &name) const
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantRoleBatch ( const std::vector< std::string > &  roles,
const std::vector< std::string > &  grantees 
)

Definition at line 2717 of file SysCatalog.cpp.

References execInTransaction(), and grantRoleBatch_unsafe().

Referenced by Catalog_Namespace::Catalog::createDashboardSystemRoles().

2718  {
2720 }
void grantRoleBatch_unsafe(const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantRoleBatch_unsafe ( const std::vector< std::string > &  roles,
const std::vector< std::string > &  grantees 
)
private

Definition at line 2184 of file SysCatalog.cpp.

References getMetadataForUser(), grantRole_unsafe(), and Catalog_Namespace::UserMetadata::is_temporary.

Referenced by grantRoleBatch().

2185  {
2186  for (const auto& role : roles) {
2187  for (const auto& grantee : grantees) {
2188  bool is_temporary_user{false};
2189  UserMetadata user;
2190  if (getMetadataForUser(grantee, user)) {
2191  is_temporary_user = user.is_temporary;
2192  }
2193  grantRole_unsafe(role, grantee, is_temporary_user);
2194  }
2195  }
2196 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
void grantRole_unsafe(const std::string &roleName, const std::string &granteeName, const bool is_temporary)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::hasAnyPrivileges ( const UserMetadata user,
std::vector< DBObject > &  privObjects 
)

Definition at line 2359 of file SysCatalog.cpp.

References getUserGrantee(), instance(), Catalog_Namespace::UserMetadata::isSuper, Catalog_Namespace::UserMetadata::userLoggable(), and Catalog_Namespace::UserMetadata::userName.

2360  {
2361  sys_read_lock read_lock(this);
2362  if (user.isSuper) {
2363  return true;
2364  }
2365  auto* user_rl = instance().getUserGrantee(user.userName);
2366  if (!user_rl) {
2367  throw runtime_error("Cannot check privileges. User " + user.userLoggable() +
2368  " does not exist.");
2369  }
2370  for (std::vector<DBObject>::iterator objectIt = privObjects.begin();
2371  objectIt != privObjects.end();
2372  ++objectIt) {
2373  if (!user_rl->hasAnyPrivileges(*objectIt, false)) {
2374  return false;
2375  }
2376  }
2377  return true;
2378 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
static SysCatalog & instance()
Definition: SysCatalog.h:337
User * getUserGrantee(const std::string &name) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

bool Catalog_Namespace::SysCatalog::hasExecutedMigration ( const std::string &  migration_name) const

Definition at line 3010 of file SysCatalog.cpp.

References hasVersionHistoryTable(), and sqliteConnector_.

Referenced by initializeInformationSchemaDb().

3010  {
3011  if (hasVersionHistoryTable()) {
3012  sys_sqlite_lock sqlite_lock(this);
3013  sqliteConnector_->query_with_text_params(
3014  "SELECT migration_history FROM mapd_version_history WHERE migration_history = ?",
3015  std::vector<std::string>{migration_name});
3016  return (sqliteConnector_->getNumRows() > 0);
3017  }
3018  return false;
3019 }
bool hasVersionHistoryTable() const
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::hasVersionHistoryTable ( ) const
private

Definition at line 3031 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by hasExecutedMigration(), and recordExecutedMigration().

3031  {
3032  sys_sqlite_lock sqlite_lock(this);
3033  sqliteConnector_->query(
3034  "select name from sqlite_master WHERE type='table' AND "
3035  "name='mapd_version_history'");
3036  return (sqliteConnector_->getNumRows() > 0);
3037 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::importDataFromOldMapdDB ( )
private

Definition at line 358 of file SysCatalog.cpp.

References basePath_, logger::ERROR, logger::INFO, shared::kCatalogDirectoryName, shared::kSystemCatalogName, LOG, and sqliteConnector_.

358  {
359  sys_sqlite_lock sqlite_lock(this);
360  std::string mapd_db_path = basePath_ + "/" + shared::kCatalogDirectoryName + "/mapd";
361  sqliteConnector_->query("ATTACH DATABASE `" + mapd_db_path + "` as old_cat");
362  sqliteConnector_->query("BEGIN TRANSACTION");
363  LOG(INFO) << "Moving global metadata into a separate catalog";
364  try {
365  auto moveTableIfExists = [conn = sqliteConnector_.get()](const std::string& tableName,
366  bool deleteOld = true) {
367  conn->query("SELECT sql FROM old_cat.sqlite_master WHERE type='table' AND name='" +
368  tableName + "'");
369  if (conn->getNumRows() != 0) {
370  conn->query(conn->getData<string>(0, 0));
371  conn->query("INSERT INTO " + tableName + " SELECT * FROM old_cat." + tableName);
372  if (deleteOld) {
373  conn->query("DROP TABLE old_cat." + tableName);
374  }
375  }
376  };
377  moveTableIfExists("mapd_users");
378  moveTableIfExists("mapd_databases");
379  moveTableIfExists("mapd_roles");
380  moveTableIfExists("mapd_object_permissions");
381  moveTableIfExists("mapd_privileges");
382  moveTableIfExists("mapd_version_history", false);
383  } catch (const std::exception& e) {
384  LOG(ERROR) << "Failed to move global metadata into a separate catalog: " << e.what();
385  sqliteConnector_->query("ROLLBACK TRANSACTION");
386  try {
387  sqliteConnector_->query("DETACH DATABASE old_cat");
388  } catch (const std::exception&) {
389  // nothing to do here
390  }
391  throw;
392  }
393  sqliteConnector_->query("END TRANSACTION");
394  const std::string sys_catalog_path =
395  basePath_ + "/" + shared::kCatalogDirectoryName + "/" + shared::kSystemCatalogName;
396  LOG(INFO) << "Global metadata has been successfully moved into a separate catalog: "
397  << sys_catalog_path
398  << ". Using this database with an older version of heavydb "
399  "is now impossible.";
400  try {
401  sqliteConnector_->query("DETACH DATABASE old_cat");
402  } catch (const std::exception&) {
403  // nothing to do here
404  }
405 }
#define LOG(tag)
Definition: Logger.h:216
const std::string kSystemCatalogName
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
const std::string kCatalogDirectoryName
void Catalog_Namespace::SysCatalog::init ( const std::string &  basePath,
std::shared_ptr< Data_Namespace::DataMgr dataMgr,
const AuthMetadata authMetadata,
std::shared_ptr< Calcite calcite,
bool  is_new_db,
bool  aggregator,
const std::vector< LeafHostInfo > &  string_dict_hosts 
)

Definition at line 160 of file SysCatalog.cpp.

References anonymous_namespace{SysCatalog.cpp}::copy_catalog_if_read_only(), Catalog_Namespace::dsqliteMutex_(), g_multi_instance, shared::kCatalogDirectoryName, shared::kLockfilesDirectoryName, shared::kSystemCatalogName, migrations::MigrationMgr::migrationEnabled(), migrations::MigrationMgr::relaxMigrationLock(), and migrations::MigrationMgr::takeMigrationLock().

166  {
167  basePath_ = !g_multi_instance ? copy_catalog_if_read_only(basePath).string() : basePath;
170  dcatalogMutex_ = std::make_unique<heavyai::DistributedSharedMutex>(
171  std::filesystem::path(basePath_) / shared::kLockfilesDirectoryName /
173  [this](size_t) {
175  *dsqliteMutex_);
177  });
178  dsqliteMutex_ = std::make_unique<heavyai::DistributedSharedMutex>(
179  std::filesystem::path(basePath_) / shared::kLockfilesDirectoryName /
182  sys_sqlite_lock sqlite_lock(this);
183  dataMgr_ = dataMgr;
184  authMetadata_ = &authMetadata;
185  pki_server_.reset(new PkiServer(*authMetadata_));
186  calciteMgr_ = calcite;
187  string_dict_hosts_ = string_dict_hosts;
188  aggregator_ = aggregator;
190  if (is_new_db) {
191  initDB();
192  } else {
193  bool db_exists =
194  boost::filesystem::exists(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
196  if (!db_exists) {
198  }
202  }
203  }
204  buildMaps(is_new_db);
205 }
void buildMaps(bool is_new_db=false)
Definition: SysCatalog.cpp:207
bool g_multi_instance
Definition: heavyai_locks.h:21
static void relaxMigrationLock()
const std::string kSystemCatalogName
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::unique_ptr< PkiServer > pki_server_
Definition: SysCatalog.h:487
const AuthMetadata * authMetadata_
Definition: SysCatalog.h:488
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
static bool migrationEnabled()
Definition: MigrationMgr.h:43
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: SysCatalog.h:486
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_lock< T > unique_lock
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::unique_ptr< heavyai::DistributedSharedMutex > dsqliteMutex_
Definition: SysCatalog.h:504
static void takeMigrationLock(const std::string &base_path)
void buildMapsUnlocked(bool is_new_db=false)
Definition: SysCatalog.cpp:214
const std::string kCatalogDirectoryName
std::vector< LeafHostInfo > string_dict_hosts_
Definition: SysCatalog.h:490
std::unique_ptr< heavyai::DistributedSharedMutex > dcatalogMutex_
Definition: SysCatalog.h:503
std::shared_ptr< Calcite > calciteMgr_
Definition: SysCatalog.h:489
const std::string kLockfilesDirectoryName
std::filesystem::path copy_catalog_if_read_only(std::filesystem::path base_data_path)
Definition: SysCatalog.cpp:79

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::initDB ( )
private

Definition at line 278 of file SysCatalog.cpp.

References createDatabase(), createRole_unsafe(), g_read_only, anonymous_namespace{SysCatalog.cpp}::hash_with_bcrypt(), shared::kDefaultDbName, shared::kDefaultRootPasswd, shared::kRootUserId, shared::kRootUserIdStr, shared::kRootUsername, and sqliteConnector_.

278  {
279  if (g_read_only) {
280  throw std::runtime_error("can't init a new database in read-only mode");
281  }
282  sys_sqlite_lock sqlite_lock(this);
283  sqliteConnector_->query("BEGIN TRANSACTION");
284  try {
285  sqliteConnector_->query(
286  "CREATE TABLE mapd_users (userid integer primary key, name text unique, "
287  "passwd_hash text, issuper boolean, default_db integer references "
288  "mapd_databases, can_login boolean)");
289  sqliteConnector_->query_with_text_params(
290  "INSERT INTO mapd_users VALUES (?, ?, ?, 1, NULL, 1)",
291  std::vector<std::string>{shared::kRootUserIdStr,
294  sqliteConnector_->query(
295  "CREATE TABLE mapd_databases (dbid integer primary key, name text unique, owner "
296  "integer references mapd_users)");
297  sqliteConnector_->query(
298  "CREATE TABLE mapd_roles(roleName text, userName text, UNIQUE(roleName, "
299  "userName))");
300  sqliteConnector_->query(
301  "CREATE TABLE mapd_object_permissions ("
302  "roleName text, "
303  "roleType bool, "
304  "dbId integer references mapd_databases, "
305  "objectName text, "
306  "objectId integer, "
307  "objectPermissionsType integer, "
308  "objectPermissions integer, "
309  "objectOwnerId integer, UNIQUE(roleName, objectPermissionsType, dbId, "
310  "objectId))");
311  } catch (const std::exception&) {
312  sqliteConnector_->query("ROLLBACK TRANSACTION");
313  throw;
314  }
315  sqliteConnector_->query("END TRANSACTION");
318  shared::kRootUsername, /*userPrivateRole=*/true, /*is_temporary=*/false);
319 }
const int kRootUserId
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
const std::string kDefaultDbName
std::string hash_with_bcrypt(const std::string &pwd)
Definition: SysCatalog.cpp:71
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
const std::string kRootUsername
bool g_read_only
Definition: File.cpp:40
const std::string kDefaultRootPasswd
const std::string kRootUserIdStr
void createDatabase(const std::string &dbname, int owner)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::initializeInformationSchemaDb ( )
private

Definition at line 2989 of file SysCatalog.cpp.

References createDatabase(), dropDatabase(), g_enable_system_tables, getMetadataForDB(), hasExecutedMigration(), shared::kInfoSchemaDbName, shared::kInfoSchemaMigrationName, shared::kRootUserId, LOG, recordExecutedMigration(), and logger::WARNING.

2989  {
2991  sys_write_lock write_lock(this);
2992  DBMetadata db_metadata;
2993  if (getMetadataForDB(shared::kInfoSchemaDbName, db_metadata)) {
2994  LOG(WARNING) << "A database with name \"" << shared::kInfoSchemaDbName
2995  << "\" already exists. System table creation will be skipped. Rename "
2996  "this database in order to use system tables.";
2997  } else {
2999  try {
3001  } catch (...) {
3003  dropDatabase(db_metadata);
3004  throw;
3005  }
3006  }
3007  }
3008 }
void recordExecutedMigration(const std::string &migration_name) const
const int kRootUserId
#define LOG(tag)
Definition: Logger.h:216
void dropDatabase(const DBMetadata &db)
heavyai::unique_lock< heavyai::shared_mutex > write_lock
const std::string kInfoSchemaDbName
bool g_enable_system_tables
Definition: SysCatalog.cpp:64
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
bool hasExecutedMigration(const std::string &migration_name) const
void createDatabase(const std::string &dbname, int owner)
const std::string kInfoSchemaMigrationName
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

static SysCatalog& Catalog_Namespace::SysCatalog::instance ( )
inlinestatic

Definition at line 337 of file SysCatalog.h.

References instance_, and SysCatalog().

Referenced by foreign_storage::anonymous_namespace{LogFileBufferParser.cpp}::add_nonce_values(), foreign_storage::cache_blocks(), AlterForeignServerCommand::changeForeignServerOwner(), Catalog_Namespace::SessionInfo::checkDBAccessPrivileges(), checkPermissionForTables(), checkPrivileges(), QueryRunner::QueryRunner::clearCpuMemory(), QueryRunner::QueryRunner::clearGpuMemory(), Executor::clearMemory(), Catalog_Namespace::Catalog::createDashboardSystemRoles(), createDBObject(), foreign_storage::ForeignDataWrapperFactory::createForeignTableProxy(), foreign_storage::AbstractTextFileDataWrapper::createRenderGroupAnalyzers(), foreign_storage::ParquetDataWrapper::createRenderGroupAnalyzers(), QueryRunner::QueryRunner::createStatement(), CreateForeignServerCommand::execute(), DropForeignServerCommand::execute(), CreateForeignTableCommand::execute(), ShowCreateTableCommand::execute(), ShowDatabasesCommand::execute(), ShowUserDetailsCommand::execute(), ShowRolesCommand::execute(), RefreshForeignTablesCommand::execute(), foreign_storage::ParquetDataWrapper::fetchChunkMetadata(), foreign_storage::ForeignTableSchema::ForeignTableSchema(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_all_dashboards(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_all_role_assignments(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_all_tables(), foreign_storage::anonymous_namespace{InternalMemoryStatsDataWrapper.cpp}::get_column_name(), foreign_storage::get_db_name(), foreign_storage::get_foreign_table_for_key(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_table_ddl(), foreign_storage::get_table_name(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_user_id_to_user_name_map(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_user_name(), QueryRunner::QueryRunner::getBufferPoolStats(), QueryRunner::QueryRunner::getCalcitePlan(), foreign_storage::ParseBufferRequest::getCatalog(), foreign_storage::ParquetImportBatchResult::getChunksAndDictionaries(), lockmgr::TableLockMgrImpl< TableDataLockMgr >::getClusterTableMutex(), foreign_storage::ParquetDataWrapper::getColumnsToInitialize(), getDBObjectPrivileges(), QueryRunner::QueryRunner::getExecutor(), Executor::getExecutor(), QueryRunner::QueryRunner::getMemoryInfo(), QueryRunner::QueryRunner::getParsedGlobalQueryHints(), QueryRunner::QueryRunner::getParsedQueryHint(), QueryRunner::QueryRunner::getParsedQueryHints(), QueryRunner::QueryRunner::getQueryInfoForDataRecyclerTest(), QueryRunner::QueryRunner::getRaExecutionSequence(), QueryRunner::QueryRunner::getRelAlgTranslator(), QueryRunner::QueryRunner::getRootNodeFromParsedQuery(), grantDBObjectPrivileges_unsafe(), hasAnyPrivileges(), EmbeddedDatabase::DBEngineImpl::importArrowTable(), foreign_storage::init_chunk_for_column(), foreign_storage::Csv::init_chunk_for_column(), foreign_storage::InternalCatalogDataWrapper::initializeObjectsForTable(), foreign_storage::InternalMemoryStatsDataWrapper::initializeObjectsForTable(), foreign_storage::InternalStorageStatsDataWrapper::initializeObjectsForTable(), PersistentStorageMgr::isForeignStorage(), isRoleGrantedToGrantee(), foreign_storage::ParquetDataWrapper::loadBuffersUsingLazyParquetChunkLoader(), DBObject::loadKey(), main(), foreign_storage::InternalSystemDataWrapper::populateChunkBuffers(), foreign_storage::AbstractTextFileDataWrapper::populateChunkBuffers(), foreign_storage::InternalSystemDataWrapper::populateChunkMetadata(), foreign_storage::AbstractTextFileDataWrapper::populateChunkMetadata(), QueryRunner::QueryRunner::QueryRunner(), Catalog_Namespace::Catalog::recordOwnershipOfObjectsInObjectPermissions(), AlterForeignServerCommand::renameForeignServer(), revokeDBObjectPrivileges_unsafe(), QueryRunner::QueryRunner::runDDLStatement(), QueryRunner::QueryRunner::runSelectQuery(), QueryRunner::QueryRunner::runSQL(), QueryRunner::QueryRunner::runSQLWithAllowingInterrupt(), EmbeddedDatabase::DBEngineImpl::setDatabase(), foreign_storage::ForeignTableRefreshScheduler::start(), foreign_storage::AbstractTextFileDataWrapper::updateMetadata(), verifyDBObjectOwnership(), and Catalog_Namespace::UserAlterations::wouldChange().

337  {
338  if (!instance_) {
339  instance_.reset(new SysCatalog());
340  }
341  return *instance_;
342  }
static std::unique_ptr< SysCatalog > instance_
Definition: SysCatalog.h:500

+ Here is the call graph for this function:

bool Catalog_Namespace::SysCatalog::isAggregator ( ) const
inline

Definition at line 336 of file SysCatalog.h.

References aggregator_.

336 { return aggregator_; }
bool Catalog_Namespace::SysCatalog::isDashboardSystemRole ( const std::string &  roleName) const
private

Definition at line 2476 of file SysCatalog.cpp.

References SYSTEM_ROLE_TAG().

Referenced by getCreatedRoles(), getMetadataForAllObjects(), and getRoles().

2476  {
2477  return boost::algorithm::ends_with(roleName, SYSTEM_ROLE_TAG);
2478 }
static const std::string SYSTEM_ROLE_TAG("#dash_system_role")
specifies the content in-memory of a row in the dashboard

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::isRoleGrantedToGrantee ( const std::string &  granteeName,
const std::string &  roleName,
bool  only_direct 
) const

Definition at line 2454 of file SysCatalog.cpp.

References CHECK, getRoleGrantee(), getUserGrantee(), Grantee::hasRole(), and instance().

Referenced by getRoles().

2456  {
2457  sys_read_lock read_lock(this);
2458  if (roleName == granteeName) {
2459  return true;
2460  }
2461  bool is_role_granted = false;
2462  auto* target_role = instance().getRoleGrantee(roleName);
2463  auto has_role = [&](auto grantee_rl) {
2464  is_role_granted = target_role && grantee_rl->hasRole(target_role, only_direct);
2465  };
2466  if (auto* user_role = instance().getUserGrantee(granteeName); user_role) {
2467  has_role(user_role);
2468  } else if (auto* role = instance().getRoleGrantee(granteeName); role) {
2469  has_role(role);
2470  } else {
2471  CHECK(false);
2472  }
2473  return is_role_granted;
2474 }
heavyai::shared_lock< heavyai::shared_mutex > read_lock
static SysCatalog & instance()
Definition: SysCatalog.h:337
Role * getRoleGrantee(const std::string &name) const
User * getUserGrantee(const std::string &name) const
bool hasRole(Role *role, bool only_direct) const
Definition: Grantee.cpp:55
#define CHECK(condition)
Definition: Logger.h:222
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:122

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::shared_ptr< Catalog > Catalog_Namespace::SysCatalog::login ( std::string &  db,
std::string &  username,
const std::string &  password,
UserMetadata user_meta,
bool  check_password = true 
)

logins (connects) a user against a database.

throws a std::exception in all error cases! (including wrong password)

Definition at line 862 of file SysCatalog.cpp.

References Catalog_Namespace::UserMetadata::can_login, getCatalog(), getMetadataForUser(), getMetadataWithDefaultDB(), and loginImpl().

866  {
867  // NOTE(sy): The dbname isn't const because getMetadataWithDefaultDB()
868  // can reset it. The username isn't const because SamlServer's
869  // login()/authenticate_user() can reset it.
870 
871  if (check_password) {
872  loginImpl(username, password, user_meta);
873  } else { // not checking for password so user must exist
874  if (!getMetadataForUser(username, user_meta)) {
875  throw std::runtime_error("Invalid credentials.");
876  }
877  }
878  // we should have a user and user_meta by now
879  if (!user_meta.can_login) {
880  throw std::runtime_error("Unauthorized Access: User " + username + " is deactivated");
881  }
883  getMetadataWithDefaultDB(dbname, username, db_meta, user_meta);
884  return getCatalog(db_meta, false);
885 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
void loginImpl(std::string &username, const std::string &password, UserMetadata &user_meta)
Definition: SysCatalog.cpp:888
void getMetadataWithDefaultDB(std::string &dbname, const std::string &username, Catalog_Namespace::DBMetadata &db_meta, UserMetadata &user_meta)
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::loginImpl ( std::string &  username,
const std::string &  password,
UserMetadata user_meta 
)
private

Definition at line 888 of file SysCatalog.cpp.

References checkPasswordForUser().

Referenced by login().

890  {
891  if (!checkPasswordForUser(password, username, user_meta)) {
892  throw std::runtime_error("Authentication failure");
893  }
894 }
bool checkPasswordForUser(const std::string &passwd, std::string &name, UserMetadata &user)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::migrateDBAccessPrivileges ( )
private

Definition at line 767 of file SysCatalog.cpp.

References AccessPrivileges::ACCESS, CHECK, DatabaseDBObjectType, DBObjectKey::dbId, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, logger::ERROR, getMetadataForDB(), logger::INFO, Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), shared::kRootUserId, LOG, MAPD_VERSION, DBObjectKey::permissionType, DBObject::setName(), DBObject::setObjectType(), sqliteConnector_, to_string(), DBObject::updatePrivileges(), and AccessPrivileges::VIEW_SQL_EDITOR.

Referenced by checkAndExecuteMigrations().

767  {
768  sys_sqlite_lock sqlite_lock(this);
769  sqliteConnector_->query("BEGIN TRANSACTION");
770  try {
771  sqliteConnector_->query(
772  "select name from sqlite_master WHERE type='table' AND "
773  "name='mapd_version_history'");
774  if (sqliteConnector_->getNumRows() == 0) {
775  sqliteConnector_->query(
776  "CREATE TABLE mapd_version_history(version integer, migration_history text "
777  "unique)");
778  } else {
779  sqliteConnector_->query(
780  "select * from mapd_version_history where migration_history = "
781  "'db_access_privileges'");
782  if (sqliteConnector_->getNumRows() != 0) {
783  // both privileges migrated
784  // no need for further execution
785  sqliteConnector_->query("END TRANSACTION");
786  return;
787  }
788  }
789  // Insert check for migration
790  sqliteConnector_->query_with_text_params(
791  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
792  std::vector<std::string>{std::to_string(MAPD_VERSION), "db_access_privileges"});
793 
794  sqliteConnector_->query("select dbid, name from mapd_databases");
795  std::unordered_map<int, string> databases;
796  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
797  databases[sqliteConnector_->getData<int>(i, 0)] =
798  sqliteConnector_->getData<string>(i, 1);
799  }
800 
801  sqliteConnector_->query("select userid, name from mapd_users");
802  std::unordered_map<int, string> users;
803  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
804  users[sqliteConnector_->getData<int>(i, 0)] =
805  sqliteConnector_->getData<string>(i, 1);
806  }
807 
808  // All existing users by default will be granted DB Access permissions
809  // and view sql editor privileges
810  DBMetadata dbmeta;
811  for (auto db_ : databases) {
812  CHECK(getMetadataForDB(db_.second, dbmeta));
813  for (auto user : users) {
814  if (user.first != shared::kRootUserId) {
815  {
816  DBObjectKey key;
818  key.dbId = dbmeta.dbId;
819 
820  // access permission;
821  DBObject object_access(key, AccessPrivileges::ACCESS, dbmeta.dbOwner);
822  object_access.setObjectType(DBObjectType::DatabaseDBObjectType);
823  object_access.setName(dbmeta.dbName);
824  // sql_editor permission
825  DBObject object_editor(
826  key, AccessPrivileges::VIEW_SQL_EDITOR, dbmeta.dbOwner);
827  object_editor.setObjectType(DBObjectType::DatabaseDBObjectType);
828  object_editor.setName(dbmeta.dbName);
829  object_editor.updatePrivileges(object_access);
831  sqliteConnector_, user.second, true, object_editor);
832  }
833  }
834  }
835  }
836  } catch (const std::exception& e) {
837  LOG(ERROR) << "Failed to migrate db access privileges: " << e.what();
838  sqliteConnector_->query("ROLLBACK TRANSACTION");
839  throw;
840  }
841  sqliteConnector_->query("END TRANSACTION");
842  LOG(INFO) << "Successfully migrated db access privileges";
843 }
static const AccessPrivileges VIEW_SQL_EDITOR
Definition: DBObject.h:152
const int kRootUserId
#define LOG(tag)
Definition: Logger.h:216
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:476
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
static const int32_t MAPD_VERSION
Definition: release.h:32
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
int32_t dbId
Definition: DBObject.h:54
static const AccessPrivileges ACCESS
Definition: DBObject.h:153
#define CHECK(condition)
Definition: Logger.h:222
int32_t permissionType
Definition: DBObject.h:53
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::migratePrivileged_old ( )
private

Definition at line 845 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by checkAndExecuteMigrations().

845  {
846  sys_sqlite_lock sqlite_lock(this);
847 
848  sqliteConnector_->query("BEGIN TRANSACTION");
849  try {
850  sqliteConnector_->query(
851  "CREATE TABLE IF NOT EXISTS mapd_privileges (userid integer references "
852  "mapd_users, dbid integer references "
853  "mapd_databases, select_priv boolean, insert_priv boolean, UNIQUE(userid, "
854  "dbid))");
855  } catch (const std::exception& e) {
856  sqliteConnector_->query("ROLLBACK TRANSACTION");
857  throw;
858  }
859  sqliteConnector_->query("END TRANSACTION");
860 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::migratePrivileges ( )
private

Definition at line 509 of file SysCatalog.cpp.

References AccessPrivileges::ALL_DASHBOARD_MIGRATE, AccessPrivileges::ALL_TABLE_MIGRATE, AccessPrivileges::ALL_VIEW_MIGRATE, DashboardDBObjectType, DatabaseDBObjectType, Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), shared::kRootUserId, AccessPrivileges::NONE, sqliteConnector_, TableDBObjectType, run_benchmark_import::type, and ViewDBObjectType.

Referenced by checkAndExecuteMigrations().

509  {
510  sys_sqlite_lock sqlite_lock(this);
511  sqliteConnector_->query("BEGIN TRANSACTION");
512  try {
513  sqliteConnector_->query(
514  "SELECT name FROM sqlite_master WHERE type='table' AND "
515  "name='mapd_object_permissions'");
516  if (sqliteConnector_->getNumRows() != 0) {
517  // already done
518  sqliteConnector_->query("END TRANSACTION");
519  return;
520  }
521 
522  sqliteConnector_->query(
523  "CREATE TABLE IF NOT EXISTS mapd_object_permissions ("
524  "roleName text, "
525  "roleType bool, "
526  "dbId integer references mapd_databases, "
527  "objectName text, "
528  "objectId integer, "
529  "objectPermissionsType integer, "
530  "objectPermissions integer, "
531  "objectOwnerId integer, UNIQUE(roleName, objectPermissionsType, dbId, "
532  "objectId))");
533 
534  // get the list of databases and their grantees
535  sqliteConnector_->query(
536  "SELECT userid, dbid FROM mapd_privileges WHERE select_priv = 1 and insert_priv "
537  "= 1");
538  size_t numRows = sqliteConnector_->getNumRows();
539  vector<pair<int, int>> db_grantees(numRows);
540  for (size_t i = 0; i < numRows; ++i) {
541  db_grantees[i].first = sqliteConnector_->getData<int>(i, 0);
542  db_grantees[i].second = sqliteConnector_->getData<int>(i, 1);
543  }
544  // map user names to user ids
545  sqliteConnector_->query("select userid, name from mapd_users");
546  numRows = sqliteConnector_->getNumRows();
547  std::unordered_map<int, string> users_by_id;
548  std::unordered_map<int, bool> user_has_privs;
549  for (size_t i = 0; i < numRows; ++i) {
550  users_by_id[sqliteConnector_->getData<int>(i, 0)] =
551  sqliteConnector_->getData<string>(i, 1);
552  user_has_privs[sqliteConnector_->getData<int>(i, 0)] = false;
553  }
554  // map db names to db ids
555  sqliteConnector_->query("select dbid, name from mapd_databases");
556  numRows = sqliteConnector_->getNumRows();
557  std::unordered_map<int, string> dbs_by_id;
558  for (size_t i = 0; i < numRows; ++i) {
559  dbs_by_id[sqliteConnector_->getData<int>(i, 0)] =
560  sqliteConnector_->getData<string>(i, 1);
561  }
562  // migrate old privileges to new privileges: if user had insert access to database, he
563  // was a grantee
564  for (const auto& grantee : db_grantees) {
565  user_has_privs[grantee.first] = true;
566  auto dbName = dbs_by_id[grantee.second];
567  {
568  // table level permissions
570  DBObjectKey key{type, grantee.second};
571  DBObject object(
574  sqliteConnector_, users_by_id[grantee.first], true, object);
575  }
576 
577  {
578  // dashboard level permissions
580  DBObjectKey key{type, grantee.second};
581  DBObject object(dbName,
582  type,
583  key,
587  sqliteConnector_, users_by_id[grantee.first], true, object);
588  }
589 
590  {
591  // view level permissions
593  DBObjectKey key{type, grantee.second};
594  DBObject object(
597  sqliteConnector_, users_by_id[grantee.first], true, object);
598  }
599  }
600  for (auto user : user_has_privs) {
601  auto dbName = dbs_by_id[0];
602  if (user.second == false && user.first != shared::kRootUserId) {
603  {
605  DBObjectKey key{type, 0};
608  sqliteConnector_, users_by_id[user.first], true, object);
609  }
610  }
611  }
612  } catch (const std::exception&) {
613  sqliteConnector_->query("ROLLBACK TRANSACTION");
614  throw;
615  }
616  sqliteConnector_->query("END TRANSACTION");
617 }
const int kRootUserId
static const AccessPrivileges ALL_TABLE_MIGRATE
Definition: DBObject.h:156
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:476
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
static const AccessPrivileges ALL_DASHBOARD_MIGRATE
Definition: DBObject.h:168
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
static const AccessPrivileges NONE
Definition: DBObject.h:148
static const AccessPrivileges ALL_VIEW_MIGRATE
Definition: DBObject.h:176

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::string Catalog_Namespace::SysCatalog::name ( ) const
inline

Definition at line 350 of file SysCatalog.h.

References shared::kDefaultDbName.

Referenced by alterUser(), buildRoleMapUnlocked(), createUser(), and Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::get_users().

350 { return shared::kDefaultDbName; }
const std::string kDefaultDbName

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::populateRoleDbObjects ( const std::vector< DBObject > &  objects)

Definition at line 2600 of file SysCatalog.cpp.

References CHECK, getMetadataForUserById(), getUserGrantee(), Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), sqliteConnector_, and Catalog_Namespace::UserMetadata::userName.

Referenced by Catalog_Namespace::Catalog::recordOwnershipOfObjectsInObjectPermissions().

2600  {
2601  sys_write_lock write_lock(this);
2602  sys_sqlite_lock sqlite_lock(this);
2603  sqliteConnector_->query("BEGIN TRANSACTION");
2604  try {
2605  for (auto dbobject : objects) {
2606  UserMetadata user;
2607  CHECK(getMetadataForUserById(dbobject.getOwner(), user));
2608  auto* grantee = getUserGrantee(user.userName);
2609  if (grantee) {
2611  sqliteConnector_, grantee->getName(), true, dbobject);
2612  grantee->grantPrivileges(dbobject);
2613  }
2614  }
2615 
2616  } catch (const std::exception& e) {
2617  sqliteConnector_->query("ROLLBACK TRANSACTION");
2618  throw;
2619  }
2620  sqliteConnector_->query("END TRANSACTION");
2621 }
heavyai::unique_lock< heavyai::shared_mutex > write_lock
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:476
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
User * getUserGrantee(const std::string &name) const
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
#define CHECK(condition)
Definition: Logger.h:222

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::reassignObjectOwners ( const std::map< int32_t, std::vector< DBObject >> &  old_owner_db_objects,
int32_t  new_owner_id,
const Catalog_Namespace::Catalog catalog 
)

Reassigns database object ownership from a set of users (old owners) to another user (new owner).

Parameters
old_owner_db_objects- map of user ids and database objects whose ownership will be reassigned
new_owner_id- id of user who will own reassigned database objects
catalog- catalog for database where ownership reassignment occurred

Definition at line 2934 of file SysCatalog.cpp.

References CHECK, shared::contains(), Catalog_Namespace::Catalog::getDatabaseId(), getMetadataForUserById(), grantDBObjectPrivilegesBatch_unsafe(), granteeMap_, Catalog_Namespace::UserMetadata::isSuper, objectDescriptorMap_, rebuildObjectMapsUnlocked(), revokeDBObjectPrivilegesBatch_unsafe(), sqliteConnector_, to_string(), and Catalog_Namespace::UserMetadata::userName.

2937  {
2938  sys_write_lock write_lock(this);
2939  sys_sqlite_lock sqlite_lock(this);
2940 
2941  sqliteConnector_->query("BEGIN TRANSACTION");
2942  try {
2943  UserMetadata new_owner;
2944  CHECK(getMetadataForUserById(new_owner_id, new_owner));
2945  for (const auto& [old_owner_id, db_objects] : old_owner_db_objects) {
2946  UserMetadata old_owner;
2947  CHECK(getMetadataForUserById(old_owner_id, old_owner));
2948  if (!old_owner.isSuper) {
2949  revokeDBObjectPrivilegesBatch_unsafe({old_owner.userName}, db_objects, catalog);
2950  }
2951  if (!new_owner.isSuper) {
2952  grantDBObjectPrivilegesBatch_unsafe({new_owner.userName}, db_objects, catalog);
2953  }
2954  }
2955 
2956  std::set<int32_t> old_owner_ids;
2957  for (const auto& [old_owner_id, db_objects] : old_owner_db_objects) {
2958  old_owner_ids.emplace(old_owner_id);
2959  }
2960 
2961  auto db_id = catalog.getDatabaseId();
2962  for (const auto old_user_id : old_owner_ids) {
2963  sqliteConnector_->query_with_text_params(
2964  "UPDATE mapd_object_permissions SET objectOwnerId = ? WHERE objectOwnerId = ? "
2965  "AND dbId = ? AND objectId != -1",
2966  std::vector<std::string>{std::to_string(new_owner_id),
2967  std::to_string(old_user_id),
2968  std::to_string(db_id)});
2969  }
2970 
2971  for (const auto& [user_or_role, grantee] : granteeMap_) {
2972  grantee->reassignObjectOwners(old_owner_ids, new_owner_id, db_id);
2973  }
2974 
2975  for (const auto& [object_key, object_descriptor] : objectDescriptorMap_) {
2976  if (object_descriptor->objectId != -1 && object_descriptor->dbId == db_id &&
2977  shared::contains(old_owner_ids, object_descriptor->objectOwnerId)) {
2978  object_descriptor->objectOwnerId = new_owner_id;
2979  }
2980  }
2981  } catch (std::exception& e) {
2982  sqliteConnector_->query("ROLLBACK TRANSACTION");
2984  throw;
2985  }
2986  sqliteConnector_->query("END TRANSACTION");
2987 }
bool contains(const T &container, const U &element)
Definition: misc.h:195
void revokeDBObjectPrivilegesBatch_unsafe(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
heavyai::unique_lock< heavyai::shared_mutex > write_lock
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
int getDatabaseId() const
Definition: Catalog.h:298
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
void grantDBObjectPrivilegesBatch_unsafe(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
#define CHECK(condition)
Definition: Logger.h:222

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::rebuildObjectMapsUnlocked ( )
private

Definition at line 3046 of file SysCatalog.cpp.

References buildObjectDescriptorMapUnlocked(), buildRoleMapUnlocked(), granteeMap_, and objectDescriptorMap_.

Referenced by changeDBObjectOwnership(), and reassignObjectOwners().

3046  {
3047  // Rebuild updated maps from storage
3048  granteeMap_.clear();
3050  objectDescriptorMap_.clear();
3052 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::recordExecutedMigration ( const std::string &  migration_name) const
private

Definition at line 3021 of file SysCatalog.cpp.

References createVersionHistoryTable(), hasVersionHistoryTable(), MAPD_VERSION, sqliteConnector_, and to_string().

Referenced by initializeInformationSchemaDb().

3021  {
3022  if (!hasVersionHistoryTable()) {
3024  }
3025  sys_sqlite_lock sqlite_lock(this);
3026  sqliteConnector_->query_with_text_params(
3027  "INSERT INTO mapd_version_history(version, migration_history) values(?, ?)",
3028  std::vector<std::string>{std::to_string(MAPD_VERSION), migration_name});
3029 }
std::string to_string(char const *&&v)
bool hasVersionHistoryTable() const
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
static const int32_t MAPD_VERSION
Definition: release.h:32
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
void createVersionHistoryTable() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::removeCatalog ( const std::string &  dbName)

Definition at line 2930 of file SysCatalog.cpp.

References cat_map_.

Referenced by createDatabase(), dropDatabase(), and renameDatabase().

2930  {
2931  cat_map_.erase(dbName);
2932 }

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::renameDatabase ( std::string const &  old_name,
std::string const &  new_name 
)

Definition at line 1313 of file SysCatalog.cpp.

References DatabaseDBObjectType, Catalog_Namespace::CommonFileOperations::duplicateAndRenameCatalog(), getMetadataForDB(), shared::kSystemCatalogName, removeCatalog(), Catalog_Namespace::CommonFileOperations::removeCatalogByFullPath(), sqliteConnector_, to_string(), to_upper(), and yieldTransactionStreamer().

1314  {
1315  using namespace std::string_literals;
1316  sys_write_lock write_lock(this);
1317  sys_sqlite_lock sqlite_lock(this);
1318 
1319  DBMetadata new_db;
1320  if (getMetadataForDB(new_name, new_db)) {
1321  throw std::runtime_error("Database " + new_name + " already exists.");
1322  }
1323  if (to_upper(new_name) == to_upper(shared::kSystemCatalogName)) {
1324  throw std::runtime_error("Database name " + new_name + "is reserved.");
1325  }
1326 
1327  DBMetadata old_db;
1328  if (!getMetadataForDB(old_name, old_db)) {
1329  throw std::runtime_error("Database " + old_name + " does not exists.");
1330  }
1331 
1332  removeCatalog(old_db.dbName);
1333 
1334  std::string old_catalog_path, new_catalog_path;
1335  std::tie(old_catalog_path, new_catalog_path) =
1336  duplicateAndRenameCatalog(old_name, new_name);
1337 
1338  auto transaction_streamer = yieldTransactionStreamer();
1339  auto failure_handler = [this, new_catalog_path] {
1340  removeCatalogByFullPath(new_catalog_path);
1341  };
1342  auto success_handler = [this, old_catalog_path] {
1343  removeCatalogByFullPath(old_catalog_path);
1344  };
1345 
1346  auto q1 = {"UPDATE mapd_databases SET name=?1 WHERE name=?2;"s, new_name, old_name};
1347  auto q2 = {
1348  "UPDATE mapd_object_permissions SET objectName=?1 WHERE objectNAME=?2 and (objectPermissionsType=?3 or objectId = -1) and dbId=?4;"s,
1349  new_name,
1350  old_name,
1352  std::to_string(old_db.dbId)};
1353 
1354  transaction_streamer(sqliteConnector_, success_handler, failure_handler, q1, q2);
1355 }
auto duplicateAndRenameCatalog(std::string const &current_name, std::string const &new_name)
Definition: SysCatalog.cpp:143
void removeCatalog(const std::string &dbName)
const std::string kSystemCatalogName
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
std::string to_upper(const std::string &str)
void removeCatalogByFullPath(std::string const &full_path)
Definition: SysCatalog.cpp:135
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::renameDBObject ( const std::string &  objectName,
const std::string &  newName,
DBObjectType  type,
int32_t  objectId,
const Catalog_Namespace::Catalog catalog 
)

Renames an DBObject

Parameters
objectName- original DBObject name
newName- new name of DBObject
type- type of DBObject
objectId- original DBObject ID
catalog- Catalog instance object exists in

Definition at line 1810 of file SysCatalog.cpp.

References DBObjectKey::dbId, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::Catalog::getCurrentDB(), getGrantee(), getMetadataForObject(), DBObjectKey::objectId, DBObjectKey::permissionType, Grantee::renameDbObject(), renameObjectsInDescriptorMap(), DBObject::setObjectKey(), and run_benchmark_import::type.

1814  {
1815  sys_write_lock write_lock(this);
1816  DBObject new_object(newName, type);
1817  DBObjectKey key;
1818  key.dbId = catalog.getCurrentDB().dbId;
1819  key.objectId = objectId;
1820  key.permissionType = type;
1821  new_object.setObjectKey(key);
1822  auto objdescs =
1823  getMetadataForObject(key.dbId, static_cast<int32_t>(type), key.objectId);
1824  for (auto obj : objdescs) {
1825  Grantee* grnt = getGrantee(obj->roleName);
1826  if (grnt) {
1827  grnt->renameDbObject(new_object);
1828  }
1829  }
1830  renameObjectsInDescriptorMap(new_object, catalog);
1831 }
Grantee * getGrantee(const std::string &name) const
int32_t objectId
Definition: DBObject.h:55
heavyai::unique_lock< heavyai::shared_mutex > write_lock
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:242
void renameObjectsInDescriptorMap(DBObject &object, const Catalog_Namespace::Catalog &cat)
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
int32_t dbId
Definition: DBObject.h:54
int32_t permissionType
Definition: DBObject.h:53
std::vector< ObjectRoleDescriptor * > getMetadataForObject(int32_t dbId, int32_t dbType, int32_t objectId) const
virtual void renameDbObject(const DBObject &object)
Definition: Grantee.cpp:121

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::renameObjectsInDescriptorMap ( DBObject object,
const Catalog_Namespace::Catalog cat 
)

Definition at line 2299 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::Catalog::getCurrentDB(), objectDescriptorMap_, sqliteConnector_, and to_string().

Referenced by renameDBObject().

2300  {
2301  sys_write_lock write_lock(this);
2302  sys_sqlite_lock sqlite_lock(this);
2303  auto range = objectDescriptorMap_.equal_range(
2304  std::to_string(cat.getCurrentDB().dbId) + ":" +
2305  std::to_string(object.getObjectKey().permissionType) + ":" +
2306  std::to_string(object.getObjectKey().objectId));
2307  for (auto d = range.first; d != range.second; ++d) {
2308  // rename object
2309  d->second->objectName = object.getName();
2310  }
2311 
2312  sqliteConnector_->query("BEGIN TRANSACTION");
2313  try {
2314  sqliteConnector_->query_with_text_params(
2315  "UPDATE mapd_object_permissions SET objectName = ?1 WHERE "
2316  "dbId = ?2 AND objectId = ?3",
2317  std::vector<std::string>{object.getName(),
2319  std::to_string(object.getObjectKey().objectId)});
2320  } catch (const std::exception& e) {
2321  sqliteConnector_->query("ROLLBACK TRANSACTION");
2322  throw;
2323  }
2324  sqliteConnector_->query("END TRANSACTION");
2325 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
heavyai::unique_lock< heavyai::shared_mutex > write_lock
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:242
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::renameUser ( std::string const &  old_name,
std::string const &  new_name 
)

Definition at line 1264 of file SysCatalog.cpp.

References CHECK, Catalog_Namespace::g_log_user_id, getGrantee(), getMetadataForUser(), sqliteConnector_, temporary_users_by_name_, updateUserRoleName(), and yieldTransactionStreamer().

1264  {
1265  using namespace std::string_literals;
1266  sys_write_lock write_lock(this);
1267  sys_sqlite_lock sqlite_lock(this);
1268 
1269  UserMetadata old_user;
1270  if (!getMetadataForUser(old_name, old_user)) {
1271  std::string const loggable = g_log_user_id ? std::string("") : old_name + ' ';
1272  throw std::runtime_error("User " + loggable + "doesn't exist.");
1273  }
1274 
1275  UserMetadata new_user;
1276  if (getMetadataForUser(new_name, new_user)) {
1277  throw std::runtime_error("User " + new_user.userLoggable() + " already exists.");
1278  }
1279 
1280  if (getGrantee(new_name)) {
1281  std::string const loggable = g_log_user_id ? std::string("") : new_name + ' ';
1282  throw runtime_error(
1283  "Username " + loggable +
1284  "is same as one of existing grantees. User and role names should be unique.");
1285  }
1286 
1287  // Temporary user.
1288  if (old_user.is_temporary) {
1289  auto userit = temporary_users_by_name_.find(old_name);
1290  CHECK(userit != temporary_users_by_name_.end());
1291  auto node = temporary_users_by_name_.extract(userit);
1292  node.key() = new_name;
1293  temporary_users_by_name_.insert(std::move(node));
1294  userit->second->userName = new_name;
1295  updateUserRoleName(old_name, new_name);
1296  return;
1297  }
1298 
1299  // Normal user.
1300  auto transaction_streamer = yieldTransactionStreamer();
1301  auto failure_handler = [] {};
1302  auto success_handler = [this, &old_name, &new_name] {
1303  updateUserRoleName(old_name, new_name);
1304  };
1305  auto q1 = {"UPDATE mapd_users SET name=?1 where name=?2;"s, new_name, old_name};
1306  auto q2 = {"UPDATE mapd_object_permissions set roleName=?1 WHERE roleName=?2;"s,
1307  new_name,
1308  old_name};
1309  auto q3 = {"UPDATE mapd_roles set userName=?1 WHERE userName=?2;"s, new_name, old_name};
1310  transaction_streamer(sqliteConnector_, success_handler, failure_handler, q1, q2, q3);
1311 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
Grantee * getGrantee(const std::string &name) const
heavyai::unique_lock< heavyai::shared_mutex > write_lock
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:512
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:122
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484
void updateUserRoleName(const std::string &roleName, const std::string &newName)
#define CHECK(condition)
Definition: Logger.h:222

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::revokeAllOnDatabase_unsafe ( const std::string &  roleName,
int32_t  dbId,
Grantee grantee 
)
private

Definition at line 1983 of file SysCatalog.cpp.

References objectDescriptorMap_, Grantee::revokeAllOnDatabase(), sqliteConnector_, temporary_users_by_name_, and to_string().

Referenced by dropDatabase(), and revokeDBObjectPrivileges_unsafe().

1985  {
1986  bool is_temporary =
1987  (temporary_users_by_name_.find(roleName) != temporary_users_by_name_.end());
1988  if (!is_temporary) {
1989  sys_sqlite_lock sqlite_lock(this);
1990  sqliteConnector_->query_with_text_params(
1991  "DELETE FROM mapd_object_permissions WHERE roleName = ?1 and dbId = ?2",
1992  std::vector<std::string>{roleName, std::to_string(dbId)});
1993  }
1994  grantee->revokeAllOnDatabase(dbId);
1995  for (auto d = objectDescriptorMap_.begin(); d != objectDescriptorMap_.end();) {
1996  if (d->second->roleName == roleName && d->second->dbId == dbId) {
1997  d = objectDescriptorMap_.erase(d);
1998  } else {
1999  d++;
2000  }
2001  }
2002 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:483
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:123
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:512
virtual void revokeAllOnDatabase(int32_t dbId)
Definition: Grantee.cpp:296
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:484

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::revokeDBObjectPrivileges ( const std::string &  grantee,
const DBObject object,
const Catalog_Namespace::Catalog catalog 
)

Definition at line 2753 of file SysCatalog.cpp.

References execInTransaction(), and revokeDBObjectPrivileges_unsafe().

2755  {