summaryrefslogtreecommitdiff
path: root/src/buildtool/execution_engine/tree_operations/tree_operations_utils.cpp
blob: fb7d3bf0ee73ab4475bbd6e2becb5ad27fc51988 (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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// Copyright 2025 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.

#include "src/buildtool/execution_engine/tree_operations/tree_operations_utils.hpp"

#include <algorithm>
#include <cstddef>
#include <functional>
#include <iterator>
#include <memory>
#include <set>
#include <type_traits>  // for remove_reference
#include <unordered_set>
#include <vector>

#include "fmt/core.h"
#include "google/protobuf/repeated_ptr_field.h"
#include "nlohmann/json.hpp"
#include "src/buildtool/common/artifact_blob.hpp"
#include "src/buildtool/common/artifact_digest_factory.hpp"
#include "src/buildtool/common/bazel_types.hpp"
#include "src/buildtool/common/protocol_traits.hpp"
#include "src/buildtool/file_system/git_repo.hpp"
#include "src/buildtool/file_system/object_type.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/logging/logger.hpp"
#include "src/buildtool/multithreading/task_system.hpp"
#include "src/utils/cpp/hex_string.hpp"

auto TreeOperationsUtils::ParseBazelDirectory(
    std::string const& tree_data,
    HashFunction::Type hash_type) noexcept -> std::optional<TreeEntries> {
    bazel_re::Directory bazel_directory{};
    if (not bazel_directory.ParseFromString(tree_data)) {
        return std::nullopt;
    }

    // Collect all entries from bazel directory.
    TreeEntries tree_entries{};
    tree_entries.reserve(
        static_cast<size_t>(bazel_directory.files_size()) +
        static_cast<size_t>(bazel_directory.symlinks_size()) +
        static_cast<size_t>(bazel_directory.directories_size()));

    // Collect files.
    for (auto const& file : bazel_directory.files()) {
        auto digest =
            ArtifactDigestFactory::FromBazel(hash_type, file.digest());
        if (not digest) {
            return std::nullopt;
        }
        tree_entries.insert(
            {file.name(),
             TreeEntry{.info = Artifact::ObjectInfo{
                           .digest = *std::move(digest),
                           .type = file.is_executable() ? ObjectType::Executable
                                                        : ObjectType::File}}});
    }

    // Collect symlinks.
    HashFunction hash_function{hash_type};
    for (auto const& symlink : bazel_directory.symlinks()) {
        tree_entries.insert(
            {symlink.name(),
             TreeEntry{
                 .info =
                     Artifact::ObjectInfo{
                         .digest = ArtifactDigestFactory::HashDataAs<
                             ObjectType::File>(hash_function, symlink.target()),
                         .type = ObjectType::Symlink},
                 .symlink_target = symlink.target()}});
    }

    // Collect directories.
    for (auto const& dir : bazel_directory.directories()) {
        auto digest = ArtifactDigestFactory::FromBazel(hash_type, dir.digest());
        if (not digest) {
            return std::nullopt;
        }
        tree_entries.insert({dir.name(),
                             TreeEntry{.info = Artifact::ObjectInfo{
                                           .digest = *std::move(digest),
                                           .type = ObjectType::Tree}}});
    }
    return tree_entries;
}

auto TreeOperationsUtils::ParseGitTree(std::string const& tree_data,
                                       ArtifactDigest const& tree_digest,
                                       HashFunction::Type hash_type) noexcept
    -> std::optional<TreeEntries> {
    // For a tree-overlay computation, the actual target of a symbolic
    // link is not relevant. Symbolic links are just considered as
    // regular blobs.
    auto git_entries = GitRepo::ReadTreeData(
        tree_data,
        tree_digest.hash(),
        [](std::vector<ArtifactDigest> const&) { return true; },
        /*is_hex_id=*/true);
    if (not git_entries) {
        return std::nullopt;
    }

    // Collect all entries from git tree.
    TreeEntries tree_entries{};
    tree_entries.reserve(git_entries->size());
    for (auto const& [git_hash, entries] : *git_entries) {
        // Pick the first entry for that git hash to calculate the
        // object info once, since all follow-up entries will be the
        // same object, just with a different name.
        auto const& first_entry = entries.front();
        auto digest =
            ArtifactDigestFactory::Create(hash_type,
                                          ToHexString(git_hash),
                                          /*size=*/0,
                                          IsTreeObject(first_entry.type));
        if (not digest) {
            return std::nullopt;
        }
        // Pick up all names for that git object and create a tree entry
        // for each of them.
        for (auto const& entry : entries) {
            tree_entries.insert(
                {entry.name,
                 TreeEntry{.info = Artifact::ObjectInfo{
                               .digest = *digest, .type = first_entry.type}}});
        }
    }
    return tree_entries;
}

auto TreeOperationsUtils::ReadTree(
    IExecutionApi const& api,
    Artifact::ObjectInfo const& tree_info) noexcept
    -> expected<TreeEntries, std::string> {
    // Fetch tree data.
    auto tree_data = api.RetrieveToMemory(tree_info);
    if (not tree_data) {
        return unexpected{
            fmt::format("Failed to fetch tree: {}", tree_info.ToString())};
    }

    // Parse tree data.
    auto tree_entries =
        ProtocolTraits::IsNative(api.GetHashType())
            ? ParseGitTree(*tree_data, tree_info.digest, api.GetHashType())
            : ParseBazelDirectory(*tree_data, api.GetHashType());
    if (not tree_entries) {
        return unexpected{
            fmt::format("Failed to parse tree: {}", tree_info.ToString())};
    }
    return *tree_entries;
}

auto TreeOperationsUtils::SerializeBazelDirectory(
    TreeEntries const& tree_entries) noexcept -> std::optional<std::string> {
    // Sort tree entry names, so we can process them in the correct order.
    auto sorted = std::set<std::string>{};
    std::transform(tree_entries.begin(),
                   tree_entries.end(),
                   std::inserter(sorted, sorted.end()),
                   [](auto const& name_entry) { return name_entry.first; });
    // Convert tree entries to bazel directory.
    bazel_re::Directory bazel_directory{};
    for (auto const& name : sorted) {
        auto const& entry = tree_entries.at(name);
        switch (entry.info.type) {
            case ObjectType::File:
            case ObjectType::Executable: {
                auto* file = bazel_directory.add_files();
                file->set_name(name);
                *file->mutable_digest() =
                    ArtifactDigestFactory::ToBazel(entry.info.digest);
                file->set_is_executable(entry.info.type ==
                                        ObjectType::Executable);
                break;
            }
            case ObjectType::Symlink: {
                auto* symlink = bazel_directory.add_symlinks();
                symlink->set_name(name);
                symlink->set_target(*entry.symlink_target);
                break;
            }
            case ObjectType::Tree: {
                auto* dir = bazel_directory.add_directories();
                dir->set_name(name);
                *dir->mutable_digest() =
                    ArtifactDigestFactory::ToBazel(entry.info.digest);
                break;
            }
            default: {
                return std::nullopt;
            }
        }
    }

    // Serialize bazel directory.
    return bazel_directory.SerializeAsString();
}

auto TreeOperationsUtils::SerializeGitTree(
    TreeEntries const& tree_entries) noexcept -> std::optional<std::string> {
    // Convert tree entries to git entries.
    GitRepo::tree_entries_t git_entries{};
    git_entries.reserve(tree_entries.size());
    for (auto const& [name, entry] : tree_entries) {
        auto git_hash = FromHexString(entry.info.digest.hash());
        if (not git_hash) {
            return std::nullopt;
        }
        auto it = git_entries.find(*git_hash);
        if (it == git_entries.end()) {
            if (auto res = git_entries.insert(
                    {*git_hash, std::vector<GitRepo::TreeEntry>{}});
                res.second) {
                it = std::move(res).first;
            }
            else {
                return std::nullopt;
            }
        }
        it->second.emplace_back(name, entry.info.type);
    }

    // Serialize git entries.
    auto git_tree = GitRepo::CreateShallowTree(git_entries);
    if (not git_tree) {
        return std::nullopt;
    }
    return git_tree->second;
}

auto TreeOperationsUtils::WriteTree(IExecutionApi const& api,
                                    TreeEntries const& tree_entries) noexcept
    -> expected<Artifact::ObjectInfo, std::string> {
    // Serialize tree entries.
    auto tree_data = ProtocolTraits::IsNative(api.GetHashType())
                         ? SerializeGitTree(tree_entries)
                         : SerializeBazelDirectory(tree_entries);
    if (not tree_data) {
        return unexpected{fmt::format("Failed to serialize tree entries")};
    }

    // Write tree data.
    auto tree_blob = ArtifactBlob::FromMemory(HashFunction{api.GetHashType()},
                                              ObjectType::Tree,
                                              *std::move(tree_data));
    if (not tree_blob) {
        return unexpected{fmt::format("Failed to create tree blob")};
    }
    if (api.Upload(std::unordered_set{*tree_blob})) {
        return Artifact::ObjectInfo{.digest = tree_blob->GetDigest(),
                                    .type = ObjectType::Tree};
    }
    return unexpected{fmt::format("Failed to upload tree blob")};
}

auto TreeOperationsUtils::CreateTreeOverlayMap(IExecutionApi const& api,
                                               bool disjoint) noexcept
    -> AsyncMapConsumer<TreePair, Artifact::ObjectInfo> {
    auto value_creator = [&api, disjoint](auto /*unused*/,
                                          auto const& setter,
                                          auto const& logger,
                                          auto const& subcaller,
                                          auto const& key) {
        auto const& base_tree_info = key.trees.first;
        auto const& other_tree_info = key.trees.second;

        Logger::Log(LogLevel::Trace,
                    "Compute tree overlay:\n  - {}\n  - {}",
                    base_tree_info.ToString(),
                    other_tree_info.ToString());

        // Wrap logger for this tree-overlay computation.
        auto new_logger = std::make_shared<AsyncMapConsumerLogger>(
            [logger, base_tree_info, other_tree_info](auto const& msg,
                                                      auto fatal) {
                (*logger)(fmt::format("While merging the trees:\n  - {}\n  "
                                      "- {}\n{}",
                                      base_tree_info.ToString(),
                                      other_tree_info.ToString(),
                                      msg),
                          fatal);
            });

        // Ensure that both objects are actually trees.
        if (not IsTreeObject(base_tree_info.type) or
            not IsTreeObject(other_tree_info.type)) {
            (*new_logger)(fmt::format("Both objects have to be trees."),
                          /*fatal=*/true);
            return;
        }

        // Early return if both trees are the same.
        if (base_tree_info == other_tree_info) {
            (*setter)(Artifact::ObjectInfo{base_tree_info});
            return;
        }

        // Read base tree.
        auto base_tree = ReadTree(api, base_tree_info);
        if (not base_tree) {
            (*new_logger)(base_tree.error(), /*fatal=*/true);
            return;
        }

        // Read other tree.
        auto other_tree = ReadTree(api, other_tree_info);
        if (not other_tree) {
            (*new_logger)(other_tree.error(), /*fatal=*/true);
            return;
        }

        // Compute tree overlay. If two trees conflict, collect them and
        // process them in the subcaller.
        TreeEntries overlay_tree{*other_tree};  // Make a copy of other tree.
        std::vector<TreePair> keys{};
        std::vector<std::string> base_names{};
        auto min_size = std::min(base_tree->size(), other_tree->size());
        keys.reserve(min_size);
        base_names.reserve(min_size);
        for (auto& [base_name, base_entry] : *base_tree) {
            auto it = overlay_tree.find(base_name);
            if (it == overlay_tree.end()) {
                // No naming conflict detected, add entry to the other
                // tree.
                overlay_tree[std::move(base_name)] = std::move(base_entry);
                continue;
            }

            if (it->second.info == base_entry.info) {
                // Naming conflict detected, but names point to the same
                // object, no conflict.
                continue;
            }

            // Naming conflict detected and names point to different
            // objects.
            if (IsTreeObject(base_entry.info.type) and
                IsTreeObject(it->second.info.type)) {
                // If both objects are trees, compute tree overlay in
                // the subcaller.
                keys.emplace_back(std::make_pair(std::move(base_entry.info),
                                                 std::move(it->second.info)));
                base_names.emplace_back(std::move(base_name));
                continue;
            }

            // If both objects are not trees, actual conflict detected.
            if (disjoint) {
                (*new_logger)(fmt::format("Naming conflict detected at path "
                                          "{}:\n  - {}\n  - {}",
                                          nlohmann::json(base_name).dump(),
                                          base_entry.info.ToString(),
                                          it->second.info.ToString()),
                              /*fatal=*/true);
                return;
            }

            // Ignore conflict, keep entry from other tree.
        }

        (*subcaller)(
            keys,
            [setter,
             new_logger,
             &api,
             base_names = std::move(base_names),
             partial_overlay_tree =
                 std::move(overlay_tree)](auto const& values) {
                // Insert computed tree overlays into tree-overlay
                // entries.
                TreeEntries overlay_tree{partial_overlay_tree};
                for (size_t i = 0; i < values.size(); ++i) {
                    // Create copy of the value.
                    overlay_tree[base_names[i]] =
                        TreeEntry{.info = *(values[i])};
                }

                // Write tree overlay.
                auto overlay_tree_info = WriteTree(api, overlay_tree);
                if (not overlay_tree_info) {
                    (*new_logger)(overlay_tree_info.error(), /*fatal=*/true);
                    return;
                }

                Logger::Log(LogLevel::Trace,
                            "Tree-overlay result: {}",
                            overlay_tree_info->ToString());

                (*setter)(*std::move(overlay_tree_info));
            },
            new_logger);
    };

    return AsyncMapConsumer<TreePair, Artifact::ObjectInfo>{value_creator};
}

auto TreeOperationsUtils::ComputeTreeOverlay(
    IExecutionApi const& api,
    Artifact::ObjectInfo const& base_tree_info,
    Artifact::ObjectInfo const& other_tree_info,
    bool disjoint) noexcept -> expected<Artifact::ObjectInfo, std::string> {

    auto tree_overlay_map = CreateTreeOverlayMap(api, disjoint);
    Artifact::ObjectInfo result{};
    std::string failed_msg{};
    bool failed{false};
    {
        TaskSystem ts{1};
        tree_overlay_map.ConsumeAfterKeysReady(
            &ts,
            {TreePair{std::make_pair(base_tree_info, other_tree_info)}},
            [&result](auto const& values) { result = *values[0]; },
            [&failed_msg, &failed](auto const& msg, auto fatal) {
                failed_msg = msg;
                failed = fatal;
            });
    }
    if (failed) {
        return unexpected{failed_msg};
    }
    return result;
}