summaryrefslogtreecommitdiff
path: root/src/buildtool/execution_api/execution_service/execution_server.cpp
blob: 1b416ec8f7ab6517889938603d7a01ce782240a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// 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/execution_api/execution_service/execution_server.hpp"

#include <algorithm>
#include <fstream>
#include <string>
#include <utility>

#include "fmt/core.h"
#include "src/buildtool/common/artifact_digest.hpp"
#include "src/buildtool/common/artifact_digest_factory.hpp"
#include "src/buildtool/common/protocol_traits.hpp"
#include "src/buildtool/execution_api/execution_service/operation_cache.hpp"
#include "src/buildtool/execution_api/local/local_cas_reader.hpp"
#include "src/buildtool/file_system/file_system_manager.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/storage/garbage_collector.hpp"
#include "src/utils/cpp/hex_string.hpp"
#include "src/utils/cpp/path.hpp"

namespace {
void UpdateTimeStamp(
    gsl::not_null<::google::longrunning::Operation*> const& op) {
    ::google::protobuf::Timestamp t;
    t.set_seconds(
        std::chrono::duration_cast<std::chrono::seconds>(
            std::chrono::high_resolution_clock::now().time_since_epoch())
            .count());
    op->mutable_metadata()->PackFrom(t);
}

[[nodiscard]] auto ToBazelActionResult(
    IExecutionResponse::ArtifactInfos const& artifacts,
    IExecutionResponse::DirSymlinks const& dir_symlinks,
    Storage const& storage) noexcept
    -> expected<bazel_re::ActionResult, std::string>;

[[nodiscard]] auto ToBazelAction(ArtifactDigest const& action_digest,
                                 Storage const& storage) noexcept
    -> expected<::bazel_re::Action, std::string>;

[[nodiscard]] auto ToBazelCommand(bazel_re::Action const& action,
                                  Storage const& storage) noexcept
    -> expected<bazel_re::Command, std::string>;
}  // namespace

auto ExecutionServiceImpl::ToIExecutionAction(
    ::bazel_re::Action const& action,
    ::bazel_re::Command const& command) const noexcept
    -> std::optional<IExecutionAction::Ptr> {
    auto const root_digest = ArtifactDigestFactory::FromBazel(
        storage_config_.hash_function.GetType(), action.input_root_digest());
    if (not root_digest) {
        return std::nullopt;
    }
    std::vector<std::string> const args(command.arguments().begin(),
                                        command.arguments().end());
    std::vector<std::string> const files(command.output_files().begin(),
                                         command.output_files().end());
    std::vector<std::string> const dirs(command.output_directories().begin(),
                                        command.output_directories().end());
    std::map<std::string, std::string> env_vars;
    for (auto const& x : command.environment_variables()) {
        env_vars.insert_or_assign(x.name(), x.value());
    }
    auto execution_action = api_.CreateAction(*root_digest,
                                              args,
                                              command.working_directory(),
                                              files,
                                              dirs,
                                              env_vars,
                                              /*properties=*/{});
    if (execution_action == nullptr) {
        return std::nullopt;
    }

    execution_action->SetCacheFlag(
        action.do_not_cache() ? IExecutionAction::CacheFlag::DoNotCacheOutput
                              : IExecutionAction::CacheFlag::CacheOutput);
    return std::move(execution_action);
}

auto ExecutionServiceImpl::ToBazelExecuteResponse(
    IExecutionResponse::Ptr const& i_execution_response) const noexcept
    -> expected<::bazel_re::ExecuteResponse, std::string> {
    auto artifacts = i_execution_response->Artifacts();
    if (not artifacts) {
        return unexpected{std::move(artifacts).error()};
    }
    auto dir_symlinks = i_execution_response->DirectorySymlinks();
    if (not dir_symlinks) {
        return unexpected{std::move(dir_symlinks).error()};
    }
    auto result = ToBazelActionResult(*std::move(artifacts).value(),
                                      *std::move(dir_symlinks).value(),
                                      storage_);
    if (not result) {
        return unexpected{std::move(result).error()};
    }

    auto action_result = *std::move(result);

    action_result.set_exit_code(i_execution_response->ExitCode());
    if (i_execution_response->HasStdErr()) {
        auto const cas_digest =
            storage_.CAS().StoreBlob(i_execution_response->StdErr(),
                                     /*is_executable=*/false);
        if (not cas_digest) {
            return unexpected{
                fmt::format("Could not store stderr of action {}",
                            i_execution_response->ActionDigest())};
        }
        (*action_result.mutable_stderr_digest()) =
            ArtifactDigestFactory::ToBazel(*cas_digest);
    }

    if (i_execution_response->HasStdOut()) {
        auto const cas_digest =
            storage_.CAS().StoreBlob(i_execution_response->StdOut(),
                                     /*is_executable=*/false);
        if (not cas_digest) {
            return unexpected{
                fmt::format("Could not store stdout of action {}",
                            i_execution_response->ActionDigest())};
        }
        (*action_result.mutable_stdout_digest()) =
            ArtifactDigestFactory::ToBazel(*cas_digest);
    }

    ::bazel_re::ExecuteResponse bazel_response{};
    (*bazel_response.mutable_result()) = std::move(action_result);
    bazel_response.set_cached_result(i_execution_response->IsCached());

    // we run the action locally, so no communication issues should happen
    bazel_response.mutable_status()->set_code(grpc::StatusCode::OK);
    return std::move(bazel_response);
}

