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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
|
// Copyright 2023 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 BOOTSTRAP_BUILD_TOOL
#include "src/buildtool/serve_api/serve_service/source_tree.hpp"
#include <algorithm>
#include <shared_mutex>
#include <thread>
#include "fmt/core.h"
#include "src/buildtool/common/artifact.hpp"
#include "src/buildtool/common/artifact_digest.hpp"
#include "src/buildtool/common/artifact_digest_factory.hpp"
#include "src/buildtool/compatibility/compatibility.hpp"
#include "src/buildtool/crypto/hash_function.hpp"
#include "src/buildtool/execution_api/git/git_api.hpp"
#include "src/buildtool/file_system/file_system_manager.hpp"
#include "src/buildtool/file_system/git_repo.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/multithreading/async_map_utils.hpp"
#include "src/buildtool/storage/fs_utils.hpp"
#include "src/buildtool/storage/garbage_collector.hpp"
#include "src/buildtool/storage/repository_garbage_collector.hpp"
#include "src/utils/archive/archive_ops.hpp"
#include "src/utils/cpp/expected.hpp"
namespace {
auto ArchiveTypeToString(
::justbuild::just_serve::ServeArchiveTreeRequest_ArchiveType const& type)
-> std::string {
using ServeArchiveType =
::justbuild::just_serve::ServeArchiveTreeRequest_ArchiveType;
switch (type) {
case ServeArchiveType::ServeArchiveTreeRequest_ArchiveType_ZIP: {
return "zip";
}
case ServeArchiveType::ServeArchiveTreeRequest_ArchiveType_TAR:
default:
return "archive"; // default to .tar archive
}
}
auto SymlinksResolveToPragmaSpecial(
::justbuild::just_serve::ServeArchiveTreeRequest_SymlinksResolve const&
resolve) -> std::optional<PragmaSpecial> {
using ServeSymlinksResolve =
::justbuild::just_serve::ServeArchiveTreeRequest_SymlinksResolve;
switch (resolve) {
case ServeSymlinksResolve::
ServeArchiveTreeRequest_SymlinksResolve_IGNORE: {
return PragmaSpecial::Ignore;
}
case ServeSymlinksResolve::
ServeArchiveTreeRequest_SymlinksResolve_PARTIAL: {
return PragmaSpecial::ResolvePartially;
}
case ServeSymlinksResolve::
ServeArchiveTreeRequest_SymlinksResolve_COMPLETE: {
return PragmaSpecial::ResolveCompletely;
}
case ServeSymlinksResolve::ServeArchiveTreeRequest_SymlinksResolve_NONE:
default:
return std::nullopt; // default to NONE
}
}
/// \brief Extracts the archive of given type into the destination directory
/// provided. Returns nullopt on success, or error string on failure.
[[nodiscard]] auto ExtractArchive(std::filesystem::path const& archive,
std::string const& repo_type,
std::filesystem::path const& dst_dir) noexcept
-> std::optional<std::string> {
if (repo_type == "archive") {
return ArchiveOps::ExtractArchive(
ArchiveType::TarAuto, archive, dst_dir);
}
if (repo_type == "zip") {
return ArchiveOps::ExtractArchive(
ArchiveType::ZipAuto, archive, dst_dir);
}
return "unrecognized archive type";
}
} // namespace
auto SourceTreeService::GetSubtreeFromCommit(
std::filesystem::path const& repo_path,
std::string const& commit,
std::string const& subdir,
std::shared_ptr<Logger> const& logger)
-> expected<std::string, GitLookupError> {
if (auto git_cas = GitCAS::Open(repo_path)) {
if (auto repo = GitRepo::Open(git_cas)) {
// wrap logger for GitRepo call
auto wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[logger, repo_path, commit, subdir](auto const& msg,
bool fatal) {
if (fatal) {
logger->Emit(LogLevel::Debug,
"While retrieving subtree {} of commit {} "
"from repository {}:\n{}",
subdir,
commit,
repo_path.string(),
msg);
}
});
return repo->GetSubtreeFromCommit(commit, subdir, wrapped_logger);
}
}
return unexpected{GitLookupError::Fatal};
}
auto SourceTreeService::GetSubtreeFromTree(
std::filesystem::path const& repo_path,
std::string const& tree_id,
std::string const& subdir,
std::shared_ptr<Logger> const& logger)
-> expected<std::string, GitLookupError> {
if (auto git_cas = GitCAS::Open(repo_path)) {
if (auto repo = GitRepo::Open(git_cas)) {
// wrap logger for GitRepo call
auto wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[logger, repo_path, tree_id, subdir](auto const& msg,
bool fatal) {
if (fatal) {
logger->Emit(LogLevel::Debug,
"While retrieving subtree {} of tree {} "
"from repository {}:\n{}",
subdir,
tree_id,
repo_path.string(),
msg);
}
});
if (auto subtree_id =
repo->GetSubtreeFromTree(tree_id, subdir, wrapped_logger)) {
return *subtree_id;
}
return unexpected{GitLookupError::NotFound}; // non-fatal failure
}
}
return unexpected{GitLookupError::Fatal};
}
auto SourceTreeService::GetBlobFromRepo(std::filesystem::path const& repo_path,
std::string const& blob_id,
std::shared_ptr<Logger> const& logger)
-> expected<std::string, GitLookupError> {
if (auto git_cas = GitCAS::Open(repo_path)) {
if (auto repo = GitRepo::Open(git_cas)) {
// wrap logger for GitRepo call
auto wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[logger, repo_path, blob_id](auto const& msg, bool fatal) {
if (fatal) {
logger->Emit(LogLevel::Debug,
"While checking existence of blob {} in "
"repository {}:\n{}",
blob_id,
repo_path.string(),
msg);
}
});
auto res = repo->TryReadBlob(blob_id, wrapped_logger);
if (not res.first) {
return unexpected{GitLookupError::Fatal};
}
if (not res.second) {
logger->Emit(LogLevel::Debug,
"Blob {} not found in repository {}",
blob_id,
repo_path.string());
return unexpected{
GitLookupError::NotFound}; // non-fatal failure
}
return res.second.value();
}
}
// failed to open repository
logger->Emit(
LogLevel::Debug, "Failed to open repository {}", repo_path.string());
return unexpected{GitLookupError::Fatal};
}
auto SourceTreeService::ServeCommitTree(
::grpc::ServerContext* /* context */,
const ::justbuild::just_serve::ServeCommitTreeRequest* request,
ServeCommitTreeResponse* response) -> ::grpc::Status {
auto repo_lock = RepositoryGarbageCollector::SharedLock(storage_config_);
if (not repo_lock) {
logger_->Emit(LogLevel::Error, "Could not acquire repo gc SharedLock");
response->set_status(ServeCommitTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto const& commit{request->commit()};
auto const& subdir{request->subdir()};
// try in local build root Git cache
auto res = GetSubtreeFromCommit(
storage_config_.GitRoot(), commit, subdir, logger_);
if (res) {
auto tree_id = *std::move(res);
auto status = ServeCommitTreeResponse::OK;
if (request->sync_tree()) {
status =
SyncGitEntryToCas<ObjectType::Tree, ServeCommitTreeResponse>(
tree_id, storage_config_.GitRoot());
}
*(response->mutable_tree()) = std::move(tree_id);
response->set_status(status);
return ::grpc::Status::OK;
}
// report fatal failure
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(LogLevel::Error,
"Failed while retrieving subtree {} of commit {} from "
"repository {}",
subdir,
commit,
storage_config_.GitRoot().string());
response->set_status(ServeCommitTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// try given extra repositories, in order
for (auto const& path : serve_config_.known_repositories) {
auto res = GetSubtreeFromCommit(path, commit, subdir, logger_);
if (res) {
auto tree_id = *std::move(res);
auto status = ServeCommitTreeResponse::OK;
if (request->sync_tree()) {
status =
SyncGitEntryToCas<ObjectType::Tree,
ServeCommitTreeResponse>(tree_id, path);
}
*(response->mutable_tree()) = std::move(tree_id);
response->set_status(status);
return ::grpc::Status::OK;
}
// report fatal failure
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(LogLevel::Error,
"Failed while retrieving subtree {} of commit {} "
"from repository {}",
subdir,
commit,
path.string());
response->set_status(ServeCommitTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
}
// commit not found
response->set_status(ServeCommitTreeResponse::NOT_FOUND);
return ::grpc::Status::OK;
}
auto SourceTreeService::SyncArchive(std::string const& tree_id,
std::filesystem::path const& repo_path,
bool sync_tree,
ServeArchiveTreeResponse* response)
-> ::grpc::Status {
auto status = ServeArchiveTreeResponse::OK;
if (sync_tree) {
status = SyncGitEntryToCas<ObjectType::Tree, ServeArchiveTreeResponse>(
tree_id, repo_path);
}
*(response->mutable_tree()) = tree_id;
response->set_status(status);
return ::grpc::Status::OK;
}
template <ObjectType kType, typename TResponse>
auto SourceTreeService::SyncGitEntryToCas(
std::string const& object_hash,
std::filesystem::path const& repo_path) const noexcept
-> std::remove_cvref_t<decltype(TResponse::OK)> {
if (IsTreeObject(kType) and Compatibility::IsCompatible()) {
logger_->Emit(LogLevel::Error,
"Cannot sync tree {} from repository {} with "
"the remote in compatible mode",
object_hash,
repo_path.string());
return TResponse::SYNC_ERROR;
}
auto repo = RepositoryConfig{};
if (not repo.SetGitCAS(repo_path)) {
logger_->Emit(
LogLevel::Error, "Failed to SetGitCAS at {}", repo_path.string());
return TResponse::INTERNAL_ERROR;
}
auto const digest =
ArtifactDigestFactory::Create(storage_config_.hash_function.GetType(),
object_hash,
0,
IsTreeObject(kType));
if (not digest) {
logger_->Emit(LogLevel::Error, "{}", digest.error());
return TResponse::INTERNAL_ERROR;
}
auto git_api = GitApi{&repo};
if (not git_api.RetrieveToCas(
{Artifact::ObjectInfo{.digest = *digest, .type = kType}},
*apis_.remote)) {
logger_->Emit(LogLevel::Error,
"Failed to sync object {} from repository {}",
object_hash,
repo_path.string());
return TResponse::SYNC_ERROR;
}
return TResponse::OK;
}
auto SourceTreeService::ResolveContentTree(
std::string const& tree_id,
std::filesystem::path const& repo_path,
bool repo_is_git_cache,
std::optional<PragmaSpecial> const& resolve_special,
bool sync_tree,
ServeArchiveTreeResponse* response) -> ::grpc::Status {
if (resolve_special) {
// get the resolved tree
auto tree_id_file = StorageUtils::GetResolvedTreeIDFile(
storage_config_, tree_id, *resolve_special);
if (FileSystemManager::Exists(tree_id_file)) {
// read resolved tree id
auto resolved_tree_id = FileSystemManager::ReadFile(tree_id_file);
if (not resolved_tree_id) {
logger_->Emit(LogLevel::Error,
"Failed to read resolved tree id from file {}",
tree_id_file.string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
return SyncArchive(
*resolved_tree_id, repo_path, sync_tree, response);
}
// resolve tree; target repository is always the Git cache
auto target_cas = GitCAS::Open(storage_config_.GitRoot());
if (not target_cas) {
logger_->Emit(LogLevel::Error,
"Failed to open Git ODB at {}",
storage_config_.GitRoot().string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto source_cas = target_cas;
if (not repo_is_git_cache) {
source_cas = GitCAS::Open(repo_path);
if (not source_cas) {
logger_->Emit(LogLevel::Error,
"Failed to open Git ODB at {}",
repo_path.string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
}
std::optional<ResolvedGitObject> resolved_tree = std::nullopt;
bool failed{false};
{
TaskSystem ts{serve_config_.jobs};
resolve_symlinks_map_.ConsumeAfterKeysReady(
&ts,
{GitObjectToResolve{tree_id,
".",
*resolve_special,
/*known_info=*/std::nullopt,
source_cas,
target_cas}},
[&resolved_tree](auto hashes) { resolved_tree = *hashes[0]; },
[logger = logger_, tree_id, &failed](auto const& msg,
bool fatal) {
logger->Emit(LogLevel::Error,
"While resolving tree {}:\n{}",
tree_id,
msg);
failed = failed or fatal;
});
}
if (failed) {
logger_->Emit(
LogLevel::Error, "Failed to resolve tree id {}", tree_id);
response->set_status(ServeArchiveTreeResponse::RESOLVE_ERROR);
return ::grpc::Status::OK;
}
// check if we have a value
if (not resolved_tree) {
// check for cycles
if (auto error = DetectAndReportCycle(
fmt::format("resolving symlinks in tree {}", tree_id),
resolve_symlinks_map_,
kGitObjectToResolvePrinter)) {
logger_->Emit(LogLevel::Error, *error);
response->set_status(ServeArchiveTreeResponse::RESOLVE_ERROR);
return ::grpc::Status::OK;
}
logger_->Emit(LogLevel::Error,
"Unknown error while resolving tree id {}",
tree_id);
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// keep tree alive in the Git cache via a tagged commit
auto wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[logger = logger_,
storage_config = &storage_config_,
resolved_tree](auto const& msg, bool fatal) {
if (fatal) {
logger->Emit(LogLevel::Error,
"While keeping tree {} in repository {}:\n{}",
resolved_tree->id,
storage_config->GitRoot().string(),
msg);
}
});
{
// this is a non-thread-safe Git operation, so it must be guarded!
std::shared_lock slock{mutex_};
// open real repository at Git CAS location
auto git_repo = GitRepo::Open(storage_config_.GitRoot());
if (not git_repo) {
logger_->Emit(LogLevel::Error,
"Failed to open Git CAS repository {}",
storage_config_.GitRoot().string());
response->set_status(ServeArchiveTreeResponse::RESOLVE_ERROR);
return ::grpc::Status::OK;
}
// Important: message must be consistent with just-mr!
if (not git_repo->KeepTree(resolved_tree->id,
"Keep referenced tree alive", // message
wrapped_logger)) {
response->set_status(ServeArchiveTreeResponse::RESOLVE_ERROR);
return ::grpc::Status::OK;
}
}
// cache the resolved tree association
if (not StorageUtils::WriteTreeIDFile(tree_id_file,
resolved_tree->id)) {
logger_->Emit(LogLevel::Error,
"Failed to write resolved tree id to file {}",
tree_id_file.string());
response->set_status(ServeArchiveTreeResponse::RESOLVE_ERROR);
return ::grpc::Status::OK;
}
return SyncArchive(resolved_tree->id, repo_path, sync_tree, response);
}
// if no special handling of symlinks, use given tree as-is
return SyncArchive(tree_id, repo_path, sync_tree, response);
}
auto SourceTreeService::CommonImportToGit(
std::filesystem::path const& content_path,
std::string const& commit_message) -> expected<std::string, std::string> {
// the repository path that imports the content must be separate from the
// content path, to avoid polluting the entries
auto tmp_dir = storage_config_.CreateTypedTmpDir("import-repo");
if (not tmp_dir) {
return unexpected{
std::string("Failed to create tmp path for import repository")};
}
auto const& repo_path = tmp_dir->GetPath();
// do the initial commit; no need to guard, as the tmp location is unique
auto git_repo = GitRepo::InitAndOpen(repo_path,
/*is_bare=*/false);
if (not git_repo) {
return unexpected{fmt::format("Could not initialize repository {}",
repo_path.string())};
}
// wrap logger for GitRepo call
std::string err;
auto wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[content_path, repo_path, &err](auto const& msg, bool fatal) {
if (fatal) {
err = fmt::format(
"While committing directory {} in repository {}:\n{}",
content_path.string(),
repo_path.string(),
msg);
}
});
// stage and commit all
auto commit_hash =
git_repo->CommitDirectory(content_path, commit_message, wrapped_logger);
if (not commit_hash) {
return unexpected{err};
}
// open the Git CAS repo
auto just_git_cas = GitCAS::Open(storage_config_.GitRoot());
if (not just_git_cas) {
return unexpected{fmt::format("Failed to open Git ODB at {}",
storage_config_.GitRoot().string())};
}
auto just_git_repo = GitRepo::Open(just_git_cas);
if (not just_git_repo) {
return unexpected{fmt::format("Failed to open Git repository {}",
storage_config_.GitRoot().string())};
}
// wrap logger for GitRepo call
err.clear();
wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[&err, storage_config = &storage_config_](auto const& msg, bool fatal) {
if (fatal) {
err = fmt::format("While fetching in repository {}:\n{}",
storage_config->GitRoot().string(),
msg);
}
});
// fetch the new commit into the Git CAS via tmp directory; the call is
// thread-safe, so it needs no guarding
if (not just_git_repo->LocalFetchViaTmpRepo(storage_config_,
repo_path.string(),
/*branch=*/std::nullopt,
wrapped_logger)) {
return unexpected{err};
}
// wrap logger for GitRepo call
err.clear();
wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[commit_hash, storage_config = &storage_config_, &err](auto const& msg,
bool fatal) {
if (fatal) {
err =
fmt::format("While tagging commit {} in repository {}:\n{}",
*commit_hash,
storage_config->GitRoot().string(),
msg);
}
});
// tag commit and keep it in Git CAS
{
// this is a non-thread-safe Git operation, so it must be guarded!
std::shared_lock slock{mutex_};
// open real repository at Git CAS location
auto git_repo = GitRepo::Open(storage_config_.GitRoot());
if (not git_repo) {
return unexpected{
fmt::format("Failed to open Git CAS repository {}",
storage_config_.GitRoot().string())};
}
// Important: message must be consistent with just-mr!
if (not git_repo->KeepTag(*commit_hash,
"Keep referenced tree alive", // message
wrapped_logger)) {
return unexpected{err};
}
}
// wrap logger for GitRepo call
err.clear();
wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[commit_hash, &err](auto const& msg, bool fatal) {
if (fatal) {
err = fmt::format("While retrieving tree id of commit {}:\n{}",
*commit_hash,
msg);
}
});
// get the root tree of this commit; this is thread-safe
auto res =
just_git_repo->GetSubtreeFromCommit(*commit_hash, ".", wrapped_logger);
if (not res) {
return unexpected{err};
}
// return the root tree id
return *std::move(res);
}
auto SourceTreeService::ArchiveImportToGit(
std::filesystem::path const& unpack_path,
std::filesystem::path const& archive_tree_id_file,
std::string const& content,
std::string const& archive_type,
std::string const& subdir,
std::optional<PragmaSpecial> const& resolve_special,
bool sync_tree,
ServeArchiveTreeResponse* response) -> ::grpc::Status {
// Important: commit message must match that in just-mr!
auto commit_message =
fmt::format("Content of {} {}", archive_type, content);
auto res = CommonImportToGit(unpack_path, commit_message);
if (not res) {
// report the error
logger_->Emit(LogLevel::Error, "{}", res.error());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto const& tree_id = *res;
// write to tree id file
if (not StorageUtils::WriteTreeIDFile(archive_tree_id_file, tree_id)) {
logger_->Emit(LogLevel::Error,
"Failed to write tree id to file {}",
archive_tree_id_file.string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// open the Git CAS repo
auto just_git_cas = GitCAS::Open(storage_config_.GitRoot());
if (not just_git_cas) {
logger_->Emit(LogLevel::Error,
"Failed to open Git ODB at {}",
storage_config_.GitRoot().string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto just_git_repo = GitRepo::Open(just_git_cas);
if (not just_git_repo) {
logger_->Emit(LogLevel::Error,
"Failed to open Git repository {}",
storage_config_.GitRoot().string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// wrap logger for GitRepo call
std::string err;
auto wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[&err, subdir, tree_id](auto const& msg, bool fatal) {
if (fatal) {
err = fmt::format("While retrieving subtree {} of tree {}:\n{}",
subdir,
tree_id,
msg);
}
});
// get the subtree id; this is thread-safe
auto subtree_id =
just_git_repo->GetSubtreeFromTree(tree_id, subdir, wrapped_logger);
if (not subtree_id) {
logger_->Emit(LogLevel::Error, "{}", err);
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
return ResolveContentTree(*subtree_id,
storage_config_.GitRoot(),
/*repo_is_git_cache=*/true,
resolve_special,
sync_tree,
response);
}
auto SourceTreeService::IsTreeInRepo(std::string const& tree_id,
std::filesystem::path const& repo_path,
std::shared_ptr<Logger> const& logger)
-> std::optional<bool> {
if (auto git_cas = GitCAS::Open(repo_path)) {
if (auto repo = GitRepo::Open(git_cas)) {
// wrap logger for GitRepo call
auto wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
[logger, repo_path, tree_id](auto const& msg, bool fatal) {
if (fatal) {
logger->Emit(LogLevel::Debug,
"While checking existence of tree {} in "
"repository {}:\n{}",
tree_id,
repo_path.string(),
msg);
}
});
return repo->CheckTreeExists(tree_id, wrapped_logger);
}
}
// failed to open repository
logger->Emit(
LogLevel::Debug, "Failed to open repository {}", repo_path.string());
return std::nullopt;
}
auto SourceTreeService::ServeArchiveTree(
::grpc::ServerContext* /* context */,
const ::justbuild::just_serve::ServeArchiveTreeRequest* request,
ServeArchiveTreeResponse* response) -> ::grpc::Status {
auto repo_lock = RepositoryGarbageCollector::SharedLock(storage_config_);
if (not repo_lock) {
logger_->Emit(LogLevel::Error, "Could not acquire repo gc SharedLock");
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto const& content{request->content()};
auto archive_type = ArchiveTypeToString(request->archive_type());
auto const& subdir{request->subdir()};
auto resolve_special =
SymlinksResolveToPragmaSpecial(request->resolve_symlinks());
// check for archive_tree_id_file
auto archive_tree_id_file = StorageUtils::GetArchiveTreeIDFile(
storage_config_, archive_type, content);
if (FileSystemManager::Exists(archive_tree_id_file)) {
// read archive_tree_id from file tree_id_file
auto archive_tree_id =
FileSystemManager::ReadFile(archive_tree_id_file);
if (not archive_tree_id) {
logger_->Emit(LogLevel::Error,
"Failed to read tree id from file {}",
archive_tree_id_file.string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check local build root Git cache
auto res = GetSubtreeFromTree(
storage_config_.GitRoot(), *archive_tree_id, subdir, logger_);
if (res) {
return ResolveContentTree(*res, // tree_id
storage_config_.GitRoot(),
/*repo_is_git_cache=*/true,
resolve_special,
request->sync_tree(),
response);
}
// check for fatal error
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(LogLevel::Error,
"Failed to open repository {}",
storage_config_.GitRoot().string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check known repositories
for (auto const& path : serve_config_.known_repositories) {
auto res =
GetSubtreeFromTree(path, *archive_tree_id, subdir, logger_);
if (res) {
return ResolveContentTree(*res, // tree_id
path,
/*repo_is_git_cache=*/false,
resolve_special,
request->sync_tree(),
response);
}
// check for fatal error
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(LogLevel::Error,
"Failed to open repository {}",
path.string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
}
// report error for missing tree specified in id file
logger_->Emit(LogLevel::Error,
"Failed while retrieving subtree {} of known tree {}",
subdir,
*archive_tree_id);
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// acquire lock for CAS
auto lock = GarbageCollector::SharedLock(storage_config_);
if (not lock) {
logger_->Emit(LogLevel::Error, "Could not acquire gc SharedLock");
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check if content is in local CAS already
auto const digest = ArtifactDigestFactory::Create(
storage_config_.hash_function.GetType(), content, 0, /*is_tree=*/false);
auto const& cas = storage_.CAS();
auto content_cas_path =
digest ? cas.BlobPath(*digest, /*is_executable=*/false) : std::nullopt;
if (not content_cas_path) {
// check if content blob is in Git cache
auto res = GetBlobFromRepo(storage_config_.GitRoot(), content, logger_);
if (res) {
// add to CAS
content_cas_path = StorageUtils::AddToCAS(storage_, *res);
}
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(
LogLevel::Error,
"Failed while trying to retrieve content {} from repository {}",
content,
storage_config_.GitRoot().string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
}
if (not content_cas_path) {
// check if content blob is in a known repository
for (auto const& path : serve_config_.known_repositories) {
auto res = GetBlobFromRepo(path, content, logger_);
if (res) {
// add to CAS
content_cas_path = StorageUtils::AddToCAS(storage_, *res);
if (content_cas_path) {
break;
}
}
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(LogLevel::Error,
"Failed while trying to retrieve content {} from "
"repository {}",
content,
path.string());
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
}
}
if (digest and not content_cas_path) {
// try to retrieve it from remote CAS
if (not(apis_.remote->IsAvailable(*digest) and
apis_.remote->RetrieveToCas(
{Artifact::ObjectInfo{.digest = *digest,
.type = ObjectType::File}},
*apis_.local))) {
// content could not be found
response->set_status(ServeArchiveTreeResponse::NOT_FOUND);
return ::grpc::Status::OK;
}
// content should now be in CAS
content_cas_path = cas.BlobPath(*digest, /*is_executable=*/false);
if (not content_cas_path) {
logger_->Emit(LogLevel::Error,
"Retrieving content {} from CAS failed unexpectedly",
content);
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
}
// extract archive
auto tmp_dir = storage_config_.CreateTypedTmpDir(archive_type);
if (not tmp_dir) {
logger_->Emit(
LogLevel::Error,
"Failed to create tmp path for {} archive with content {}",
archive_type,
content);
response->set_status(ServeArchiveTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto res =
ExtractArchive(*content_cas_path, archive_type, tmp_dir->GetPath());
if (res != std::nullopt) {
logger_->Emit(LogLevel::Error,
"Failed to extract archive {} from CAS:\n{}",
content_cas_path->string(),
*res);
response->set_status(ServeArchiveTreeResponse::UNPACK_ERROR);
return ::grpc::Status::OK;
}
// import to git
return ArchiveImportToGit(tmp_dir->GetPath(),
archive_tree_id_file,
content,
archive_type,
subdir,
resolve_special,
request->sync_tree(),
response);
}
auto SourceTreeService::DistdirImportToGit(
std::string const& distdir_tree_id,
std::string const& content_id,
std::unordered_map<std::string, std::pair<std::string, bool>> const&
content_list,
bool sync_tree,
ServeDistdirTreeResponse* response) -> ::grpc::Status {
auto repo_lock = RepositoryGarbageCollector::SharedLock(storage_config_);
if (not repo_lock) {
logger_->Emit(LogLevel::Error, "Could not acquire repo gc SharedLock");
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// create tmp directory for the distdir
auto distdir_tmp_dir = storage_config_.CreateTypedTmpDir("distdir");
if (not distdir_tmp_dir) {
logger_->Emit(LogLevel::Error,
"Failed to create tmp path for distdir target {}",
content_id);
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto const& tmp_path = distdir_tmp_dir->GetPath();
// link the CAS blobs into the tmp dir
auto const& cas = storage_.CAS();
if (not std::all_of(
content_list.begin(),
content_list.end(),
[&cas, tmp_path](auto const& kv) {
auto const digest = ArtifactDigestFactory::Create(
cas.GetHashFunction().GetType(),
kv.second.first,
0,
/*is_tree=*/false);
if (not digest) {
return false;
}
auto content_path = cas.BlobPath(*digest, kv.second.second);
if (content_path) {
return FileSystemManager::CreateFileHardlink(
*content_path, // from: cas_path/content_id
tmp_path / kv.first) // to: tmp_path/name
.has_value();
}
return false;
})) {
logger_->Emit(LogLevel::Error,
"Failed to create links to CAS content {}",
content_id);
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// Important: commit message must match that in just-mr!
auto commit_message = fmt::format("Content of distdir {}", content_id);
auto res = CommonImportToGit(tmp_path, commit_message);
if (not res) {
// report the error
logger_->Emit(LogLevel::Error, "{}", res.error());
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto tree_id = *std::move(res);
// check the committed tree matches what we expect
if (tree_id != distdir_tree_id) {
// something is very wrong...
logger_->Emit(LogLevel::Error,
"Unexpected mismatch for tree of committed "
"distdir:\nexpected {} but got {}",
distdir_tree_id,
tree_id);
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// if asked, sync tree (and implicitly all blobs) with remote CAS
auto status = ServeDistdirTreeResponse::OK;
if (sync_tree) {
status = SyncGitEntryToCas<ObjectType::Tree, ServeDistdirTreeResponse>(
tree_id, storage_config_.GitRoot());
}
// set response on success
*(response->mutable_tree()) = std::move(tree_id);
response->set_status(status);
return ::grpc::Status::OK;
}
auto SourceTreeService::ServeDistdirTree(
::grpc::ServerContext* /* context */,
const ::justbuild::just_serve::ServeDistdirTreeRequest* request,
ServeDistdirTreeResponse* response) -> ::grpc::Status {
// acquire lock for CAS
auto lock = GarbageCollector::SharedLock(storage_config_);
if (not lock) {
logger_->Emit(LogLevel::Error, "Could not acquire gc SharedLock");
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// create in-memory tree from distfiles map
GitRepo::tree_entries_t entries{};
entries.reserve(request->distfiles().size());
auto const& cas = storage_.CAS();
std::unordered_map<std::string, std::pair<std::string, bool>>
content_list{};
content_list.reserve(request->distfiles().size());
for (auto const& kv : request->distfiles()) {
bool blob_found{};
std::string blob_digest; // The digest of the requested distfile, taken
// by the hash applicable for our CAS; this
// might be different from content, if our CAS
// ist not based on git blob identifiers
// (i.e., if we're not in native mode).
auto const& content = kv.content();
// check content blob is known
// first check the local CAS itself, provided it uses the same type
// of identifier
auto const digest = ArtifactDigestFactory::Create(
storage_config_.hash_function.GetType(),
content,
0,
/*is_tree=*/false);
if (not Compatibility::IsCompatible()) {
blob_found = digest and cas.BlobPath(*digest, kv.executable());
}
if (blob_found) {
blob_digest = content;
}
else {
// check local Git cache
auto res =
GetBlobFromRepo(storage_config_.GitRoot(), content, logger_);
if (res) {
// add content to local CAS
auto stored_blob = cas.StoreBlob(*res, kv.executable());
if (not stored_blob) {
logger_->Emit(LogLevel::Error,
"Failed to store content {} from local Git "
"cache to local CAS",
content);
response->set_status(
ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
blob_found = true;
blob_digest = stored_blob->hash();
}
else {
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(LogLevel::Error,
"Failed while trying to retrieve content {} "
"from repository {}",
content,
storage_config_.GitRoot().string());
response->set_status(
ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check known repositories
for (auto const& path : serve_config_.known_repositories) {
auto res = GetBlobFromRepo(path, content, logger_);
if (res) {
// add content to local CAS
auto stored_blob = cas.StoreBlob(*res, kv.executable());
if (not stored_blob) {
logger_->Emit(LogLevel::Error,
"Failed to store content {} from "
"known repository {} to local CAS",
path.string(),
content);
response->set_status(
ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
blob_found = true;
blob_digest = stored_blob->hash();
break;
}
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(
LogLevel::Error,
"Failed while trying to retrieve content {} from "
"repository {}",
content,
path.string());
response->set_status(
ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
}
if (not blob_found) {
// check remote CAS
if (not Compatibility::IsCompatible() and digest and
apis_.remote->IsAvailable(*digest)) {
// retrieve content to local CAS
if (not apis_.remote->RetrieveToCas(
{Artifact::ObjectInfo{
.digest = *digest,
.type = kv.executable()
? ObjectType::Executable
: ObjectType::File}},
*apis_.local)) {
logger_->Emit(LogLevel::Error,
"Failed to retrieve content {} from "
"remote to local CAS",
content);
response->set_status(
ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
blob_found = true;
blob_digest = content;
}
}
}
}
// error out if blob is not known
if (not blob_found) {
logger_->Emit(LogLevel::Error, "Content {} is not known", content);
response->set_status(ServeDistdirTreeResponse::NOT_FOUND);
return ::grpc::Status::OK;
}
// store content blob to the entries list, using the expected raw id
if (auto raw_id = FromHexString(content)) {
entries[*raw_id].emplace_back(
kv.name(),
kv.executable() ? ObjectType::Executable : ObjectType::File);
}
else {
logger_->Emit(
LogLevel::Error,
"Conversion of content {} to raw id failed unexpectedly",
content);
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// store to content_list for import-to-git hardlinking
content_list.insert_or_assign(
kv.name(), std::make_pair(blob_digest, kv.executable()));
}
// get hash of distdir content; this must match with that in just-mr
auto content_id = HashFunction{HashFunction::Type::GitSHA1}
.HashBlobData(nlohmann::json(content_list).dump())
.HexString();
// create in-memory tree of the distdir, now that we know we have all blobs
auto tree = GitRepo::CreateShallowTree(entries);
if (not tree) {
logger_->Emit(LogLevel::Error,
"Failed to construct in-memory tree for distdir");
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// get hash from raw_id
auto tree_id = ToHexString(tree->first);
// add tree to local CAS
if (not cas.StoreTree(tree->second)) {
logger_->Emit(LogLevel::Error,
"Failed to store distdir tree {} to local CAS",
tree_id);
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check if tree is already in Git cache
auto has_tree = IsTreeInRepo(tree_id, storage_config_.GitRoot(), logger_);
if (not has_tree) {
logger_->Emit(LogLevel::Error,
"Failed while checking for tree {} in repository {}",
tree_id,
storage_config_.GitRoot().string());
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
if (*has_tree) {
// if asked, sync tree and all blobs with remote CAS
auto status = ServeDistdirTreeResponse::OK;
if (request->sync_tree()) {
status =
SyncGitEntryToCas<ObjectType::Tree, ServeDistdirTreeResponse>(
tree_id, storage_config_.GitRoot());
}
// set response on success
*(response->mutable_tree()) = std::move(tree_id);
response->set_status(status);
return ::grpc::Status::OK;
}
// check if tree is in a known repository
for (auto const& path : serve_config_.known_repositories) {
auto has_tree = IsTreeInRepo(tree_id, path, logger_);
if (not has_tree) {
logger_->Emit(LogLevel::Error,
"Failed while checking for tree {} in repository {}",
tree_id,
path.string());
response->set_status(ServeDistdirTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
if (*has_tree) {
// if asked, sync tree and all blobs with remote CAS
auto status = ServeDistdirTreeResponse::OK;
if (request->sync_tree()) {
status =
SyncGitEntryToCas<ObjectType::Tree,
ServeDistdirTreeResponse>(tree_id, path);
}
// set response on success
*(response->mutable_tree()) = std::move(tree_id);
response->set_status(status);
return ::grpc::Status::OK;
}
}
// otherwise, we import the tree from CAS ourselves
return DistdirImportToGit(
tree_id, content_id, content_list, request->sync_tree(), response);
}
auto SourceTreeService::ServeContent(
::grpc::ServerContext* /* context */,
const ::justbuild::just_serve::ServeContentRequest* request,
ServeContentResponse* response) -> ::grpc::Status {
auto const& content{request->content()};
// acquire locks
auto repo_lock = RepositoryGarbageCollector::SharedLock(storage_config_);
if (not repo_lock) {
logger_->Emit(LogLevel::Error, "Could not acquire repo gc SharedLock");
response->set_status(ServeContentResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto lock = GarbageCollector::SharedLock(storage_config_);
if (not lock) {
logger_->Emit(LogLevel::Error, "Could not acquire gc SharedLock");
response->set_status(ServeContentResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check if content blob is in Git cache
auto res = GetBlobFromRepo(storage_config_.GitRoot(), content, logger_);
if (res) {
auto const status =
SyncGitEntryToCas<ObjectType::File, ServeContentResponse>(
content, storage_config_.GitRoot());
response->set_status(status);
return ::grpc::Status::OK;
}
if (res.error() == GitLookupError::Fatal) {
logger_->Emit(LogLevel::Error,
"Failed while checking for content {} in repository {}",
content,
storage_config_.GitRoot().string());
response->set_status(ServeContentResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check if content blob is in a known repository
for (auto const& path : serve_config_.known_repositories) {
auto res = GetBlobFromRepo(path, content, logger_);
if (res) {
// upload blob to remote CAS
auto const status =
SyncGitEntryToCas<ObjectType::File, ServeContentResponse>(
content, path);
response->set_status(status);
return ::grpc::Status::OK;
}
if (res.error() == GitLookupError::Fatal) {
auto str = fmt::format(
"Failed while checking for content {} in repository {}",
content,
path.string());
logger_->Emit(LogLevel::Error, str);
response->set_status(ServeContentResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
}
// check also in the local CAS
auto const digest = ArtifactDigestFactory::Create(
storage_config_.hash_function.GetType(), content, 0, /*is_tree=*/false);
if (digest and apis_.local->IsAvailable(*digest)) {
if (not apis_.local->RetrieveToCas(
{Artifact::ObjectInfo{.digest = *digest,
.type = ObjectType::File}},
*apis_.remote)) {
logger_->Emit(LogLevel::Error,
"Failed to sync content {} from local CAS",
content);
response->set_status(ServeContentResponse::SYNC_ERROR);
return ::grpc::Status::OK;
}
// success!
response->set_status(ServeContentResponse::OK);
return ::grpc::Status::OK;
}
// content blob not known
response->set_status(ServeContentResponse::NOT_FOUND);
return ::grpc::Status::OK;
}
auto SourceTreeService::ServeTree(
::grpc::ServerContext* /* context */,
const ::justbuild::just_serve::ServeTreeRequest* request,
ServeTreeResponse* response) -> ::grpc::Status {
auto const& tree_id{request->tree()};
// acquire locks
auto repo_lock = RepositoryGarbageCollector::SharedLock(storage_config_);
if (not repo_lock) {
logger_->Emit(LogLevel::Error, "Could not acquire repo gc SharedLock");
response->set_status(ServeTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto lock = GarbageCollector::SharedLock(storage_config_);
if (not lock) {
logger_->Emit(LogLevel::Error, "Could not acquire gc SharedLock");
response->set_status(ServeTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check if tree is in Git cache
auto has_tree = IsTreeInRepo(tree_id, storage_config_.GitRoot(), logger_);
if (not has_tree) {
logger_->Emit(LogLevel::Error,
"Failed while checking for tree {} in repository {}",
tree_id,
storage_config_.GitRoot().string());
response->set_status(ServeTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
if (*has_tree) {
auto const status =
SyncGitEntryToCas<ObjectType::Tree, ServeTreeResponse>(
tree_id, storage_config_.GitRoot());
response->set_status(status);
return ::grpc::Status::OK;
}
// check if tree is in a known repository
for (auto const& path : serve_config_.known_repositories) {
auto has_tree = IsTreeInRepo(tree_id, path, logger_);
if (not has_tree) {
logger_->Emit(LogLevel::Error,
"Failed while checking for tree {} in repository {}",
tree_id,
path.string());
response->set_status(ServeTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
if (*has_tree) {
auto const status =
SyncGitEntryToCas<ObjectType::Tree, ServeTreeResponse>(tree_id,
path);
response->set_status(status);
return ::grpc::Status::OK;
}
}
// check also in the local CAS
auto const digest = ArtifactDigestFactory::Create(
storage_config_.hash_function.GetType(), tree_id, 0, /*is_tree=*/true);
if (digest and apis_.local->IsAvailable(*digest)) {
// upload tree to remote CAS; only possible in native mode
if (Compatibility::IsCompatible()) {
logger_->Emit(LogLevel::Error,
"Cannot sync tree {} from local CAS with the remote "
"in compatible mode",
tree_id);
response->set_status(ServeTreeResponse::SYNC_ERROR);
return ::grpc::Status::OK;
}
if (not apis_.local->RetrieveToCas(
{Artifact::ObjectInfo{.digest = *digest,
.type = ObjectType::Tree}},
*apis_.remote)) {
logger_->Emit(LogLevel::Error,
"Failed to sync tree {} from local CAS",
tree_id);
response->set_status(ServeTreeResponse::SYNC_ERROR);
return ::grpc::Status::OK;
}
// success!
response->set_status(ServeTreeResponse::OK);
return ::grpc::Status::OK;
}
// tree not known
response->set_status(ServeTreeResponse::NOT_FOUND);
return ::grpc::Status::OK;
}
auto SourceTreeService::CheckRootTree(
::grpc::ServerContext* /* context */,
const ::justbuild::just_serve::CheckRootTreeRequest* request,
CheckRootTreeResponse* response) -> ::grpc::Status {
auto const& tree_id{request->tree()};
// acquire locks
auto repo_lock = RepositoryGarbageCollector::SharedLock(storage_config_);
if (not repo_lock) {
logger_->Emit(LogLevel::Error, "Could not acquire repo gc SharedLock");
response->set_status(CheckRootTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto lock = GarbageCollector::SharedLock(storage_config_);
if (not lock) {
logger_->Emit(LogLevel::Error, "Could not acquire gc SharedLock");
response->set_status(CheckRootTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// check first in the Git cache
auto has_tree = IsTreeInRepo(tree_id, storage_config_.GitRoot(), logger_);
if (not has_tree) {
logger_->Emit(LogLevel::Error,
"Failed while checking for tree {} in repository {}",
tree_id,
storage_config_.GitRoot().string());
response->set_status(CheckRootTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
if (*has_tree) {
// success!
response->set_status(CheckRootTreeResponse::OK);
return ::grpc::Status::OK;
}
// check if tree is in a known repository
for (auto const& path : serve_config_.known_repositories) {
auto has_tree = IsTreeInRepo(tree_id, path, logger_);
if (not has_tree) {
logger_->Emit(LogLevel::Error,
"Failed while checking for tree {} in repository {}",
tree_id,
path.string());
response->set_status(CheckRootTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
if (*has_tree) {
// success!
response->set_status(CheckRootTreeResponse::OK);
return ::grpc::Status::OK;
}
}
// now check in the local CAS
auto const digest = ArtifactDigestFactory::Create(
storage_config_.hash_function.GetType(), tree_id, 0, /*is_tree=*/true);
if (digest and storage_.CAS().TreePath(*digest)) {
// As we currently build only against roots in Git repositories, we need
// to move the tree from CAS to local Git storage
auto tmp_dir =
storage_config_.CreateTypedTmpDir("source-tree-check-root-tree");
if (not tmp_dir) {
logger_->Emit(LogLevel::Error,
"Failed to create tmp directory for copying git-tree "
"{} from remote CAS",
digest->hash());
response->set_status(CheckRootTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
if (not apis_.local->RetrieveToPaths(
{Artifact::ObjectInfo{.digest = *digest,
.type = ObjectType::Tree}},
{tmp_dir->GetPath()})) {
logger_->Emit(LogLevel::Error,
"Failed to copy git-tree {} to {}",
tree_id,
tmp_dir->GetPath().string());
response->set_status(CheckRootTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// Import from tmp dir to Git cache
auto res = CommonImportToGit(
tmp_dir->GetPath(),
fmt::format("Content of tree {}", tree_id) // message
);
if (not res) {
// report the error
logger_->Emit(LogLevel::Error, "{}", res.error());
response->set_status(CheckRootTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto const& imported_tree_id = *res;
// sanity check
if (imported_tree_id != tree_id) {
logger_->Emit(
LogLevel::Error,
"Unexpected mismatch in imported tree:\nexpected {} but got {}",
tree_id,
imported_tree_id);
response->set_status(CheckRootTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// success!
response->set_status(CheckRootTreeResponse::OK);
return ::grpc::Status::OK;
}
// tree not known
response->set_status(CheckRootTreeResponse::NOT_FOUND);
return ::grpc::Status::OK;
}
auto SourceTreeService::GetRemoteTree(
::grpc::ServerContext* /* context */,
const ::justbuild::just_serve::GetRemoteTreeRequest* request,
GetRemoteTreeResponse* response) -> ::grpc::Status {
auto const& tree_id{request->tree()};
// acquire locks
auto lock = GarbageCollector::SharedLock(storage_config_);
if (not lock) {
logger_->Emit(LogLevel::Error, "Could not acquire gc SharedLock");
response->set_status(GetRemoteTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// get tree from remote CAS into tmp dir
auto const digest = ArtifactDigestFactory::Create(
storage_config_.hash_function.GetType(), tree_id, 0, /*is_tree=*/true);
if (not digest or not apis_.remote->IsAvailable(*digest)) {
logger_->Emit(LogLevel::Error,
"Remote CAS does not contain expected tree {}",
tree_id);
response->set_status(GetRemoteTreeResponse::FAILED_PRECONDITION);
return ::grpc::Status::OK;
}
auto tmp_dir =
storage_config_.CreateTypedTmpDir("source-tree-get-remote-tree");
if (not tmp_dir) {
logger_->Emit(LogLevel::Error,
"Failed to create tmp directory for copying git-tree {} "
"from remote CAS",
digest->hash());
response->set_status(GetRemoteTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
if (not apis_.remote->RetrieveToPaths(
{Artifact::ObjectInfo{.digest = *digest, .type = ObjectType::Tree}},
{tmp_dir->GetPath()},
&(*apis_.local))) {
logger_->Emit(LogLevel::Error,
"Failed to retrieve tree {} from remote CAS",
tree_id);
response->set_status(GetRemoteTreeResponse::FAILED_PRECONDITION);
return ::grpc::Status::OK;
}
// Import from tmp dir to Git cache
auto res =
CommonImportToGit(tmp_dir->GetPath(),
fmt::format("Content of tree {}", tree_id) // message
);
if (not res) {
// report the error
logger_->Emit(LogLevel::Error, "{}", res.error());
response->set_status(GetRemoteTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
auto const& imported_tree_id = *res;
// sanity check
if (imported_tree_id != tree_id) {
logger_->Emit(
LogLevel::Error,
"Unexpected mismatch in imported tree:\nexpected {}, but got {}",
tree_id,
imported_tree_id);
response->set_status(GetRemoteTreeResponse::INTERNAL_ERROR);
return ::grpc::Status::OK;
}
// success!
response->set_status(GetRemoteTreeResponse::OK);
return ::grpc::Status::OK;
}
#endif // BOOTSTRAP_BUILD_TOOL
|