OmniSciDB  ba1bac9284
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
TableArchiver Class Reference

#include <TableArchiver.h>

+ Collaboration diagram for TableArchiver:

Public Member Functions

 TableArchiver (Catalog_Namespace::Catalog *cat)
 
void dumpTable (const TableDescriptor *td, const std::string &archive_path, const std::string &compression)
 
void restoreTable (const Catalog_Namespace::SessionInfo &session, const TableDescriptor *td, const std::string &archive_path, const std::string &compression)
 
void restoreTable (const Catalog_Namespace::SessionInfo &session, const std::string &table_name, const std::string &archive_path, const std::string &compression)
 

Private Attributes

Catalog_Namespace::Catalogcat_
 

Detailed Description

Definition at line 24 of file TableArchiver.h.

Constructor & Destructor Documentation

TableArchiver::TableArchiver ( Catalog_Namespace::Catalog cat)
inline

Definition at line 26 of file TableArchiver.h.

26 : cat_(cat){};
Catalog_Namespace::Catalog * cat_
Definition: TableArchiver.h:43

Member Function Documentation

void TableArchiver::dumpTable ( const TableDescriptor td,
const std::string &  archive_path,
const std::string &  compression 
)

Definition at line 244 of file TableArchiver.cpp.

References anonymous_namespace{TableArchiver.cpp}::abs_path(), cat_, Catalog_Namespace::DBMetadata::dbId, Data_Namespace::DISK_LEVEL, Catalog_Namespace::Catalog::dumpSchema(), ddl_utils::EXPORT, omnisci::fopen(), g_cluster, get_quoted_string(), Catalog_Namespace::Catalog::getAllColumnMetadataForTable(), Catalog_Namespace::Catalog::getColumnDictDirectory(), Catalog_Namespace::Catalog::getCurrentDB(), Catalog_Namespace::Catalog::getDataMgr(), Data_Namespace::DataMgr::getGlobalFileMgr(), lockmgr::TableLockMgrImpl< TableSchemaLockMgr >::getReadLockForTable(), Catalog_Namespace::Catalog::getTableDataDirectories(), Catalog_Namespace::Catalog::getTableDictDirectories(), Catalog_Namespace::Catalog::getTableEpoch(), TableDescriptor::isView, join(), TableDescriptor::persistenceLevel, run, anonymous_namespace{TableArchiver.cpp}::simple_file_closer, table_epoch_filename, table_oldinfo_filename, table_schema_filename, TableDescriptor::tableId, TableDescriptor::tableName, to_string(), and ddl_utils::validate_allowed_file_path().

Referenced by Parser::DumpTableStmt::execute().