void ExecutionServiceImpl::WriteResponse(
    ::bazel_re::ExecuteResponse const& execute_response,
    ::grpc::ServerWriter<::google::longrunning::Operation>* writer,
    ::google::longrunning::Operation&& op) noexcept {
    // send response to the client
    op.mutable_response()->PackFrom(execute_response);
    op.set_done(true);
    UpdateTimeStamp(&op);

    op_cache_.Set(op.name(), op);
    writer->Write(op);
}

auto ExecutionServiceImpl::Execute(
    ::grpc::ServerContext* /*context*/,
    const ::bazel_re::ExecuteRequest* request,
    ::grpc::ServerWriter<::google::longrunning::Operation>* writer)
    -> ::grpc::Status {
    auto const action_digest = ArtifactDigestFactory::FromBazel(
        storage_config_.hash_function.GetType(), request->action_digest());
    if (not action_digest) {
        logger_.Emit(LogLevel::Error, "{}", action_digest.error());
        return grpc::Status{grpc::StatusCode::INTERNAL, action_digest.error()};
    }

    auto const lock = GarbageCollector::SharedLock(storage_config_);
    if (not lock) {
        static constexpr auto kStr = "Could not acquire SharedLock";
        logger_.Emit(LogLevel::Error, "{}", kStr);
        return grpc::Status{grpc::StatusCode::INTERNAL, kStr};
    }

    auto action = ToBazelAction(*action_digest, storage_);
    if (not action) {
        logger_.Emit(LogLevel::Error, "{}", action.error());
        return ::grpc::Status{grpc::StatusCode::INTERNAL,
                              std::move(action).error()};
    }
    auto command = ToBazelCommand(*action, storage_);
    if (not command) {
        logger_.Emit(LogLevel::Error, "{}", command.error());
        return ::grpc::Status{grpc::StatusCode::INTERNAL,
                              std::move(command).error()};
    }
    auto i_execution_action = ToIExecutionAction(*action, *command);
    if (not i_execution_action) {
        auto const str = fmt::format("Could not create action from {}",
                                     action_digest->hash());
        logger_.Emit(LogLevel::Error, "{}", str);
        return ::grpc::Status{grpc::StatusCode::INTERNAL, str};
    }

    logger_.Emit(LogLevel::Info, "Execute {}", action_digest->hash());
    // send initial response to the client
    auto op = ::google::longrunning::Operation{};
    auto const& op_name = request->action_digest().hash();
    op.set_name(op_name);
    op.set_done(false);
    UpdateTimeStamp(&op);
    op_cache_.Set(op_name, op);
    writer->Write(op);
    auto t0 = std::chrono::high_resolution_clock::now();
    auto i_execution_response = i_execution_action->get()->Execute(&logger_);
    auto t1 = std::chrono::high_resolution_clock::now();
    logger_.Emit(
        LogLevel::Trace,
        "Finished execution of {} in {} seconds",
        action_digest->hash(),
        std::chrono::duration_cast<std::chrono::seconds>(t1 - t0).count());

    if (i_execution_response == nullptr) {
        auto const str =
            fmt::format("Failed to execute action {}", action_digest->hash());
        logger_.Emit(LogLevel::Error, "{}", str);
        return ::grpc::Status{grpc::StatusCode::INTERNAL, str};
    }

    auto execute_response = ToBazelExecuteResponse(i_execution_response);
    if (not execute_response) {
        logger_.Emit(LogLevel::Error, "{}", execute_response.error());
        return ::grpc::Status{grpc::StatusCode::INTERNAL,
                              std::move(execute_response).error()};
    }

    // Store the result in action cache
    if (i_execution_response->ExitCode() == 0 and not action->do_not_cache()) {
        if (not storage_.ActionCache().StoreResult(
                *action_digest, execute_response->result())) {
            auto const str =
                fmt::format("Could not store action result for action {}",
                            action_digest->hash());

            logger_.Emit(LogLevel::Error, "{}", str);
            return ::grpc::Status{grpc::StatusCode::INTERNAL, str};
        }
    }

    WriteResponse(*execute_response, writer, std::move(op));
    return ::grpc::Status::OK;
}

