summaryrefslogtreecommitdiff
path: root/src/buildtool/execution_api/local/garbage_collector.cpp
blob: a0b68811d922502e9497f4a29e2cdda8a04c0ebb (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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// 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.

#include "src/buildtool/execution_api/local/garbage_collector.hpp"

#include <vector>

#include <nlohmann/json.hpp>

#include "src/buildtool/build_engine/target_map/target_cache_entry.hpp"
#include "src/buildtool/common/artifact.hpp"
#include "src/buildtool/common/bazel_types.hpp"
#include "src/buildtool/compatibility/compatibility.hpp"
#include "src/buildtool/compatibility/native_support.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/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/utils/cpp/hex_string.hpp"

auto GarbageCollector::FindAndUplinkBlob(std::string const& id,
                                         bool is_executable) noexcept -> bool {
    // Try to find blob in all generations.
    for (int i = 0; i < LocalExecutionConfig::NumGenerations(); i++) {
        if (UplinkBlob(i, id, is_executable)) {
            return true;
        }
    }
    return false;
}

auto GarbageCollector::FindAndUplinkTree(std::string const& id) noexcept
    -> bool {
    // Try to find tree in all generations.
    for (int i = 0; i < LocalExecutionConfig::NumGenerations(); i++) {
        if (UplinkTree(i, id)) {
            return true;
        }
    }
    return false;
}

auto GarbageCollector::FindAndUplinkActionCacheEntry(
    std::string const& id) noexcept -> bool {
    // Try to find action-cache entry in all generations.
    for (int i = 0; i < LocalExecutionConfig::NumGenerations(); i++) {
        if (UplinkActionCacheEntry(i, id)) {
            return true;
        }
    }
    return false;
}

auto GarbageCollector::FindAndUplinkTargetCacheEntry(
    std::string const& id) noexcept -> bool {
    // Try to find target-cache entry in all generations.
    for (int i = 0; i < LocalExecutionConfig::NumGenerations(); i++) {
        if (UplinkTargetCacheEntry(i, id)) {
            return true;
        }
    }
    return false;
}

auto GarbageCollector::SharedLock() noexcept -> std::optional<LockFile> {
    return LockFile::Acquire(LockFilePath(), /*is_shared=*/true);
}

auto GarbageCollector::ExclusiveLock() noexcept -> std::optional<LockFile> {
    return LockFile::Acquire(LockFilePath(), /*is_shared=*/false);
}

auto GarbageCollector::LockFilePath() noexcept -> std::filesystem::path {
    return LocalExecutionConfig::CacheRoot() / "gc.lock";
}

auto GarbageCollector::TriggerGarbageCollection() noexcept -> bool {
    auto pid = CreateProcessUniqueId();
    if (not pid) {
        return false;
    }
    auto remove_me = std::string{"remove-me-"} + *pid;
    auto remove_me_dir = LocalExecutionConfig::CacheRoot() / remove_me;
    if (FileSystemManager::IsDirectory(remove_me_dir)) {
        if (not FileSystemManager::RemoveDirectory(remove_me_dir,
                                                   /*recursively=*/true)) {
            Logger::Log(LogLevel::Error,
                        "Failed to remove directory {}",
                        remove_me_dir.string());
            return false;
        }
    }
    {  // Create scope for critical renaming section protected by advisory lock.
        auto lock = ExclusiveLock();
        if (not lock) {
            Logger::Log(LogLevel::Error,
                        "Failed to exclusively lock the local build root");
            return false;
        }
        for (int i = LocalExecutionConfig::NumGenerations() - 1; i >= 0; i--) {
            auto cache_root = LocalExecutionConfig::CacheRoot(i);
            if (FileSystemManager::IsDirectory(cache_root)) {
                auto new_cache_root =
                    (i == LocalExecutionConfig::NumGenerations() - 1)
                        ? remove_me_dir
                        : LocalExecutionConfig::CacheRoot(i + 1);
                if (not FileSystemManager::Rename(cache_root, new_cache_root)) {
                    Logger::Log(LogLevel::Error,
                                "Failed to rename {} to {}.",
                                cache_root.string(),
                                new_cache_root.string());
                    return false;
                }
            }
        }
    }
    if (FileSystemManager::IsDirectory(remove_me_dir)) {
        if (not FileSystemManager::RemoveDirectory(remove_me_dir,
                                                   /*recursively=*/true)) {
            Logger::Log(LogLevel::Warning,
                        "Failed to remove directory {}",
                        remove_me_dir.string());
            return false;
        }
    }
    return true;
}

auto GarbageCollector::UplinkBlob(int index,
                                  std::string const& id,
                                  bool is_executable) noexcept -> bool {
    // Determine blob path of given generation.
    auto root =
        is_executable
            ? LocalExecutionConfig::CASDir<ObjectType::Executable>(index)
            : LocalExecutionConfig::CASDir<ObjectType::File>(index);
    auto blob_path = GetStoragePath(root, id);
    if (not FileSystemManager::IsFile(blob_path)) {
        return false;
    }

    // Determine blob path in latest generation.
    auto root_latest =
        is_executable ? LocalExecutionConfig::CASDir<ObjectType::Executable>(0)
                      : LocalExecutionConfig::CASDir<ObjectType::File>(0);
    auto blob_path_latest = GetStoragePath(root_latest, id);
    if (not FileSystemManager::IsFile(blob_path_latest)) {
        // Uplink blob from older generation to the latest generation.
        if (not FileSystemManager::CreateDirectory(
                blob_path_latest.parent_path())) {
            return false;
        }
        if (not FileSystemManager::CreateFileHardlink(
                blob_path,
                blob_path_latest,
                /*log_failure_at=*/LogLevel::Debug) and
            not FileSystemManager::IsFile(blob_path_latest)) {
            return false;
        }
    }
    return true;
}

// NOLINTNEXTLINE(misc-no-recursion)
auto GarbageCollector::UplinkTree(int index, std::string const& id) noexcept
    -> bool {
    // Determine tree path of given generation.
    auto root = LocalExecutionConfig::CASDir<ObjectType::Tree>(index);
    auto tree_path = GetStoragePath(root, id);
    if (not FileSystemManager::IsFile(tree_path)) {
        return false;
    }

    // Determine tree path in latest generation.
    auto root_latest = LocalExecutionConfig::CASDir<ObjectType::Tree>(0);
    auto tree_path_latest = GetStoragePath(root_latest, id);
    if (not FileSystemManager::IsFile(tree_path_latest)) {
        // Determine tree entries.
        auto content = FileSystemManager::ReadFile(tree_path);
        auto tree_entries = GitRepo::ReadTreeData(*content,
                                                  id,
                                                  /*is_hex_id=*/true);
        if (not tree_entries) {
            return false;
        }

        // Uplink tree entries.
        for (auto const& [raw_id, entry_vector] : *tree_entries) {
            // Process only first entry from 'entry_vector' since all entries
            // represent the same blob, just with different names.
            auto entry = entry_vector.front();
            auto hash = ToHexString(raw_id);
            if (entry.type == ObjectType::Tree) {
                if (not UplinkTree(index, hash)) {
                    return false;
                }
            }
            else {
                if (not UplinkBlob(
                        index, hash, entry.type == ObjectType::Executable)) {
                    return false;
                }
            }
        }

        // Uplink tree from older generation to the latest generation.
        if (not FileSystemManager::CreateDirectory(
                tree_path_latest.parent_path())) {
            return false;
        }
        if (not FileSystemManager::CreateFileHardlink(
                tree_path,
                tree_path_latest,
                /*log_failure_at=*/LogLevel::Debug) and
            not FileSystemManager::IsFile(tree_path_latest)) {
            return false;
        }
    }
    return true;
}

// NOLINTNEXTLINE(misc-no-recursion)
auto GarbageCollector::UplinkBazelDirectory(int index,
                                            std::string const& id) noexcept
    -> bool {
    // Determine bazel directory path of given generation.
    auto root = LocalExecutionConfig::CASDir<ObjectType::File>(index);
    auto dir_path = GetStoragePath(root, id);
    if (not FileSystemManager::IsFile(dir_path)) {
        return false;
    }

    // Determine bazel directory entries.
    auto content = FileSystemManager::ReadFile(dir_path);
    bazel_re::Directory dir{};
    if (not dir.ParseFromString(*content)) {
        return false;
    }

    // Uplink bazel directory entries.
    for (auto const& file : dir.files()) {
        if (not UplinkBlob(index,
                           NativeSupport::Unprefix(file.digest().hash()),
                           file.is_executable())) {
            return false;
        }
    }
    for (auto const& directory : dir.directories()) {
        if (not UplinkBazelDirectory(
                index, NativeSupport::Unprefix(directory.digest().hash()))) {
            return false;
        }
    }

    // Determine bazel directory path in latest generation.
    auto root_latest = LocalExecutionConfig::CASDir<ObjectType::File>(0);
    auto dir_path_latest = GetStoragePath(root_latest, id);

    // Uplink bazel directory from older generation to the latest generation.
    if (not FileSystemManager::IsFile(dir_path_latest)) {
        if (not FileSystemManager::CreateDirectory(
                dir_path_latest.parent_path())) {
            return false;
        }
        if (not FileSystemManager::CreateFileHardlink(
                dir_path,
                dir_path_latest,
                /*log_failure_at=*/LogLevel::Debug) and
            not FileSystemManager::IsFile(dir_path_latest)) {
            return false;
        }
    }
    return true;
}

auto GarbageCollector::UplinkActionCacheEntry(int index,
                                              std::string const& id) noexcept
    -> bool {
    // Determine action-cache entry path of given generation.
    auto root = LocalExecutionConfig::ActionCacheDir(index);
    auto entry_path = GetStoragePath(root, id);
    if (not FileSystemManager::IsFile(entry_path)) {
        return false;
    }

    // Determine action-cache entry location.
    auto content = FileSystemManager::ReadFile(entry_path, ObjectType::File);
    bazel_re::Digest digest{};
    if (not digest.ParseFromString(*content)) {
        return false;
    }

    // Uplink action-cache entry blob.
    if (not UplinkActionCacheEntryBlob(
            index, NativeSupport::Unprefix(digest.hash()))) {
        return false;
    }

    // Determine action-cache entry path in latest generation.
    auto root_latest = LocalExecutionConfig::ActionCacheDir(0);
    auto entry_path_latest = GetStoragePath(root_latest, id);

    // Uplink action-cache entry from older generation to the latest
    // generation.
    if (not FileSystemManager::IsFile(entry_path_latest)) {
        if (not FileSystemManager::CreateDirectory(
                entry_path_latest.parent_path())) {
            return false;
        }
        if (not FileSystemManager::CreateFileHardlink(
                entry_path,
                entry_path_latest,
                /*log_failure_at=*/LogLevel::Debug) and
            not FileSystemManager::IsFile(entry_path_latest)) {
            return false;
        }
    }
    return true;
}

auto GarbageCollector::UplinkActionCacheEntryBlob(
    int index,
    std::string const& id) noexcept -> bool {

    // Determine action-cache entry blob path of given generation.
    auto root = LocalExecutionConfig::CASDir<ObjectType::File>(index);
    auto entry_path = GetStoragePath(root, id);
    if (not FileSystemManager::IsFile(entry_path)) {
        return false;
    }

    // Determine artifacts referenced by action-cache entry.
    auto content = FileSystemManager::ReadFile(entry_path);
    bazel_re::ActionResult result{};
    if (not result.ParseFromString(*content)) {
        return false;
    }

    // Uplink referenced artifacts.
    for (auto const& file : result.output_files()) {
        if (not UplinkBlob(index,
                           NativeSupport::Unprefix(file.digest().hash()),
                           file.is_executable())) {
            return false;
        }
    }
    for (auto const& directory : result.output_directories()) {
        if (Compatibility::IsCompatible()) {
            if (not UplinkBazelDirectory(
                    index,
                    NativeSupport::Unprefix(directory.tree_digest().hash()))) {
                return false;
            }
        }
        else {
            if (not UplinkTree(
                    index,
                    NativeSupport::Unprefix(directory.tree_digest().hash()))) {
                return false;
            }
        }
    }

    // Determine action-cache entry blob path in latest generation.
    auto root_latest = LocalExecutionConfig::CASDir<ObjectType::File>(0);
    auto entry_path_latest = GetStoragePath(root_latest, id);

    // Uplink action-cache entry blob from older generation to the latest
    // generation.
    if (not FileSystemManager::IsFile(entry_path_latest)) {
        if (not FileSystemManager::CreateDirectory(
                entry_path_latest.parent_path())) {
            return false;
        }
        if (not FileSystemManager::CreateFileHardlink(
                entry_path,
                entry_path_latest,
                /*log_failure_at=*/LogLevel::Debug) and
            not FileSystemManager::IsFile(entry_path_latest)) {
            return false;
        }
    }
    return true;
}

auto GarbageCollector::UplinkTargetCacheEntry(int index,
                                              std::string const& id) noexcept
    -> bool {

    // Determine target-cache entry path of given generation.
    auto root = LocalExecutionConfig::TargetCacheDir(index);
    auto entry_path = GetStoragePath(root, id);
    if (not FileSystemManager::IsFile(entry_path)) {
        return false;
    }

    // Determine target-cache entry location.
    auto content = FileSystemManager::ReadFile(entry_path);
    auto info = Artifact::ObjectInfo::FromString(*content);
    if (not info) {
        return false;
    }

    // Uplink target-cache entry blob.
    if (not UplinkTargetCacheEntryBlob(index, info->digest.hash())) {
        return false;
    }

    // Determine target-cache entry path in latest generation.
    auto root_latest = LocalExecutionConfig::TargetCacheDir(0);
    auto entry_path_latest = GetStoragePath(root_latest, id);

    // Uplink target-cache entry from older generation to the latest
    // generation.
    if (not FileSystemManager::IsFile(entry_path_latest)) {
        if (not FileSystemManager::CreateDirectory(
                entry_path_latest.parent_path())) {
            return false;
        }
        if (not FileSystemManager::CreateFileHardlink(
                entry_path,
                entry_path_latest,
                /*log_failure_at=*/LogLevel::Debug) and
            not FileSystemManager::IsFile(entry_path_latest)) {
            return false;
        }
    }
    return true;
}

auto GarbageCollector::UplinkTargetCacheEntryBlob(
    int index,
    std::string const& id) noexcept -> bool {

    // Determine target-cache entry blob path of given generation.
    auto root = LocalExecutionConfig::CASDir<ObjectType::File>(index);
    auto entry_path = GetStoragePath(root, id);
    if (not FileSystemManager::IsFile(entry_path)) {
        return false;
    }

    // Determine artifacts referenced by target-cache entry.
    auto content = FileSystemManager::ReadFile(entry_path);
    nlohmann::json json_desc{};
    try {
        json_desc = nlohmann::json::parse(*content);
    } catch (std::exception const& ex) {
        return false;
    }
    auto entry = TargetCacheEntry::FromJson(json_desc);
    std::vector<Artifact::ObjectInfo> artifacts_info;
    if (not entry.ToArtifacts(&artifacts_info)) {
        return false;
    }

    // Uplink referenced artifacts.
    for (auto const& info : artifacts_info) {
        auto hash = info.digest.hash();
        if (info.type == ObjectType::Tree) {
            if (Compatibility::IsCompatible()) {
                if (not UplinkBazelDirectory(index, hash)) {
                    return false;
                }
            }
            else {
                if (not UplinkTree(index, hash)) {
                    return false;
                }
            }
        }
        else {
            if (not UplinkBlob(
                    index, hash, info.type == ObjectType::Executable)) {
                return false;
            }
        }
    }

    // Determine target-cache entry blob path in latest generation.
    auto root_latest = LocalExecutionConfig::CASDir<ObjectType::File>(0);
    auto entry_path_latest = GetStoragePath(root_latest, id);

    // Uplink target-cache entry blob from older generation to the latest
    // generation.
    if (not FileSystemManager::IsFile(entry_path_latest)) {
        if (not FileSystemManager::CreateDirectory(
                entry_path_latest.parent_path())) {
            return false;
        }
        if (not FileSystemManager::CreateFileHardlink(
                entry_path,
                entry_path_latest,
                /*log_failure_at=*/LogLevel::Debug) and
            not FileSystemManager::IsFile(entry_path_latest)) {
            return false;
        }
    }
    return true;
}