summaryrefslogtreecommitdiff
path: root/src/buildtool/serve_api/serve_service/target_utils.cpp
blob: 3fd98242cdc7570b1273010b66fceddc5aa3ee17 (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
// 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/buildtool/serve_api/serve_service/target_utils.hpp"

#include <exception>
#include <fstream>
#include <map>
#include <string>
#include <variant>
#include <vector>

#include "fmt/core.h"
#include "nlohmann/json.hpp"
#include "src/buildtool/file_system/file_root.hpp"
#include "src/buildtool/file_system/git_cas.hpp"
#include "src/buildtool/file_system/git_repo.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/utils/cpp/expected.hpp"

auto GetServingRepository(RemoteServeConfig const& serve_config,
                          StorageConfig const& storage_config,
                          std::string const& tree_id,
                          std::shared_ptr<Logger> const& logger)
    -> std::optional<std::filesystem::path> {
    // try the Git cache repository
    auto in_git_cas = GitRepo::IsTreeInRepo(storage_config.GitRoot(), tree_id);
    if (not in_git_cas.has_value()) {
        logger->Emit(LogLevel::Info,
                     "ServeTarget: While checking existence of "
                     "tree {} in repository {}:\n{}",
                     tree_id,
                     storage_config.GitRoot().string(),
                     std::move(in_git_cas).error());
    }
    else if (*in_git_cas) {
        return storage_config.GitRoot();
    }
    // check the known repositories
    for (auto const& path : serve_config.known_repositories) {
        auto in_repo = GitRepo::IsTreeInRepo(path, tree_id);
        if (not in_repo.has_value()) {
            logger->Emit(LogLevel::Info,
                         "ServeTarget: While checking existence of "
                         "tree {} in repository {}:\n{}",
                         tree_id,
                         path.string(),
                         std::move(in_repo).error());
        }
        else if (*in_repo) {
            return path;
        }
    }
    return std::nullopt;  // tree cannot be served
}

auto DetermineRoots(RemoteServeConfig const& serve_config,
                    gsl::not_null<StorageConfig const*> storage_config,
                    std::string const& main_repo,
                    std::filesystem::path const& repo_config_path,
                    gsl::not_null<RepositoryConfig*> const& repository_config,
                    std::shared_ptr<Logger> const& logger)
    -> std::optional<std::string> {
    // parse repository configuration file
    auto repos = nlohmann::json::object();
    try {
        std::ifstream fs(repo_config_path);
        repos = nlohmann::json::parse(fs);
        if (not repos.is_object()) {
            return fmt::format(
                "Repository configuration file {} does not contain a map.",
                repo_config_path.string());
        }
    } catch (std::exception const& ex) {
        return fmt::format("Parsing repository config file {} failed with:\n{}",
                           repo_config_path.string(),
                           ex.what());
    }
    if (not repos.contains(main_repo)) {
        return fmt::format(
            "Repository configuration does not contain expected main "
            "repository {}",
            main_repo);
    }
    // populate RepositoryConfig instance
    for (auto const& [repo, desc] : repos.items()) {
        // root parser
        auto parse_keyword_root =
            [&serve_config, storage_config, &desc = desc, &repo = repo, logger](
                std::string const& keyword) -> expected<FileRoot, std::string> {
            auto it = desc.find(keyword);
            if (it != desc.end()) {
                auto parsed_root =
                    FileRoot::ParseRoot(storage_config, repo, keyword, *it);
                if (not parsed_root) {
                    return unexpected{std::move(parsed_root).error()};
                }
                // check that root has absent-like format
                if (not parsed_root->first.IsAbsent()) {
                    return unexpected{fmt::format(
                        "Expected {} to have absent Git tree format, but "
                        "found {}",
                        keyword,
                        it->dump())};
                }
                // find the serving repository for the root tree
                auto tree_id = *parsed_root->first.GetAbsentTreeId();
                auto repo_path = GetServingRepository(
                    serve_config, *storage_config, tree_id, logger);
                if (not repo_path) {
                    return unexpected{fmt::format(
                        "{} tree {} is not known", keyword, tree_id)};
                }
                // set the root as present
                if (auto root =
                        FileRoot::FromGit(storage_config,
                                          *repo_path,
                                          tree_id,
                                          parsed_root->first.IgnoreSpecial())) {
                    return *std::move(root);
                }
            }
            return unexpected{
                fmt::format("Missing {} for repository {}", keyword, repo)};
        };

        auto ws_root = parse_keyword_root("workspace_root");
        if (not ws_root) {
            return std::move(ws_root).error();
        }
        auto info = RepositoryConfig::RepositoryInfo{*std::move(ws_root)};

        if (auto target_root = parse_keyword_root("target_root")) {
            info.target_root = *std::move(target_root);
        }
        else {
            return std::move(target_root).error();
        }

        if (auto rule_root = parse_keyword_root("rule_root")) {
            info.rule_root = *std::move(rule_root);
        }
        else {
            return std::move(rule_root).error();
        }

        if (auto expression_root = parse_keyword_root("expression_root")) {
            info.expression_root = *std::move(expression_root);
        }
        else {
            return std::move(expression_root).error();
        }

        auto it_bindings = desc.find("bindings");
        if (it_bindings != desc.end()) {
            if (not it_bindings->is_object()) {
                return fmt::format(
                    "bindings has to be a string-string map, but found {}",
                    it_bindings->dump());
            }
            for (auto const& [local_name, global_name] : it_bindings->items()) {
                if (not repos.contains(global_name)) {
                    return fmt::format(
                        "Binding {} for {} in {} does not refer to a "
                        "defined repository.",
                        global_name,
                        local_name,
                        repo);
                }
                info.name_mapping[local_name] = global_name;
            }
        }
        else {
            return fmt::format("Missing bindings for repository {}", repo);
        }

        auto parse_keyword_file_name = [&desc = desc, &repo = repo](
                                           std::string* keyword_file_name,
                                           std::string const& keyword)
            -> expected<std::monostate, std::string> {
            auto it = desc.find(keyword);
            if (it != desc.end()) {
                *keyword_file_name = *it;
                return std::monostate{};
            }
            return unexpected{
                fmt::format("Missing {} for repository {}", keyword, repo)};
        };

        if (auto result = parse_keyword_file_name(&info.target_file_name,
                                                  "target_file_name");
            not result) {
            return std::move(result).error();
        }

        if (auto result =
                parse_keyword_file_name(&info.rule_file_name, "rule_file_name");
            not result) {
            return std::move(result).error();
        }

        if (auto result = parse_keyword_file_name(&info.expression_file_name,
                                                  "expression_file_name");
            not result) {
            return std::move(result).error();
        }

        repository_config->SetInfo(repo, std::move(info));
    }
    // success
    return std::nullopt;
}

auto GetBlobContent(std::filesystem::path const& repo_path,
                    std::string const& tree_id,
                    std::string const& rel_path,
                    std::shared_ptr<Logger> const& logger)
    -> std::optional<std::pair<bool, std::optional<std::string>>> {
    if (auto git_cas = GitCAS::Open(repo_path)) {
        if (auto repo = GitRepo::Open(git_cas)) {
            // check if tree exists
            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,
                                     "ServeTargetVariables: While checking if "
                                     "tree {} exists in repository {}:\n{}",
                                     tree_id,
                                     repo_path.string(),
                                     msg);
                    }
                });
            if (repo->CheckTreeExists(tree_id, wrapped_logger) == true) {
                // get tree entry by path
                if (auto entry_info =
                        repo->GetObjectByPathFromTree(tree_id, rel_path)) {
                    wrapped_logger = std::make_shared<GitRepo::anon_logger_t>(
                        [logger, repo_path, blob_id = entry_info->id](
                            auto const& msg, bool fatal) {
                            if (fatal) {
                                logger->Emit(
                                    LogLevel::Debug,
                                    "ServeTargetVariables: While retrieving "
                                    "blob {} from repository {}:\n{}",
                                    blob_id,
                                    repo_path.string(),
                                    msg);
                            }
                        });
                    // get blob content
                    return repo->TryReadBlob(entry_info->id, wrapped_logger);
                }
                // trace failure to get entry
                logger->Emit(LogLevel::Debug,
                             "ServeTargetVariables: Failed to retrieve entry "
                             "{} in tree {} from repository {}",
                             rel_path,
                             tree_id,
                             repo_path.string());
                return std::pair(false, std::nullopt);  // could not read blob
            }
        }
    }
    return std::nullopt;  // tree not found or errors while retrieving tree
}