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
|
// 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/other_tools/root_maps/commit_git_map.hpp"
#include <algorithm>
#include "src/buildtool/file_system/file_root.hpp"
#include "src/other_tools/git_operations/git_repo_remote.hpp"
#include "src/other_tools/just_mr/progress_reporting/progress.hpp"
#include "src/other_tools/just_mr/progress_reporting/statistics.hpp"
#include "src/utils/cpp/tmp_dir.hpp"
namespace {
[[nodiscard]] auto GitURLIsPath(std::string const& url) noexcept -> bool {
auto prefixes = std::vector<std::string>{"ssh://", "http://", "https://"};
// return true if no URL prefix exists
return std::none_of(
prefixes.begin(), prefixes.end(), [url](auto const& prefix) {
return (url.rfind(prefix, 0) == 0);
});
}
void EnsureCommit(GitRepoInfo const& repo_info,
std::filesystem::path const& repo_root,
GitCASPtr const& git_cas,
gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
gsl::not_null<ImportToGitMap*> const& import_to_git_map,
std::string const& git_bin,
std::vector<std::string> const& launcher,
ServeApi* serve_api,
IExecutionApi* local_api,
IExecutionApi* remote_api,
bool fetch_absent,
gsl::not_null<TaskSystem*> const& ts,
CommitGitMap::SetterPtr const& ws_setter,
CommitGitMap::LoggerPtr const& logger) {
// ensure commit exists, and fetch if needed
auto git_repo = GitRepoRemote::Open(git_cas); // link fake repo to odb
if (not git_repo) {
(*logger)(
fmt::format("Could not open repository {}", repo_root.string()),
/*fatal=*/true);
return;
}
// setup wrapped logger
auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
[logger](auto const& msg, bool fatal) {
(*logger)(fmt::format("While checking commit exists:\n{}", msg),
fatal);
});
auto is_commit_present =
git_repo->CheckCommitExists(repo_info.hash, wrapped_logger);
if (is_commit_present == std::nullopt) {
return;
}
if (not is_commit_present.value()) {
if (repo_info.absent) {
auto tree_id_file =
JustMR::Utils::GetCommitTreeIDFile(repo_info.hash);
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)(fmt::format("Failed to read tree id from file {}",
tree_id_file.string()),
/*fatal=*/true);
return;
}
if (fetch_absent) {
(*ws_setter)(std::pair(
nlohmann::json::array(
{repo_info.ignore_special
? FileRoot::kGitTreeIgnoreSpecialMarker
: FileRoot::kGitTreeMarker,
*resolved_tree_id,
StorageConfig::GitRoot().string()}),
false));
}
else {
(*ws_setter)(std::pair(
nlohmann::json::array(
{repo_info.ignore_special
? FileRoot::kGitTreeIgnoreSpecialMarker
: FileRoot::kGitTreeMarker,
*resolved_tree_id}),
false));
}
return;
}
JustMRProgress::Instance().TaskTracker().Start(repo_info.origin);
// check if commit is known to remote serve service, if asked for an
// absent root
if (serve_api != nullptr) {
if (auto tree_id = serve_api->RetrieveTreeFromCommit(
repo_info.hash, repo_info.subdir, fetch_absent)) {
if (not fetch_absent) {
// set the workspace root as absent
JustMRProgress::Instance().TaskTracker().Stop(
repo_info.origin);
(*ws_setter)(std::pair(
nlohmann::json::array(
{repo_info.ignore_special
? FileRoot::kGitTreeIgnoreSpecialMarker
: FileRoot::kGitTreeMarker,
*tree_id}),
false));
return;
}
// verify if we know the tree already locally
auto wrapped_logger =
std::make_shared<AsyncMapConsumerLogger>(
[logger, tree = *tree_id](auto const& msg,
bool fatal) {
(*logger)(
fmt::format("While verifying presence of "
"tree {}:\n{}",
tree,
msg),
fatal);
});
auto tree_present =
git_repo->CheckTreeExists(*tree_id, wrapped_logger);
if (not tree_present) {
return;
}
if (*tree_present) {
JustMRProgress::Instance().TaskTracker().Stop(
repo_info.origin);
(*ws_setter)(std::pair(
nlohmann::json::array(
{repo_info.ignore_special
? FileRoot::kGitTreeIgnoreSpecialMarker
: FileRoot::kGitTreeMarker,
*tree_id,
StorageConfig::GitRoot().string()}),
false));
return;
}
// try to get the tree from remote execution endpoint
auto digest = ArtifactDigest{*tree_id, 0, /*is_tree=*/true};
if (remote_api != nullptr and local_api != nullptr and
remote_api->RetrieveToCas(
{Artifact::ObjectInfo{.digest = digest,
.type = ObjectType::Tree}},
local_api)) {
JustMRProgress::Instance().TaskTracker().Stop(
repo_info.origin);
// Move tree from CAS to local git storage
auto tmp_dir = JustMR::Utils::CreateTypedTmpDir(
"fetch-absent-root");
if (not tmp_dir) {
(*logger)(
fmt::format(
"Failed to create tmp directory after "
"fetching tree {} for absent commit {}",
repo_info.hash,
*tree_id),
true);
return;
}
if (not local_api->RetrieveToPaths(
{Artifact::ObjectInfo{
.digest = digest,
.type = ObjectType::Tree}},
{tmp_dir->GetPath()})) {
(*logger)(fmt::format("Failed to copy fetchted "
"tree {} to {}",
*tree_id,
tmp_dir->GetPath().string()),
true);
return;
}
CommitInfo c_info{tmp_dir->GetPath(), "tree", *tree_id};
import_to_git_map->ConsumeAfterKeysReady(
ts,
{std::move(c_info)},
[tmp_dir, // keep tmp_dir alive
repo_info,
tree_id,
tree_id_file,
logger,
ws_setter](auto const& values) {
if (not values[0]->second) {
(*logger)("Importing to git failed",
/*fatal=*/true);
return;
}
// Now that we also have the tree, write the
// association.
if (not JustMR::Utils::WriteTreeIDFile(
tree_id_file, *tree_id)) {
(*logger)(
fmt::format("Failed to write tree id "
"{} to file {}",
*tree_id,
tree_id_file.string()),
/*fatal=*/true);
return;
}
// set the workspace root as present
(*ws_setter)(std::pair(
nlohmann::json::array(
{repo_info.ignore_special
? FileRoot::
kGitTreeIgnoreSpecialMarker
: FileRoot::kGitTreeMarker,
*tree_id,
StorageConfig::GitRoot().string()}),
false));
},
[logger, tmp_dir, tree_id](auto const& msg,
bool fatal) {
(*logger)(
fmt::format("While moving tree {} from {} "
"to local git:\n{}",
*tree_id,
tmp_dir->GetPath().string(),
msg),
fatal);
});
return;
}
// just serve should have made the tree available in the
// remote CAS, so log this attempt and revert to network
(*logger)(fmt::format("Tree {} marked as served, but not "
"found on remote",
*tree_id),
/*fatal=*/false);
}
else {
// give warning
(*logger)(
fmt::format("Tree at subdir {} for commit {} could "
"not be served",
repo_info.subdir,
repo_info.hash),
/*fatal=*/false);
}
}
else {
if (not fetch_absent) {
// give warning
(*logger)(fmt::format("Missing serve endpoint for Git "
"repository {} marked absent "
"requires slower network fetch.",
repo_root.string()),
/*fatal=*/false);
}
}
}
// default to fetching it from network
auto tmp_dir = JustMR::Utils::CreateTypedTmpDir("fetch");
if (not tmp_dir) {
(*logger)("Failed to create fetch tmp directory!",
/*fatal=*/true);
return;
}
// setup wrapped logger
auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
[logger](auto const& msg, bool fatal) {
(*logger)(fmt::format("While fetching via tmp repo:\n{}", msg),
fatal);
});
if (not git_repo->FetchViaTmpRepo(tmp_dir->GetPath(),
repo_info.repo_url,
repo_info.branch,
git_bin,
launcher,
wrapped_logger)) {
return;
}
// setup wrapped logger
wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
[logger](auto const& msg, bool fatal) {
(*logger)(fmt::format("While checking commit exists:\n{}", msg),
fatal);
});
// check if commit exists now, after fetch
auto is_commit_present =
git_repo->CheckCommitExists(repo_info.hash, wrapped_logger);
if (not is_commit_present) {
return;
}
if (not *is_commit_present) {
// commit could not be fetched, so fail
(*logger)(fmt::format("Could not fetch commit {} from branch "
"{} for remote {}",
repo_info.hash,
repo_info.branch,
repo_info.repo_url),
/*fatal=*/true);
return;
}
// keep tag
GitOpKey op_key = {.params =
{
repo_root, // target_path
repo_info.hash, // git_hash
"", // branch
"Keep referenced tree alive" // message
},
.op_type = GitOpType::KEEP_TAG};
critical_git_op_map->ConsumeAfterKeysReady(
ts,
{std::move(op_key)},
[git_cas, repo_info, repo_root, fetch_absent, ws_setter, logger](
auto const& values) {
GitOpValue op_result = *values[0];
// check flag
if (not op_result.result) {
(*logger)("Keep tag failed",
/*fatal=*/true);
return;
}
// ensure commit exists, and fetch if needed
auto git_repo =
GitRepoRemote::Open(git_cas); // link fake repo to odb
if (not git_repo) {
(*logger)(fmt::format("Could not open repository {}",
repo_root.string()),
/*fatal=*/true);
return;
}
// setup wrapped logger
auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
[logger](auto const& msg, bool fatal) {
(*logger)(fmt::format("While getting subtree "
"from commit:\n{}",
msg),
fatal);
});
// get tree id and return workspace root
auto subtree = git_repo->GetSubtreeFromCommit(
repo_info.hash, repo_info.subdir, wrapped_logger);
if (not subtree) {
return;
}
// set the workspace root
JustMRProgress::Instance().TaskTracker().Stop(repo_info.origin);
auto root = nlohmann::json::array(
{repo_info.ignore_special
? FileRoot::kGitTreeIgnoreSpecialMarker
: FileRoot::kGitTreeMarker,
*subtree});
if (fetch_absent or not repo_info.absent) {
root.emplace_back(repo_root);
}
(*ws_setter)(std::pair(std::move(root), false));
},
[logger, target_path = repo_root](auto const& msg, bool fatal) {
(*logger)(fmt::format("While running critical Git op "
"KEEP_TAG for target {}:\n{}",
target_path.string(),
msg),
fatal);
});
}
else {
JustMRProgress::Instance().TaskTracker().Start(repo_info.origin);
// setup wrapped logger
auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
[logger](auto const& msg, bool fatal) {
(*logger)(
fmt::format("While getting subtree from commit:\n{}", msg),
fatal);
});
// get tree id and return workspace root
auto subtree = git_repo->GetSubtreeFromCommit(
repo_info.hash, repo_info.subdir, wrapped_logger);
if (not subtree) {
return;
}
// set the workspace root
auto root = nlohmann::json::array(
{repo_info.ignore_special ? FileRoot::kGitTreeIgnoreSpecialMarker
: FileRoot::kGitTreeMarker,
*subtree});
if (fetch_absent or not repo_info.absent) {
root.emplace_back(repo_root);
}
(*ws_setter)(std::pair(std::move(root), true));
}
}
} // namespace
/// \brief Create a CommitGitMap object
auto CreateCommitGitMap(
gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
gsl::not_null<ImportToGitMap*> const& import_to_git_map,
JustMR::PathsPtr const& just_mr_paths,
std::string const& git_bin,
std::vector<std::string> const& launcher,
ServeApi* serve_api,
IExecutionApi* local_api,
IExecutionApi* remote_api,
bool fetch_absent,
std::size_t jobs) -> CommitGitMap {
auto commit_to_git = [critical_git_op_map,
import_to_git_map,
just_mr_paths,
git_bin,
launcher,
serve_api,
local_api,
remote_api,
fetch_absent](auto ts,
auto setter,
auto logger,
auto /* unused */,
auto const& key) {
// get root for repo (making sure that if repo is a path, it is
// absolute)
std::string fetch_repo = key.repo_url;
if (GitURLIsPath(fetch_repo)) {
fetch_repo = std::filesystem::absolute(fetch_repo).string();
}
std::filesystem::path repo_root =
JustMR::Utils::GetGitRoot(just_mr_paths, fetch_repo);
// ensure git repo
// define Git operation to be done
GitOpKey op_key = {
.params =
{
repo_root, // target_path
"", // git_hash
"", // branch
std::nullopt, // message
not just_mr_paths->git_checkout_locations.contains(
fetch_repo) // init_bare
},
.op_type = GitOpType::ENSURE_INIT};
critical_git_op_map->ConsumeAfterKeysReady(
ts,
{std::move(op_key)},
[key,
repo_root,
critical_git_op_map,
import_to_git_map,
git_bin,
launcher,
serve_api,
local_api,
remote_api,
fetch_absent,
ts,
setter,
logger](auto const& values) {
GitOpValue op_result = *values[0];
// check flag
if (not op_result.result) {
(*logger)("Git init failed",
/*fatal=*/true);
return;
}
// setup a wrapped_logger
auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
[logger, target_path = repo_root](auto const& msg,
bool fatal) {
(*logger)(fmt::format("While ensuring commit for "
"repository {}:\n{}",
target_path.string(),
msg),
fatal);
});
EnsureCommit(key,
repo_root,
op_result.git_cas,
critical_git_op_map,
import_to_git_map,
git_bin,
launcher,
serve_api,
local_api,
remote_api,
fetch_absent,
ts,
setter,
wrapped_logger);
},
[logger, target_path = repo_root](auto const& msg, bool fatal) {
(*logger)(fmt::format("While running critical Git op "
"ENSURE_INIT for target {}:\n{}",
target_path.string(),
msg),
fatal);
});
};
return AsyncMapConsumer<GitRepoInfo, std::pair<nlohmann::json, bool>>(
commit_to_git, jobs);
}
|