246  {
249  if (g_cluster) {
250  throw std::runtime_error("DUMP/RESTORE is not supported yet on distributed setup.");
251  }
252  if (boost::filesystem::exists(archive_path)) {
253  throw std::runtime_error("Archive " + archive_path + " already exists.");
254  }
256  throw std::runtime_error("Dumping view or temporary table is not supported.");
257  }
258  // collect paths of files to archive
259  const auto global_file_mgr = cat_->getDataMgr().getGlobalFileMgr();
260  std::vector<std::string> file_paths;
261  auto file_writer = [&file_paths, global_file_mgr](const std::string& file_name,
262  const std::string& file_type,
263  const std::string& file_data) {
264  const auto file_path = abs_path(global_file_mgr) + "/" + file_name;
265  std::unique_ptr<FILE, decltype(simple_file_closer)> fp(
266  std::fopen(file_path.c_str(), "w"), simple_file_closer);
267  if (!fp) {
268  throw std::runtime_error("Failed to create " + file_type + " file '" + file_path +
269  "': " + std::strerror(errno));
270  }
271  if (std::fwrite(file_data.data(), 1, file_data.size(), fp.get()) < file_data.size()) {
272  throw std::runtime_error("Failed to write " + file_type + " file '" + file_path +
273  "': " + std::strerror(errno));
274  }
275  file_paths.push_back(file_name);
276  };
277  // Prevent modification of the table schema during a dump operation, while allowing
278  // concurrent inserts.
279  auto table_read_lock =
281  const auto table_name = td->tableName;
282  {
283  // - gen schema file
284  const auto schema_str = cat_->dumpSchema(td);
285  file_writer(table_schema_filename, "table schema", schema_str);
286  // - gen column-old-info file
287  const auto cds = cat_->getAllColumnMetadataForTable(td->tableId, true, true, true);
288  std::vector<std::string> column_oldinfo;
289  std::transform(cds.begin(),
290  cds.end(),
291  std::back_inserter(column_oldinfo),
292  [&](const auto cd) -> std::string {
293  return cd->columnName + ":" + std::to_string(cd->columnId) + ":" +
295  });
296  const auto column_oldinfo_str = boost::algorithm::join(column_oldinfo, " ");
297  file_writer(table_oldinfo_filename, "table old info", column_oldinfo_str);
298  // - gen table epoch
299  const auto epoch = cat_->getTableEpoch(cat_->getCurrentDB().dbId, td->tableId);
300  file_writer(table_epoch_filename, "table epoch", std::to_string(epoch));
301  // - collect table data file paths ...
302  const auto data_file_dirs = cat_->getTableDataDirectories(td);
303  file_paths.insert(file_paths.end(), data_file_dirs.begin(), data_file_dirs.end());
304  // - collect table dict file paths ...
305  const auto dict_file_dirs = cat_->getTableDictDirectories(td);
306  file_paths.insert(file_paths.end(), dict_file_dirs.begin(), dict_file_dirs.end());
307  // tar takes time. release cat lock to yield the cat to concurrent CREATE statements.
308  }
309  // run tar to archive the files ... this may take a while !!
310  run("tar " + compression + " -cvf " + get_quoted_string(archive_path) + " " +
311  boost::algorithm::join(file_paths, " "),
312  abs_path(global_file_mgr));
313 }
static ReadLock getReadLockForTable(const Catalog_Namespace::Catalog &cat, const std::string &table_name)
Definition: LockMgrImpl.h:164
static constexpr char const * table_schema_filename
std::string tableName
std::string abs_path(const File_Namespace::GlobalFileMgr *global_file_mgr)
::FILE * fopen(const char *filename, const char *mode)
Definition: omnisci_fs.cpp:72
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:223
std::string join(T const &container, std::string const &delim)
static constexpr char const * table_oldinfo_filename
int32_t getTableEpoch(const int32_t db_id, const int32_t table_id) const
Definition: Catalog.cpp:2804
std::vector< std::string > getTableDataDirectories(const TableDescriptor *td) const
Definition: Catalog.cpp:4372
std::string to_string(char const *&&v)
std::string getColumnDictDirectory(const ColumnDescriptor *cd) const
Definition: Catalog.cpp:4386
std::string get_quoted_string(const std::string &filename, char quote, char escape)
Quote a string while escaping any existing quotes in the string.
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:222
File_Namespace::GlobalFileMgr * getGlobalFileMgr() const
Definition: DataMgr.cpp:543
void validate_allowed_file_path(const std::string &file_path, const DataTransferType data_transfer_type, const bool allow_wildcards)
Definition: DdlUtils.cpp:634
std::vector< std::string > getTableDictDirectories(const TableDescriptor *td) const
Definition: Catalog.cpp:4402
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:1771
Data_Namespace::MemoryLevel persistenceLevel
static constexpr char const * table_epoch_filename
bool g_cluster
static bool run
std::string dumpSchema(const TableDescriptor *td) const
Definition: Catalog.cpp:4418
Catalog_Namespace::Catalog * cat_
Definition: TableArchiver.h:43

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void TableArchiver::restoreTable ( const Catalog_Namespace::SessionInfo session,
const TableDescriptor td,
const std::string &  archive_path,
const std::string &  compression 
)

Definition at line 316 of file TableArchiver.cpp.

