summaryrefslogtreecommitdiff
path: root/src/buildtool/execution_api/remote/bazel/bytestream_client.hpp
blob: 89d61d1f81e8ae29a281eb0f25d39629a316c29d (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
// 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.

#ifndef INCLUDED_SRC_BUILDTOOL_EXECUTION_API_REMOTE_BAZEL_BYTESTREAM_CLIENT_HPP
#define INCLUDED_SRC_BUILDTOOL_EXECUTION_API_REMOTE_BAZEL_BYTESTREAM_CLIENT_HPP

#include <cstddef>
#include <cstdint>
#include <fstream>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>  // std::move

#include <grpcpp/grpcpp.h>

#include "google/bytestream/bytestream.grpc.pb.h"
#include "google/bytestream/bytestream.pb.h"
#include "gsl/gsl"
#include "src/buildtool/auth/authentication.hpp"
#include "src/buildtool/common/artifact_blob.hpp"
#include "src/buildtool/common/artifact_digest.hpp"
#include "src/buildtool/common/remote/client_common.hpp"
#include "src/buildtool/common/remote/port.hpp"
#include "src/buildtool/crypto/hash_function.hpp"
#include "src/buildtool/execution_api/common/bytestream_utils.hpp"
#include "src/buildtool/execution_api/common/ids.hpp"
#include "src/buildtool/file_system/object_type.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/logging/logger.hpp"
#include "src/utils/cpp/expected.hpp"
#include "src/utils/cpp/incremental_reader.hpp"
#include "src/utils/cpp/tmp_dir.hpp"

/// Implements client side for google.bytestream.ByteStream service.
class ByteStreamClient {
  public:
    class IncrementalReader {
        friend class ByteStreamClient;

      public:
        /// \brief Read next chunk of data.
        /// \returns empty string if stream finished and std::nullopt on error.
        [[nodiscard]] auto Next() -> std::optional<std::string> {
            google::bytestream::ReadResponse response{};
            if (reader_->Read(&response)) {
                return std::move(*response.mutable_data());
            }

            if (not finished_) {
                auto status = reader_->Finish();
                if (not status.ok()) {
                    logger_->Emit(LogLevel::Debug,
                                  "{}: {}",
                                  static_cast<int>(status.error_code()),
                                  status.error_message());
                    return std::nullopt;
                }
                finished_ = true;
            }
            return std::string{};
        }

      private:
        Logger const* logger_;
        grpc::ClientContext ctx_;
        std::unique_ptr<grpc::ClientReader<google::bytestream::ReadResponse>>
            reader_;
        bool finished_{false};

        IncrementalReader(
            gsl::not_null<google::bytestream::ByteStream::Stub*> const& stub,
            std::string const& instance_name,
            ArtifactDigest const& digest,
            Logger const* logger)
            : logger_{logger} {
            google::bytestream::ReadRequest request{};
            request.set_resource_name(
                ByteStreamUtils::ReadRequest::ToString(instance_name, digest));
            reader_ = stub->Read(&ctx_, request);
        }
    };

    explicit ByteStreamClient(std::string const& server,
                              Port port,
                              gsl::not_null<Auth const*> const& auth) noexcept {
        stub_ = google::bytestream::ByteStream::NewStub(
            CreateChannelWithCredentials(server, port, auth));
    }

    [[nodiscard]] auto IncrementalRead(
        std::string const& instance_name,
        ArtifactDigest const& digest) const noexcept -> IncrementalReader {
        return IncrementalReader{stub_.get(), instance_name, digest, &logger_};
    }

    [[nodiscard]] auto Read(std::string const& instance_name,
                            ArtifactDigest const& digest,
                            TmpDir::Ptr const& temp_space) const noexcept
        -> std::optional<ArtifactBlob> {
        auto temp_file = TmpDir::CreateFile(temp_space, digest.hash());
        if (temp_file == nullptr) {
            return std::nullopt;
        }

        auto reader = IncrementalRead(instance_name, digest);
        try {
            std::ofstream stream{temp_file->GetPath(), std::ios_base::binary};

            auto data = reader.Next();
            while (data.has_value() and not data->empty() and stream.good()) {
                stream << *data;
                data = reader.Next();
            }
            if (not stream.good() or not data.has_value()) {
                return std::nullopt;
            }
        } catch (...) {
            return std::nullopt;
        }

        auto blob = ArtifactBlob::FromTempFile(
            HashFunction{digest.GetHashType()},
            digest.IsTree() ? ObjectType::Tree : ObjectType::File,
            std::move(temp_file));
        if (not blob.has_value() or blob->GetDigest() != digest) {
            return std::nullopt;
        }
        return *std::move(blob);
    }

    [[nodiscard]] auto Write(std::string const& instance_name,
                             ArtifactBlob const& blob) const noexcept -> bool {
        thread_local static std::string uuid{};
        if (uuid.empty()) {
            auto id = CreateProcessUniqueId();
            if (not id) {
                logger_.Emit(LogLevel::Debug,
                             "Failed creating process unique id.");
                return false;
            }
            uuid = CreateUUIDVersion4(*id);
        }

        try {
            grpc::ClientContext ctx;
            google::bytestream::WriteResponse response{};
            auto writer = stub_->Write(&ctx, &response);

            auto const resource_name = ByteStreamUtils::WriteRequest::ToString(
                instance_name, uuid, blob.GetDigest());

            google::bytestream::WriteRequest request{};
            request.set_resource_name(resource_name);
            request.mutable_data()->reserve(ByteStreamUtils::kChunkSize);

            auto const to_read =
                blob.ReadIncrementally(ByteStreamUtils::kChunkSize);
            if (not to_read.has_value()) {
                logger_.Emit(
                    LogLevel::Error,
                    "ByteStreamClient: Failed to create a reader for {}:\n{}",
                    request.resource_name(),
                    to_read.error());
                return false;
            }

            std::size_t pos = 0;
            for (auto it = to_read->begin(); it != to_read->end();) {
                auto const chunk = *it;
                if (not chunk.has_value()) {
                    logger_.Emit(
                        LogLevel::Error,
                        "ByteStreamClient: Failed to read data for {}:\n{}",
                        request.resource_name(),
                        chunk.error());
                    return false;
                }
                *request.mutable_data() = *chunk;

                request.set_write_offset(static_cast<int>(pos));
                request.set_finish_write(pos + chunk->size() >=
                                         blob.GetContentSize());
                if (writer->Write(request)) {
                    pos += chunk->size();
                    ++it;
                }
                else {
                    // According to the docs, quote:
                    // If there is an error or the connection is broken during
                    // the `Write()`, the client should check the status of the
                    // `Write()` by calling `QueryWriteStatus()` and continue
                    // writing from the returned `committed_size`.
                    auto const committed_size =
                        QueryWriteStatus(request.resource_name());
                    if (committed_size <= 0) {
                        logger_.Emit(
                            LogLevel::Warning,
                            "broken stream for upload to resource name {}",
                            request.resource_name());
                        return false;
                    }
                    pos = gsl::narrow<std::size_t>(committed_size);
                    it = to_read->make_iterator(pos);
                }
            }
            if (not writer->WritesDone()) {
                logger_.Emit(LogLevel::Warning,
                             "broken stream for upload to resource name {}",
                             request.resource_name());
                return false;
            }

            auto status = writer->Finish();
            if (not status.ok()) {
                LogStatus(&logger_, LogLevel::Debug, status);
                return false;
            }
            if (gsl::narrow<std::size_t>(response.committed_size()) !=
                blob.GetContentSize()) {
                logger_.Emit(
                    LogLevel::Warning,
                    "Commited size {} is different from the original one {}.",
                    response.committed_size(),
                    blob.GetContentSize());
                return false;
            }
            return true;
        } catch (...) {
            logger_.Emit(LogLevel::Warning, "Caught exception in Write");
            return false;
        }
    }

  private:
    std::unique_ptr<google::bytestream::ByteStream::Stub> stub_;
    Logger logger_{"ByteStreamClient"};

    [[nodiscard]] auto QueryWriteStatus(
        std::string const& resource_name) const noexcept -> std::int64_t {
        grpc::ClientContext ctx;
        google::bytestream::QueryWriteStatusRequest request{};
        request.set_resource_name(resource_name);
        google::bytestream::QueryWriteStatusResponse response{};
        stub_->QueryWriteStatus(&ctx, request, &response);
        return response.committed_size();
    }
};

#endif  // INCLUDED_SRC_BUILDTOOL_EXECUTION_API_REMOTE_BAZEL_BYTESTREAM_CLIENT_HPP