yql_files_box.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "yql_files_box.h"
  2. #include <yql/essentials/core/file_storage/storage.h>
  3. #include <yql/essentials/utils/log/log.h>
  4. #include <util/system/fs.h>
  5. #include <util/system/error.h>
  6. #include <util/system/sysstat.h>
  7. #include <util/folder/dirut.h>
  8. namespace NYql {
  9. namespace NCommon {
  10. TFilesBox::TFilesBox(TFsPath dir, TRandGuid randGuid)
  11. : Dir(std::move(dir))
  12. , RandGuid(std::move(randGuid))
  13. {
  14. }
  15. TFilesBox::~TFilesBox() {
  16. try {
  17. Destroy();
  18. } catch (...) {
  19. YQL_LOG(ERROR) << "Error occurred in files box destroy: " << CurrentExceptionMessage();
  20. }
  21. }
  22. TString TFilesBox::MakeLinkFrom(const TString& source, const TString& filename) {
  23. if (!filename) {
  24. if (auto* existingPath = Mapping.FindPtr(source)) {
  25. return *existingPath;
  26. }
  27. }
  28. TFsPath sourcePath(source);
  29. TString sourceAbsolutePath = sourcePath.IsAbsolute() ? source : (TFsPath::Cwd() / sourcePath).GetPath();
  30. TString path;
  31. if (filename) {
  32. path = Dir / filename;
  33. if (!NFs::SymLink(sourceAbsolutePath, path)) {
  34. ythrow TSystemError() << "Failed to create symlink for file " << sourceAbsolutePath.Quote() << " to file " << path.Quote();
  35. }
  36. } else {
  37. while (true) {
  38. path = Dir / RandGuid.GenGuid();
  39. if (NFs::SymLink(sourceAbsolutePath, path)) {
  40. break;
  41. } else if (LastSystemError() != EEXIST) {
  42. ythrow TSystemError() << "Failed to create symlink for file " << sourceAbsolutePath.Quote() << " to file " << path.Quote();
  43. }
  44. }
  45. Mapping.emplace(source, path);
  46. }
  47. return path;
  48. }
  49. TString TFilesBox::GetDir() const {
  50. return Dir;
  51. }
  52. void TFilesBox::Destroy() {
  53. Mapping.clear();
  54. Dir.ForceDelete();
  55. }
  56. THolder<TFilesBox> CreateFilesBox(const TFsPath& baseDir) {
  57. TRandGuid randGuid;
  58. TFsPath path = baseDir / randGuid.GenGuid();
  59. while (true) {
  60. if (!path.Exists()) {
  61. int r = Mkdir(path.c_str(), MODE0711);
  62. if (r == 0) {
  63. break;
  64. }
  65. if (LastSystemError() != EEXIST) {
  66. ythrow TIoSystemError() << "could not create directory " << path;
  67. }
  68. }
  69. path = baseDir / randGuid.GenGuid();
  70. }
  71. return MakeHolder<TFilesBox>(std::move(path), std::move(randGuid));
  72. }
  73. }
  74. }