summaryrefslogtreecommitdiff
path: root/src/other_tools/just_mr/setup.cpp
blob: e4430b7966b80df33108964a176afecd3cd83b99 (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
// 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.

#include "src/other_tools/just_mr/setup.hpp"

#include <filesystem>

#include "nlohmann/json.hpp"
#include "src/buildtool/execution_api/common/execution_api.hpp"
#include "src/buildtool/execution_api/local/local_api.hpp"
#include "src/buildtool/file_system/symlinks_map/resolve_symlinks_map.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/logging/logger.hpp"
#include "src/buildtool/multithreading/task_system.hpp"
#include "src/buildtool/storage/fs_utils.hpp"
#include "src/other_tools/just_mr/exit_codes.hpp"
#include "src/other_tools/just_mr/progress_reporting/progress.hpp"
#include "src/other_tools/just_mr/progress_reporting/progress_reporter.hpp"
#include "src/other_tools/just_mr/setup_utils.hpp"
#include "src/other_tools/just_mr/utils.hpp"
#include "src/other_tools/ops_maps/content_cas_map.hpp"
#include "src/other_tools/ops_maps/critical_git_op_map.hpp"
#include "src/other_tools/ops_maps/git_tree_fetch_map.hpp"
#include "src/other_tools/repo_map/repos_to_setup_map.hpp"
#include "src/other_tools/root_maps/commit_git_map.hpp"
#include "src/other_tools/root_maps/content_git_map.hpp"
#include "src/other_tools/root_maps/distdir_git_map.hpp"
#include "src/other_tools/root_maps/fpath_git_map.hpp"
#include "src/other_tools/root_maps/tree_id_git_map.hpp"

auto MultiRepoSetup(std::shared_ptr<Configuration> const& config,
                    MultiRepoCommonArguments const& common_args,
                    MultiRepoSetupArguments const& setup_args,
                    MultiRepoJustSubCmdsArguments const& just_cmd_args,
                    MultiRepoRemoteAuthArguments const& auth_args,
                    bool interactive,
                    std::string multi_repo_tool_name)
    -> std::optional<std::filesystem::path> {
    // provide report
    Logger::Log(LogLevel::Info, "Performing repositories setup");
    // set anchor dir to setup_root; current dir will be reverted when anchor
    // goes out of scope
    auto cwd_anchor = FileSystemManager::ChangeDirectory(
        common_args.just_mr_paths->setup_root);

    auto repos = (*config)["repositories"];
    if (not repos.IsNotNull()) {
        Logger::Log(LogLevel::Error,
                    "Config: Mandatory key \"repositories\" missing");
        return std::nullopt;
    }
    if (not repos->IsMap()) {
        Logger::Log(LogLevel::Error,
                    "Config: Value for key \"repositories\" is not a map");
        return std::nullopt;
    }

    auto setup_repos =
        std::make_shared<JustMR::SetupRepos>();  // repos to setup and include
    nlohmann::json mr_config{};                  // output config to populate

    auto main = common_args.main;  // get local copy of updated clarg 'main', as
                                   // it might be updated again from config

    // check if config provides main repo name
    if (not main) {
        auto main_from_config = (*config)["main"];
        if (main_from_config.IsNotNull()) {
            if (main_from_config->IsString()) {
                main = main_from_config->String();
            }
            else {
                Logger::Log(
                    LogLevel::Error,
                    "Unsupported value {} for field \"main\" in configuration.",
                    main_from_config->ToString());
            }
        }
    }
    // pass on main that was explicitly set via command line or config
    if (main) {
        mr_config["main"] = *main;
    }
    // get default repos to setup and to include
    JustMR::Utils::DefaultReachableRepositories(repos, setup_repos);
    // check if main is to be taken as first repo name lexicographically
    if (not main and not setup_repos->to_setup.empty()) {
        main = *std::min_element(setup_repos->to_setup.begin(),
                                 setup_repos->to_setup.end());
    }
    // final check on which repos are to be set up
    if (main and not setup_args.sub_all) {
        JustMR::Utils::ReachableRepositories(repos, *main, setup_repos);
    }

    // setup the APIs for archive fetches; only happens if in native mode
    auto remote_api =
        JustMR::Utils::GetRemoteApi(common_args.remote_execution_address,
                                    common_args.remote_serve_address,
                                    auth_args);
    IExecutionApi::Ptr local_api{std::make_unique<LocalApi>()};
    bool remote_compatible{common_args.compatible == true};

    // setup the API for serving roots
    auto serve_api_exists = JustMR::Utils::SetupServeApi(
        common_args.remote_serve_address, auth_args);

    // check configuration of the serve endpoint provided
    if (serve_api_exists) {
        // check the compatibility mode of the serve endpoint
        auto compatible = ServeApi::IsCompatible();
        if (not compatible) {
            Logger::Log(LogLevel::Warning,
                        "Checking compatibility configuration of the provided "
                        "serve endpoint failed.");
            serve_api_exists = false;
        }
        if (*compatible != remote_compatible) {
            Logger::Log(
                LogLevel::Warning,
                "Provided serve endpoint operates in a different compatibility "
                "mode than stated. Serve endpoint ignored.");
            serve_api_exists = false;
        }
        // if we have a remote endpoint explicitly given by the user, it must
        // match what the serve endpoint expects
        if (remote_api and common_args.remote_execution_address and
            not ServeApi::CheckServeRemoteExecution()) {
            return std::nullopt;  // this check logs error on failure
        }
    }

    // setup the required async maps
    auto crit_git_op_ptr = std::make_shared<CriticalGitOpGuard>();
    auto critical_git_op_map = CreateCriticalGitOpMap(crit_git_op_ptr);

    auto content_cas_map =
        CreateContentCASMap(common_args.just_mr_paths,
                            common_args.alternative_mirrors,
                            common_args.ca_info,
                            &critical_git_op_map,
                            serve_api_exists,
                            &(*local_api),
                            (remote_api and not remote_compatible)
                                ? std::make_optional(&(*remote_api))
                                : std::nullopt,
                            common_args.jobs);

    auto import_to_git_map =
        CreateImportToGitMap(&critical_git_op_map,
                             common_args.git_path->string(),
                             *common_args.local_launcher,
                             common_args.jobs);

    auto git_tree_fetch_map =
        CreateGitTreeFetchMap(&critical_git_op_map,
                              &import_to_git_map,
                              common_args.git_path->string(),
                              *common_args.local_launcher,
                              serve_api_exists,
                              &(*local_api),
                              (remote_api and not remote_compatible)
                                  ? std::make_optional(&(*remote_api))
                                  : std::nullopt,
                              false, /* backup_to_remote */
                              common_args.jobs);

    auto resolve_symlinks_map = CreateResolveSymlinksMap();

    auto commit_git_map =
        CreateCommitGitMap(&critical_git_op_map,
                           &import_to_git_map,
                           common_args.just_mr_paths,
                           common_args.alternative_mirrors,
                           common_args.git_path->string(),
                           *common_args.local_launcher,
                           serve_api_exists,
                           &(*local_api),
                           (remote_api and not remote_compatible)
                               ? std::make_optional(&(*remote_api))
                               : std::nullopt,
                           common_args.fetch_absent,
                           common_args.jobs);

    auto content_git_map =
        CreateContentGitMap(&content_cas_map,
                            &import_to_git_map,
                            common_args.just_mr_paths,
                            common_args.alternative_mirrors,
                            common_args.ca_info,
                            &resolve_symlinks_map,
                            &critical_git_op_map,
                            serve_api_exists,
                            (remote_api and not remote_compatible)
                                ? std::make_optional(&(*remote_api))
                                : std::nullopt,
                            common_args.fetch_absent,
                            common_args.jobs);

    auto foreign_file_git_map =
        CreateForeignFileGitMap(&content_cas_map,
                                &import_to_git_map,
                                serve_api_exists,
                                common_args.fetch_absent,
                                common_args.jobs);

    auto fpath_git_map = CreateFilePathGitMap(
        just_cmd_args.subcmd_name,
        &critical_git_op_map,
        &import_to_git_map,
        &resolve_symlinks_map,
        serve_api_exists,
        (remote_api and not remote_compatible)
            ? std::make_optional(&(*remote_api))
            : std::nullopt,
        common_args.jobs,
        multi_repo_tool_name,
        common_args.just_path ? common_args.just_path->string()
                              : kDefaultJustPath);

    auto distdir_git_map =
        CreateDistdirGitMap(&content_cas_map,
                            &import_to_git_map,
                            &critical_git_op_map,
                            serve_api_exists,
                            &(*local_api),
                            (remote_api and not remote_compatible)
                                ? std::make_optional(&(*remote_api))
                                : std::nullopt,
                            common_args.jobs);

    auto tree_id_git_map =
        CreateTreeIdGitMap(&git_tree_fetch_map,
                           &critical_git_op_map,
                           &import_to_git_map,
                           common_args.fetch_absent,
                           serve_api_exists,
                           &(*local_api),
                           (remote_api and not remote_compatible)
                               ? std::make_optional(&(*remote_api))
                               : std::nullopt,
                           common_args.jobs);

    auto repos_to_setup_map = CreateReposToSetupMap(config,
                                                    main,
                                                    interactive,
                                                    &commit_git_map,
                                                    &content_git_map,
                                                    &foreign_file_git_map,
                                                    &fpath_git_map,
                                                    &distdir_git_map,
                                                    &tree_id_git_map,
                                                    common_args.fetch_absent,
                                                    common_args.jobs);

    // set up progress observer
    Logger::Log(LogLevel::Info,
                "Found {} repositories to set up",
                setup_repos->to_setup.size());
    JustMRProgress::Instance().SetTotal(setup_repos->to_setup.size());
    std::atomic<bool> done{false};
    std::condition_variable cv{};
    auto reporter = JustMRProgressReporter::Reporter();
    auto observer =
        std::thread([reporter, &done, &cv]() { reporter(&done, &cv); });

    // Populate workspace_root and TAKE_OVER fields
    bool failed{false};
    {
        TaskSystem ts{common_args.jobs};
        repos_to_setup_map.ConsumeAfterKeysReady(
            &ts,
            setup_repos->to_setup,
            [&mr_config, config, setup_repos, main, interactive](
                auto const& values) {
                nlohmann::json mr_repos{};
                for (auto const& repo : setup_repos->to_setup) {
                    auto i = static_cast<std::size_t>(
                        &repo - &setup_repos->to_setup[0]);  // get index
                    mr_repos[repo] = *values[i];
                }
                // populate ALT_DIRS
                auto repos = (*config)["repositories"];
                if (repos.IsNotNull()) {
                    for (auto const& repo : setup_repos->to_include) {
                        auto desc = repos->Get(repo, Expression::none_t{});
                        if (desc.IsNotNull()) {
                            if (not((main and (repo == *main)) and
                                    interactive)) {
                                for (auto const& key : kAltDirs) {
                                    auto val =
                                        desc->Get(key, Expression::none_t{});
                                    if (val.IsNotNull() and
                                        not((main and val->IsString() and
                                             (val->String() == *main)) and
                                            interactive)) {
                                        mr_repos[repo][key] =
                                            mr_repos[val->String()]
                                                    ["workspace_root"];
                                    }
                                }
                            }
                        }
                    }
                }
                // retain only the repos we need
                for (auto const& repo : setup_repos->to_include) {
                    mr_config["repositories"][repo] = mr_repos[repo];
                }
            },
            [&failed, interactive, multi_repo_tool_name](auto const& msg,
                                                         bool fatal) {
                Logger::Log(fatal ? LogLevel::Error : LogLevel::Warning,
                            "While performing {} {}:\n{}",
                            multi_repo_tool_name,
                            interactive ? "setup-env" : "setup",
                            msg);
                failed = failed or fatal;
            });
    }

    // close progress observer
    done = true;
    cv.notify_all();
    observer.join();

    if (failed) {
        return std::nullopt;
    }
    // if successful, return the output config
    return StorageUtils::AddToCAS(mr_config.dump(2));
}