summaryrefslogtreecommitdiff
path: root/src/buildtool/execution_api/local/local_cas.hpp
blob: afda71ed983eabc0353fb65b3c7c2cee3110e5a8 (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef INCLUDED_SRC_BUILDTOOL_EXECUTION_API_LOCAL_LOCAL_CAS_HPP
#define INCLUDED_SRC_BUILDTOOL_EXECUTION_API_LOCAL_LOCAL_CAS_HPP

#include <sstream>
#include <thread>

#include "src/buildtool/common/artifact.hpp"
#include "src/buildtool/execution_api/bazel_msg/bazel_blob.hpp"
#include "src/buildtool/execution_api/common/execution_common.hpp"
#include "src/buildtool/execution_api/local/config.hpp"
#include "src/buildtool/file_system/file_storage.hpp"
#include "src/buildtool/file_system/file_system_manager.hpp"
#include "src/buildtool/logging/logger.hpp"
#ifndef BOOTSTRAP_BUILD_TOOL
#include "src/buildtool/execution_api/local/garbage_collector.hpp"
#endif

template <ObjectType kType = ObjectType::File>
class LocalCAS {
  public:
    LocalCAS() noexcept = default;

    LocalCAS(LocalCAS const&) = delete;
    LocalCAS(LocalCAS&&) = delete;
    auto operator=(LocalCAS const&) -> LocalCAS& = delete;
    auto operator=(LocalCAS&&) -> LocalCAS& = delete;
    ~LocalCAS() noexcept = default;

    [[nodiscard]] static auto Instance() noexcept -> LocalCAS<kType>& {
        static auto instance = LocalCAS<kType>{};
        return instance;
    }

    auto Reset() noexcept -> void {
        file_store_ = FileStorage<kStorageType,
                                  StoreMode::FirstWins,
                                  /*kSetEpochTime=*/true>{
            LocalExecutionConfig::CASDir<kType>(0)};
    }

    [[nodiscard]] auto StoreBlobFromBytes(std::string const& bytes)
        const noexcept -> std::optional<bazel_re::Digest> {
        return StoreBlob(bytes, /*is_owner=*/true);
    }

    [[nodiscard]] auto StoreBlobFromFile(std::filesystem::path const& file_path,
                                         bool is_owner = false) const noexcept
        -> std::optional<bazel_re::Digest> {
        return StoreBlob(file_path, is_owner);
    }

    [[nodiscard]] auto BlobPath(bazel_re::Digest const& digest) const noexcept
        -> std::optional<std::filesystem::path> {
        auto id = NativeSupport::Unprefix(digest.hash());
        auto blob_path = file_store_.GetPath(id);
#ifndef BOOTSTRAP_BUILD_TOOL
        // Try to find blob in CAS generations and uplink if required.
        auto found = FindAndUplinkBlob(id);
#else
        auto found = FileSystemManager::IsFile(blob_path);
#endif
        if (not found) {
            logger_.Emit(LogLevel::Debug, "Blob not found {}", id);
            return std::nullopt;
        }
        return blob_path;
    }

  private:
    // For `Tree` the underlying storage type is non-executable file.
    static constexpr auto kStorageType =
        kType == ObjectType::Tree ? ObjectType::File : kType;

    Logger logger_{std::string{"LocalCAS"} + ToChar(kType)};

    FileStorage<kStorageType, StoreMode::FirstWins, /*kSetEpochTime=*/true>
        file_store_{LocalExecutionConfig::CASDir<kType>(0)};

    [[nodiscard]] static auto CreateDigest(std::string const& bytes) noexcept
        -> std::optional<bazel_re::Digest> {
        return ArtifactDigest::Create<kType>(bytes);
    }

    [[nodiscard]] static auto CreateDigest(
        std::filesystem::path const& file_path) noexcept
        -> std::optional<bazel_re::Digest> {
        auto const bytes = FileSystemManager::ReadFile(file_path);
        if (bytes.has_value()) {
            return ArtifactDigest::Create<kType>(*bytes);
        }
        return std::nullopt;
    }

    /// \brief Store blob from bytes to storage.
    [[nodiscard]] auto StoreBlobData(std::string const& blob_id,
                                     std::string const& bytes,
                                     bool /*unused*/) const noexcept -> bool {
        return file_store_.AddFromBytes(blob_id, bytes);
    }

    /// \brief Store blob from file path to storage.
    [[nodiscard]] auto StoreBlobData(std::string const& blob_id,
                                     std::filesystem::path const& file_path,
                                     bool is_owner) const noexcept -> bool {
        return file_store_.AddFromFile(blob_id, file_path, is_owner);
    }

    /// \brief Store blob from unspecified data to storage.
    template <class T>
    [[nodiscard]] auto StoreBlob(T const& data, bool is_owner) const noexcept
        -> std::optional<bazel_re::Digest> {
        auto digest = CreateDigest(data);
        if (digest) {
            auto id = NativeSupport::Unprefix(digest->hash());
#ifndef BOOTSTRAP_BUILD_TOOL
            if (FindAndUplinkBlob(id)) {
                return digest;
            }
#endif
            if (StoreBlobData(id, data, is_owner)) {
                return digest;
            }
            logger_.Emit(LogLevel::Debug, "Failed to store blob {}.", id);
        }
        logger_.Emit(LogLevel::Debug, "Failed to create digest.");
        return std::nullopt;
    }

#ifndef BOOTSTRAP_BUILD_TOOL
    [[nodiscard]] auto FindAndUplinkBlob(std::string const& id) const noexcept
        -> bool {
        if (Compatibility::IsCompatible()) {
            return GarbageCollector::FindAndUplinkBlob(
                id, kType == ObjectType::Executable);
        }
        if (kType == ObjectType::Tree) {
            return GarbageCollector::FindAndUplinkTree(id);
        }
        return GarbageCollector::FindAndUplinkBlob(
            id, kType == ObjectType::Executable);
    }
#endif
};

#endif  // INCLUDED_SRC_BUILDTOOL_EXECUTION_API_LOCAL_LOCAL_CAS_HPP