auto ExecutionServiceImpl::WaitExecution(
    ::grpc::ServerContext* /*context*/,
    const ::bazel_re::WaitExecutionRequest* request,
    ::grpc::ServerWriter<::google::longrunning::Operation>* writer)
    -> ::grpc::Status {
    auto const& hash = request->name();
    if (not IsHexString(hash)) {
        auto const str = fmt::format("Invalid hash {}", hash);
        logger_.Emit(LogLevel::Error, "{}", str);
        return ::grpc::Status{::grpc::StatusCode::INVALID_ARGUMENT, str};
    }
    logger_.Emit(LogLevel::Trace, "WaitExecution: {}", hash);
    auto op = op_cache_.Query(hash);
    while (op and not op->done()) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        op = op_cache_.Query(hash);
    }
    if (not op) {
        auto const str = fmt::format(
            "Executing action {} not found in internal cache.", hash);
        logger_.Emit(LogLevel::Error, "{}", str);
        return ::grpc::Status{grpc::StatusCode::INTERNAL, str};
    }
    writer->Write(*op);
    logger_.Emit(LogLevel::Trace, "Finished WaitExecution {}", hash);
    return ::grpc::Status::OK;
}

namespace {
[[nodiscard]] auto ToBazelOutputDirectory(std::string path,
                                          ArtifactDigest const& digest,
                                          Storage const& storage) noexcept
    -> expected<bazel_re::OutputDirectory, std::string> {
    ::bazel_re::OutputDirectory out_dir{};
    *(out_dir.mutable_path()) = std::move(path);

    LocalCasReader reader(&storage.CAS());
    if (ProtocolTraits::IsNative(storage.GetHashFunction().GetType())) {
        // In native mode: Check validity of tree entries, otherwise set the
        // digest directly.
        if (not reader.ReadGitTree(digest)) {
            auto const error = fmt::format(
                "Found invalid entry in the Git Tree {}", digest.hash());
            return unexpected{error};
        }
        (*out_dir.mutable_tree_digest()) =
            ArtifactDigestFactory::ToBazel(digest);
    }
    else {
        // In compatible mode: Create a tree digest from directory
        // digest on the fly and set tree digest.
        auto const tree = reader.MakeTree(digest);
        if (not tree) {
            return unexpected{fmt::format("Failed to build bazel Tree for {}",
                                          digest.hash())};
        }

        auto const cas_digest =
            storage.CAS().StoreBlob(tree->SerializeAsString(),
                                    /*is_executable=*/false);
        if (not cas_digest) {
            return unexpected{fmt::format(
                "Failed to add to the storage the bazel Tree for {}",
                digest.hash())};
        }
        (*out_dir.mutable_tree_digest()) =
            ArtifactDigestFactory::ToBazel(*cas_digest);
    }
    return std::move(out_dir);
}

[[nodiscard]] auto ToBazelOutputSymlink(std::string path,
                                        ArtifactDigest const& digest,
                                        Storage const& storage) noexcept
    -> expected<bazel_re::OutputSymlink, std::string> {
    ::bazel_re::OutputSymlink out_link{};
    *(out_link.mutable_path()) = std::move(path);
    // recover the target of the symlink
    auto const cas_path =
        storage.CAS().BlobPath(digest, /*is_executable=*/false);
    if (not cas_path) {
        return unexpected{
            fmt::format("Failed to recover the symlink for {}", digest.hash())};
    }

    auto content = FileSystemManager::ReadFile(*cas_path);
    if (not content) {
        return unexpected{fmt::format(
            "Failed to read the symlink content for {}", digest.hash())};
    }

    // in native mode, check that we do not pass invalid symlinks
    if (ProtocolTraits::IsNative(storage.GetHashFunction().GetType()) and
        not PathIsNonUpwards(*content)) {
        auto const error = fmt::format("Invalid symlink for {}", digest.hash());
        return unexpected{error};
    }

    *(out_link.mutable_target()) = *std::move(content);
    return std::move(out_link);
}

[[nodiscard]] auto ToBazelOutputFile(std::string path,
                                     Artifact::ObjectInfo const& info) noexcept
    -> ::bazel_re::OutputFile {
    ::bazel_re::OutputFile out_file{};
    (*out_file.mutable_path()) = std::move(path);
    (*out_file.mutable_digest()) = ArtifactDigestFactory::ToBazel(info.digest);
    out_file.set_is_executable(IsExecutableObject(info.type));
    return out_file;
}

[[nodiscard]] auto ToBazelActionResult(
    IExecutionResponse::ArtifactInfos const& artifacts,
    IExecutionResponse::DirSymlinks const& dir_symlinks,
    Storage const& storage) noexcept
    -> expected<bazel_re::ActionResult, std::string> {
    bazel_re::ActionResult result{};
    auto& result_files = *result.mutable_output_files();
    auto& result_file_links = *result.mutable_output_file_symlinks();
    auto& result_dirs = *result.mutable_output_directories();
    auto& result_dir_links = *result.mutable_output_directory_symlinks();

    auto const size = static_cast<int>(artifacts.size());
    result_files.Reserve(size);
    result_file_links.Reserve(size);
    result_dirs.Reserve(size);
    result_dir_links.Reserve(size);

    for (auto const& [path, info] : artifacts) {
        if (info.type == ObjectType::Tree) {
            auto out_dir = ToBazelOutputDirectory(path, info.digest, storage);
            if (not out_dir) {
                return unexpected{std::move(out_dir).error()};
            }
            result_dirs.Add(*std::move(out_dir));
        }
        else if (info.type == ObjectType::Symlink) {
            auto out_link = ToBazelOutputSymlink(path, info.digest, storage);
            if (not out_link) {
                return unexpected{std::move(out_link).error()};
            }
            if (dir_symlinks.contains(path)) {
                // directory symlink
                result_dir_links.Add(*std::move(out_link));
            }
            else {
                // file symlinks
                result_file_links.Add(*std::move(out_link));
            }
        }
        else {
            result_files.Add(ToBazelOutputFile(path, info));
        }
    }
    return std::move(result);
}

[[nodiscard]] auto ToBazelAction(ArtifactDigest const& action_digest,
                                 Storage const& storage) noexcept
    -> expected<::bazel_re::Action, std::string> {
    auto const action_path = storage.CAS().BlobPath(action_digest, false);
    if (not action_path) {
        return unexpected{fmt::format("could not retrieve blob {} from cas",
                                      action_digest.hash())};
    }

    ::bazel_re::Action action{};
    if (std::ifstream f(*action_path); not action.ParseFromIstream(&f)) {
        return unexpected{fmt::format("failed to parse action from blob {}",
                                      action_digest.hash())};
    }

    auto const hash_type = storage.GetHashFunction().GetType();
    auto const input_root_digest =
        ArtifactDigestFactory::FromBazel(hash_type, action.input_root_digest());
    if (not input_root_digest) {
        return unexpected{input_root_digest.error()};
    }
    auto const input_root_path =
        ProtocolTraits::IsNative(hash_type)
            ? storage.CAS().TreePath(*input_root_digest)
            : storage.CAS().BlobPath(*input_root_digest,
                                     /*is_executable=*/false);

    if (not input_root_path) {
        return unexpected{
            fmt::format("could not retrieve input root {} from cas",
                        input_root_digest->hash())};
    }
    return std::move(action);
}

[[nodiscard]] auto ToBazelCommand(bazel_re::Action const& action,
                                  Storage const& storage) noexcept
    -> expected<bazel_re::Command, std::string> {
    auto const command_digest = ArtifactDigestFactory::FromBazel(
        storage.GetHashFunction().GetType(), action.command_digest());
    if (not command_digest) {
        return unexpected{command_digest.error()};
    }
    auto const path =
        storage.CAS().BlobPath(*command_digest, /*is_executable=*/false);
    if (not path) {
        return unexpected{fmt::format("Could not retrieve blob {} from cas",
                                      command_digest->hash())};
    }

    ::bazel_re::Command c{};
    if (std::ifstream f(*path); not c.ParseFromIstream(&f)) {
        return unexpected{fmt::format("Failed to parse command from blob {}",
                                      command_digest->hash())};
    }
    return std::move(c);
}
}  // namespace