aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/providers/common/udf_resolve/yql_files_box.cpp
blob: 0220ba8f6c96763b5bf89f5d8136b73edb89feb8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "yql_files_box.h"

#include <yql/essentials/core/file_storage/storage.h>
#include <yql/essentials/utils/log/log.h>

#include <util/system/fs.h>
#include <util/system/error.h>
#include <util/system/sysstat.h>
#include <util/folder/dirut.h>

namespace NYql {
namespace NCommon {

TFilesBox::TFilesBox(TFsPath dir, TRandGuid randGuid)
    : Dir(std::move(dir))
    , RandGuid(std::move(randGuid))
{
}

TFilesBox::~TFilesBox() {
    try {
        Destroy();
    } catch (...) {
        YQL_LOG(ERROR) << "Error occurred in files box destroy: " << CurrentExceptionMessage();
    }
}

TString TFilesBox::MakeLinkFrom(const TString& source, const TString& filename) {
    if (!filename) {
        if (auto* existingPath = Mapping.FindPtr(source)) {
            return *existingPath;
        }
    }

    TFsPath sourcePath(source);
    TString sourceAbsolutePath = sourcePath.IsAbsolute() ? source : (TFsPath::Cwd() / sourcePath).GetPath();
    TString path;
    if (filename) {
        path = Dir / filename;
        if (!NFs::SymLink(sourceAbsolutePath, path)) {
            ythrow TSystemError() << "Failed to create symlink for file " << sourceAbsolutePath.Quote() << " to file " << path.Quote();
        }
    } else {
        while (true) {
            path = Dir / RandGuid.GenGuid();
            if (NFs::SymLink(sourceAbsolutePath, path)) {
                break;
            } else if (LastSystemError() != EEXIST) {
                ythrow TSystemError() << "Failed to create symlink for file " << sourceAbsolutePath.Quote() << " to file " << path.Quote();
            }
        }
        Mapping.emplace(source, path);
    }
    return path;
}

TString TFilesBox::GetDir() const {
    return Dir;
}

void TFilesBox::Destroy() {
    Mapping.clear();
    Dir.ForceDelete();
}

THolder<TFilesBox> CreateFilesBox(const TFsPath& baseDir) {
    TRandGuid randGuid;
    TFsPath path = baseDir / randGuid.GenGuid();

    while (true) {
        if (!path.Exists()) {
            int r = Mkdir(path.c_str(), MODE0711);
            if (r == 0) {
                break;
            }
            if (LastSystemError() != EEXIST) {
                ythrow TIoSystemError() << "could not create directory " << path;
            }
        }
        path = baseDir / randGuid.GenGuid();
    }

    return MakeHolder<TFilesBox>(std::move(path), std::move(randGuid));
}

}
}