References anonymous_namespace{TableArchiver.cpp}::abs_path(), anonymous_namespace{TableArchiver.cpp}::adjust_altered_table_files(), cat_, Catalog_Namespace::DBMetadata::dbId, Data_Namespace::DISK_LEVEL, measure< TimeT >::execution(), g_cluster, g_test_rollback_dump_restore, get_quoted_string(), anonymous_namespace{TableArchiver.cpp}::get_table_schema(), Catalog_Namespace::Catalog::getAllColumnMetadataForTable(), Catalog_Namespace::Catalog::getColumnDictDirectory(), Catalog_Namespace::Catalog::getCurrentDB(), Catalog_Namespace::Catalog::getDataMgr(), Data_Namespace::DataMgr::getGlobalFileMgr(), lockmgr::TableLockMgrImpl< TableSchemaLockMgr >::getReadLockForTable(), Catalog_Namespace::Catalog::getTableDataDirectories(), Catalog_Namespace::Catalog::getTableDictDirectories(), lockmgr::TableLockMgrImpl< InsertDataLockMgr >::getWriteLockForTable(), TableDescriptor::hasDeletedCol, ddl_utils::IMPORT, TableDescriptor::isView, join(), TableDescriptor::nShards, TableDescriptor::persistenceLevel, anonymous_namespace{TableArchiver.cpp}::rename_table_directories(), run, Catalog_Namespace::Catalog::setTableEpoch(), anonymous_namespace{TableArchiver.cpp}::simple_file_cat(), split(), table_epoch_filename, table_oldinfo_filename, table_schema_filename, TableDescriptor::tableId, TableDescriptor::tableName, to_string(), ddl_utils::validate_allowed_file_path(), and VLOG.

Referenced by Parser::RestoreTableStmt::execute(), and restoreTable().

319  {
322  if (g_cluster) {
323  throw std::runtime_error("DUMP/RESTORE is not supported yet on distributed setup.");
324  }
325  if (!boost::filesystem::exists(archive_path)) {
326  throw std::runtime_error("Archive " + archive_path + " does not exist.");
327  }
329  throw std::runtime_error("Restoring view or temporary table is not supported.");
330  }
331  // Obtain table schema read lock to prevent modification of the schema during
332  // restoration
333  const auto table_read_lock =
335  // prevent concurrent inserts into table during restoration
336  const auto insert_data_lock =
338 
339  // untar takes time. no grab of cat lock to yield to concurrent CREATE stmts.
340  const auto global_file_mgr = cat_->getDataMgr().getGlobalFileMgr();
341  // dirs where src files are untarred and dst files are backed up
342  constexpr static const auto temp_data_basename = "_data";
343  constexpr static const auto temp_back_basename = "_back";
344  const auto temp_data_dir = abs_path(global_file_mgr) + "/" + temp_data_basename;
345  const auto temp_back_dir = abs_path(global_file_mgr) + "/" + temp_back_basename;
346  // clean up tmp dirs and files in any case
347  auto tmp_files_cleaner = [&](void*) {
348  run("rm -rf " + temp_data_dir + " " + temp_back_dir);
349  run("rm -f " + abs_path(global_file_mgr) + "/" + table_schema_filename);
350  run("rm -f " + abs_path(global_file_mgr) + "/" + table_oldinfo_filename);
351  run("rm -f " + abs_path(global_file_mgr) + "/" + table_epoch_filename);
352  };
353  std::unique_ptr<decltype(tmp_files_cleaner), decltype(tmp_files_cleaner)> tfc(
354  &tmp_files_cleaner, tmp_files_cleaner);
355  // extract & parse schema
356  const auto schema_str = get_table_schema(archive_path, td->tableName, compression);
357  const auto create_table_stmt =
358  Parser::parseDDL<Parser::CreateTableStmt>("table schema", schema_str);
359  // verify compatibility between source and destination schemas
360  TableDescriptor src_td;
361  std::list<ColumnDescriptor> src_columns;
362  std::vector<Parser::SharedDictionaryDef> shared_dict_defs;
363  create_table_stmt->executeDryRun(session, src_td, src_columns, shared_dict_defs);
364  // - sanity check table-level compatibility
365  if (src_td.hasDeletedCol != td->hasDeletedCol) {
366  // TODO: allow the case, in which src data enables vacuum while
367  // dst doesn't, by simply discarding src $deleted column data.
368  throw std::runtime_error("Incompatible table VACCUM option");
369  }
370  if (src_td.nShards != td->nShards) {
371  // TODO: allow different shard numbers if they have a "GCD",
372  // by splitting/merging src data files before drop into dst.
373  throw std::runtime_error("Unmatched number of table shards");
374  }
375  // - sanity check column-level compatibility (based on column names)
376  const auto dst_columns =
377  cat_->getAllColumnMetadataForTable(td->tableId, false, false, false);
378  if (dst_columns.size() != src_columns.size()) {
379  throw std::runtime_error("Unmatched number of table columns");
380  }
381  for (const auto& [src_cd, dst_cd] : boost::combine(src_columns, dst_columns)) {
382  if (src_cd.columnType.get_type_name() != dst_cd->columnType.get_type_name() ||
383  src_cd.columnType.get_compression_name() !=
384  dst_cd->columnType.get_compression_name()) {
385  throw std::runtime_error("Incompatible types on column " + src_cd.columnName);
386  }
387  }
388  // extract src table column ids (ALL columns incl. system/virtual/phy geo cols)
389  const auto all_src_oldinfo_str =
390  simple_file_cat(archive_path, table_oldinfo_filename, compression);
391  std::vector<std::string> src_oldinfo_strs;
392  boost::algorithm::split(src_oldinfo_strs,
393  all_src_oldinfo_str,
394  boost::is_any_of(" "),
395  boost::token_compress_on);
396  auto all_dst_columns =
397  cat_->getAllColumnMetadataForTable(td->tableId, true, true, true);
398  if (src_oldinfo_strs.size() != all_dst_columns.size()) {
399  throw std::runtime_error("Source table has a unmatched number of columns: " +
400  std::to_string(src_oldinfo_strs.size()) + " vs " +
401  std::to_string(all_dst_columns.size()));
402  }
403  // build a map of src column ids and dst column ids, just in case src table has been
404  // ALTERed before and chunk keys of src table needs to be adjusted accordingly.
405  // note: this map is used only for the case of migrating a table and not for restoring
406  // a table. When restoring a table, the two tables must have the same column ids.
407  //
408  // also build a map of src dict paths and dst dict paths for relocating src dicts
409  std::unordered_map<int, int> column_ids_map;
410  std::unordered_map<std::string, std::string> dict_paths_map;
411  // sort inputs of transform in lexical order of column names for correct mappings
412  std::list<std::vector<std::string>> src_oldinfo_tokens;
413  std::transform(
414  src_oldinfo_strs.begin(),
415  src_oldinfo_strs.end(),
416  std::back_inserter(src_oldinfo_tokens),
417  [](const auto& src_oldinfo_str) -> auto {
418  std::vector<std::string> tokens;
420  tokens, src_oldinfo_str, boost::is_any_of(":"), boost::token_compress_on);
421  return tokens;
422  });
423  src_oldinfo_tokens.sort(
424  [](const auto& lhs, const auto& rhs) { return lhs[0].compare(rhs[0]) < 0; });
425  all_dst_columns.sort(
426  [](auto a, auto b) { return a->columnName.compare(b->columnName) < 0; });
427  // transform inputs into the maps
428  std::transform(src_oldinfo_tokens.begin(),
429  src_oldinfo_tokens.end(),
430  all_dst_columns.begin(),
431  std::inserter(column_ids_map, column_ids_map.end()),
432  [&](const auto& tokens, const auto& cd) -> std::pair<int, int> {
433  VLOG(3) << boost::algorithm::join(tokens, ":") << " ==> "
434  << cd->columnName << ":" << cd->columnId;
435  dict_paths_map[tokens[2]] = cat_->getColumnDictDirectory(cd);
436  return {boost::lexical_cast<int>(tokens[1]), cd->columnId};
437  });
438  bool was_table_altered = false;
439  std::for_each(column_ids_map.begin(), column_ids_map.end(), [&](auto& it) {
440  was_table_altered = was_table_altered || it.first != it.second;
441  });
442  VLOG(3) << "was_table_altered = " << was_table_altered;
443  // extract all data files to a temp dir. will swap with dst table dir after all set,
444  // otherwise will corrupt table in case any bad thing happens in the middle.
445  run("rm -rf " + temp_data_dir);
446  run("mkdir -p " + temp_data_dir);
447  run("tar " + compression + " -xvf " + get_quoted_string(archive_path), temp_data_dir);
448  // if table was ever altered after it was created, update column ids in chunk headers.
449  if (was_table_altered) {
450  const auto time_ms = measure<>::execution(
451  [&]() { adjust_altered_table_files(temp_data_dir, column_ids_map); });
452  VLOG(3) << "adjust_altered_table_files: " << time_ms << " ms";
453  }
454  // finally,,, swap table data/dict dirs!
455  const auto data_file_dirs = cat_->getTableDataDirectories(td);
456  const auto dict_file_dirs = cat_->getTableDictDirectories(td);
457  // move current target dirs, if exists, to backup dir
458  std::vector<std::string> both_file_dirs;
459  std::merge(data_file_dirs.begin(),
460  data_file_dirs.end(),
461  dict_file_dirs.begin(),
462  dict_file_dirs.end(),
463  std::back_inserter(both_file_dirs));
464  bool backup_completed = false;
465  try {
466  run("rm -rf " + temp_back_dir);
467  run("mkdir -p " + temp_back_dir);
468  for (const auto& dir : both_file_dirs) {
469  const auto dir_full_path = abs_path(global_file_mgr) + "/" + dir;
470  if (boost::filesystem::is_directory(dir_full_path)) {
471  run("mv " + dir_full_path + " " + temp_back_dir);
472  }
473  }
474  backup_completed = true;
475  // accord src data dirs to dst
477  cat_->getDataMgr().getGlobalFileMgr(), temp_data_dir, data_file_dirs, "table_");
478  // accord src dict dirs to dst
479  for (const auto& dit : dict_paths_map) {
480  if (!dit.first.empty() && !dit.second.empty()) {
481  const auto src_dict_path = temp_data_dir + "/" + dit.first;
482  const auto dst_dict_path = abs_path(global_file_mgr) + "/" + dit.second;
483  run("mv " + src_dict_path + " " + dst_dict_path);
484  }
485  }
486  // throw if sanity test forces a rollback
488  throw std::runtime_error("lol!");
489  }
490  } catch (...) {
491  // once backup is completed, whatever in abs_path(global_file_mgr) is the "src"
492  // dirs that are to be rolled back and discarded
493  if (backup_completed) {
494  run("rm -rf " + boost::algorithm::join(both_file_dirs, " "),
495  abs_path(global_file_mgr));
496  }
497  // complete rollback by recovering original "dst" table dirs from backup dir
498  boost::filesystem::path base_path(temp_back_dir);
499  boost::filesystem::directory_iterator end_it;
500  for (boost::filesystem::directory_iterator fit(base_path); fit != end_it; ++fit) {
501  run("mv " + fit->path().string() + " .", abs_path(global_file_mgr));
502  }
503  throw;
504  }
505  // set for reloading table from the restored/migrated files
506  const auto epoch = simple_file_cat(archive_path, table_epoch_filename, compression);
508  cat_->getCurrentDB().dbId, td->tableId, boost::lexical_cast<int>(epoch));
509 }
std::string get_table_schema(const std::string &archive_path, const std::string &table, const std::string &compression)
static ReadLock getReadLockForTable(const Catalog_Namespace::Catalog &cat, const std::string &table_name)
Definition: LockMgrImpl.h:164
static constexpr char const * table_schema_filename
std::string tableName
static TimeT::rep execution(F func, Args &&...args)
Definition: sample.cpp:29
std::string abs_path(const File_Namespace::GlobalFileMgr *global_file_mgr)
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:223
static WriteLock getWriteLockForTable(const Catalog_Namespace::Catalog &cat, const std::string &table_name)
Definition: LockMgrImpl.h:155
void adjust_altered_table_files(const std::string &temp_data_dir, const std::unordered_map< int, int > &column_ids_map)
std::string join(T const &container, std::string const &delim)
static constexpr char const * table_oldinfo_filename
std::vector< std::string > getTableDataDirectories(const TableDescriptor *td) const
Definition: Catalog.cpp:4372
std::string to_string(char const *&&v)
std::vector< std::string > split(std::string_view str, std::string_view delim, std::optional< size_t > maxsplit)
split apart a string into a vector of substrings
std::string getColumnDictDirectory(const ColumnDescriptor *cd) const
Definition: Catalog.cpp:4386
std::string get_quoted_string(const std::string &filename, char quote, char escape)
Quote a string while escaping any existing quotes in the string.
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:222
void rename_table_directories(const File_Namespace::GlobalFileMgr *global_file_mgr, const std::string &temp_data_dir, const std::vector< std::string > &target_paths, const std::string &name_prefix)
File_Namespace::GlobalFileMgr * getGlobalFileMgr() const
Definition: DataMgr.cpp:543
void validate_allowed_file_path(const std::string &file_path, const DataTransferType data_transfer_type, const bool allow_wildcards)
Definition: DdlUtils.cpp:634
void setTableEpoch(const int db_id, const int table_id, const int new_epoch)
Definition: Catalog.cpp:2855
std::vector< std::string > getTableDictDirectories(const TableDescriptor *td) const
Definition: Catalog.cpp:4402
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:1771
Data_Namespace::MemoryLevel persistenceLevel
static constexpr char const * table_epoch_filename
bool g_cluster
static bool run
std::string simple_file_cat(const std::string &archive_path, const std::string &file_name, const std::string &compression)
#define VLOG(n)
Definition: Logger.h:300
bool g_test_rollback_dump_restore
Catalog_Namespace::Catalog * cat_
Definition: TableArchiver.h:43

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void TableArchiver::restoreTable ( const Catalog_Namespace::SessionInfo session,
const std::string &  table_name,
const std::string &  archive_path,
const std::string &  compression 
)

Definition at line 513 of file TableArchiver.cpp.

References cat_, anonymous_namespace{TableArchiver.cpp}::get_table_schema(), Catalog_Namespace::Catalog::getMetadataForTable(), and restoreTable().

516  {
517  // replace table name and drop foreign dict references
518  const auto schema_str = get_table_schema(archive_path, table_name, compression);
519  Parser::parseDDL<Parser::CreateTableStmt>("table schema", schema_str)->execute(session);
520  try {
521  restoreTable(
522  session, cat_->getMetadataForTable(table_name), archive_path, compression);
523  } catch (...) {
524  Parser::parseDDL<Parser::DropTableStmt>("statement",
525  "DROP TABLE IF EXISTS " + table_name + ";")
526  ->execute(session);
527  throw;
528  }
529 }
std::string get_table_schema(const std::string &archive_path, const std::string &table, const std::string &compression)
void restoreTable(const Catalog_Namespace::SessionInfo &session, const TableDescriptor *td, const std::string &archive_path, const std::string &compression)
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
Catalog_Namespace::Catalog * cat_
Definition: TableArchiver.h:43

+ Here is the call graph for this function:

Member Data Documentation

Catalog_Namespace::Catalog* TableArchiver::cat_
private

Definition at line 43 of file TableArchiver.h.

Referenced by dumpTable(), and restoreTable().


The documentation for this class was generated from the following files: