File: RemoteCacheServer.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (410 lines) | stat: -rw-r--r-- 15,023 bytes parent folder | download
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
//===-- RemoteCacheServer.cpp - gRPC Server for Remote Caching Protocol ---===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "llvm/RemoteCachingService/RemoteCacheServer.h"
#include "llvm/RemoteCachingService/RemoteCacheProvider.h"

#include "compilation_caching_cas.grpc.pb.h"
#include "compilation_caching_kv.grpc.pb.h"
#include <grpcpp/grpcpp.h>

using namespace llvm;
using namespace llvm::cas;
using namespace llvm::cas::remote;
using namespace compilation_cache_service::cas::v1;
using namespace compilation_cache_service::keyvalue::v1;

using grpc::Server;
using grpc::ServerAsyncResponseWriter;
using grpc::ServerBuilder;
using grpc::ServerCompletionQueue;
using grpc::ServerContext;
using grpc::Status;

void RemoteCacheProvider::anchor() {}

static GetValueResponse GetValueWithError(Error &&E) {
  GetValueResponse Response;
  Response.set_outcome(GetValueResponse_Outcome_ERROR);
  Response.mutable_error()->set_description(toString(std::move(E)));
  return Response;
}

static PutValueResponse PutValueWithError(Error &&E) {
  PutValueResponse Response;
  Response.mutable_error()->set_description(toString(std::move(E)));
  return Response;
}

static CASLoadResponse CASLoadWithError(Error &&E) {
  CASLoadResponse Response;
  Response.set_outcome(CASLoadResponse_Outcome_ERROR);
  Response.mutable_error()->set_description(toString(std::move(E)));
  return Response;
}

static CASSaveResponse CASSaveWithError(Error &&E) {
  CASSaveResponse Response;
  Response.mutable_error()->set_description(toString(std::move(E)));
  return Response;
}

static CASGetResponse CASGetWithError(Error &&E) {
  CASGetResponse Response;
  Response.set_outcome(CASGetResponse_Outcome_ERROR);
  Response.mutable_error()->set_description(toString(std::move(E)));
  return Response;
}

static CASPutResponse CASPutWithError(Error &&E) {
  CASPutResponse Response;
  Response.mutable_error()->set_description(toString(std::move(E)));
  return Response;
}

static void
GetValueAdapter(const GetValueRequest &Request, RemoteCacheProvider &Provider,
                std::function<void(const GetValueResponse &)> Receiver) {
  Provider.GetValueAsync(
      Request.key(), [Receiver = std::move(Receiver)](
                         Expected<std::optional<std::string>> Response) {
        if (!Response)
          return Receiver(GetValueWithError(Response.takeError()));

        GetValueResponse grpcResponse;
        if (*Response) {
          grpcResponse.set_outcome(GetValueResponse_Outcome_SUCCESS);
          StringRef Value = **Response;
          grpcResponse.mutable_value()->ParseFromArray(Value.data(),
                                                       Value.size());
        } else {
          grpcResponse.set_outcome(GetValueResponse_Outcome_KEY_NOT_FOUND);
        }
        return Receiver(grpcResponse);
      });
}

static void
PutValueAdapter(const PutValueRequest &Request, RemoteCacheProvider &Provider,
                std::function<void(const PutValueResponse &)> Receiver) {
  Provider.PutValueAsync(Request.key(), Request.value().SerializeAsString(),
                         [Receiver = std::move(Receiver)](Error E) {
                           if (E)
                             return Receiver(PutValueWithError(std::move(E)));
                           return Receiver(PutValueResponse());
                         });
}

static void
CASLoadAdapter(const CASLoadRequest &Request, RemoteCacheProvider &Provider,
               std::function<void(const CASLoadResponse &)> Receiver) {
  Provider.CASLoadAsync(
      Request.cas_id().id(), Request.write_to_disk(),
      [Receiver = std::move(Receiver)](
          Expected<RemoteCacheProvider::LoadResponse> Response) {
        if (!Response)
          return Receiver(CASLoadWithError(Response.takeError()));

        CASLoadResponse grpcResponse;
        grpcResponse.set_outcome(CASLoadResponse_Outcome_SUCCESS);
        if (Response->Blob.IsFilePath) {
          grpcResponse.mutable_data()->mutable_blob()->set_file_path(
              std::move(Response->Blob.DataOrPath));
        } else {
          grpcResponse.mutable_data()->mutable_blob()->set_data(
              std::move(Response->Blob.DataOrPath));
        }
        return Receiver(grpcResponse);
      });
}

static void
CASSaveAdapter(const CASSaveRequest &Request, RemoteCacheProvider &Provider,
               std::function<void(const CASSaveResponse &)> Receiver) {
  const CASBytes &grpcBlob = Request.data().blob();
  RemoteCacheProvider::BlobContents Blob{
      grpcBlob.has_file_path(),
      grpcBlob.has_file_path() ? grpcBlob.file_path() : grpcBlob.data()};

  Provider.CASSaveAsync(std::move(Blob), [Receiver = std::move(Receiver)](
                                             Expected<std::string> ID) {
    if (!ID)
      return Receiver(CASSaveWithError(ID.takeError()));
    CASSaveResponse grpcResponse;
    grpcResponse.mutable_cas_id()->set_id(std::move(*ID));
    return Receiver(grpcResponse);
  });
}

static void
CASGetAdapter(const CASGetRequest &Request, RemoteCacheProvider &Provider,
              std::function<void(const CASGetResponse &)> Receiver) {
  Provider.CASGetAsync(
      Request.cas_id().id(), Request.write_to_disk(),
      [Receiver = std::move(Receiver)](
          Expected<RemoteCacheProvider::GetResponse> Response) {
        if (!Response)
          return Receiver(CASGetWithError(Response.takeError()));

        CASGetResponse grpcResponse;
        grpcResponse.set_outcome(CASGetResponse_Outcome_SUCCESS);
        if (Response->Blob.IsFilePath) {
          grpcResponse.mutable_data()->mutable_blob()->set_file_path(
              std::move(Response->Blob.DataOrPath));
        } else {
          grpcResponse.mutable_data()->mutable_blob()->set_data(
              std::move(Response->Blob.DataOrPath));
        }
        for (std::string &Ref : Response->Refs) {
          grpcResponse.mutable_data()->add_references()->set_id(std::move(Ref));
        }
        return Receiver(grpcResponse);
      });
}

static void
CASPutAdapter(const CASPutRequest &Request, RemoteCacheProvider &Provider,
              std::function<void(const CASPutResponse &)> Receiver) {
  const CASBytes &grpcBlob = Request.data().blob();
  RemoteCacheProvider::BlobContents Blob{
      grpcBlob.has_file_path(),
      grpcBlob.has_file_path() ? grpcBlob.file_path() : grpcBlob.data()};
  SmallVector<std::string> Refs;
  Refs.reserve(Request.data().references().size());
  for (auto &Ref : Request.data().references())
    Refs.push_back(Ref.id());

  Provider.CASPutAsync(
      std::move(Blob), std::move(Refs),
      [Receiver = std::move(Receiver)](Expected<std::string> ID) {
        if (!ID)
          return Receiver(CASPutWithError(ID.takeError()));
        CASPutResponse grpcResponse;
        grpcResponse.mutable_cas_id()->set_id(std::move(*ID));
        return Receiver(grpcResponse);
      });
}

/// A gRPC server implementation for the remote cache service protocol. The
/// actual work of storing and retrieving data is done via the provided
/// \p RemoteCacheProvider.
///
/// The server is implemented using asynchronous facilities so execution of a
/// request is not blocking receiving additional requests.
class RemoteCacheServer::Implementation final {
public:
  Implementation(StringRef SocketPath,
                 std::unique_ptr<RemoteCacheProvider> CacheProvider)
      : SocketPath(SocketPath), CacheProvider(std::move(CacheProvider)) {}

  ~Implementation() { Shutdown(); }

  void Start() {
    std::string Address("unix:");
    Address += SocketPath;

    ServerBuilder Builder;
    // Listen on the given address without any authentication mechanism.
    Builder.AddListeningPort(Address, grpc::InsecureServerCredentials());
    Builder.RegisterService(&KVService);
    Builder.RegisterService(&CASService);
    CQ = Builder.AddCompletionQueue();
    // Finally assemble the server.
    Server = Builder.BuildAndStart();
  }

  void Listen() {
    // Proceed to the server's main loop.
    HandleRpcs();
  }

  void Shutdown() {
    Server->Shutdown();
    CQ->Shutdown();
  }

private:
  class CallData {
  public:
    virtual ~CallData() = default;
    virtual void proceed(bool ok) = 0;
  };

  template <typename T> struct RequestTraits {};

  template <> struct RequestTraits<GetValueRequest> {
    using ResponseT = GetValueResponse;
    using ServiceT = KeyValueDB::AsyncService;

    static constexpr auto ProviderFunc = GetValueAdapter;
    static constexpr auto ServiceRequest = &ServiceT::RequestGetValue;
  };

  template <> struct RequestTraits<PutValueRequest> {
    using ResponseT = PutValueResponse;
    using ServiceT = KeyValueDB::AsyncService;

    static constexpr auto ProviderFunc = PutValueAdapter;
    static constexpr auto ServiceRequest = &ServiceT::RequestPutValue;
  };

  template <> struct RequestTraits<CASLoadRequest> {
    using ResponseT = CASLoadResponse;
    using ServiceT = CASDBService::AsyncService;

    static constexpr auto ProviderFunc = CASLoadAdapter;
    static constexpr auto ServiceRequest = &ServiceT::RequestLoad;
  };

  template <> struct RequestTraits<CASSaveRequest> {
    using ResponseT = CASSaveResponse;
    using ServiceT = CASDBService::AsyncService;

    static constexpr auto ProviderFunc = CASSaveAdapter;
    static constexpr auto ServiceRequest = &ServiceT::RequestSave;
  };

  template <> struct RequestTraits<CASGetRequest> {
    using ResponseT = CASGetResponse;
    using ServiceT = CASDBService::AsyncService;

    static constexpr auto ProviderFunc = CASGetAdapter;
    static constexpr auto ServiceRequest = &ServiceT::RequestGet;
  };

  template <> struct RequestTraits<CASPutRequest> {
    using ResponseT = CASPutResponse;
    using ServiceT = CASDBService::AsyncService;

    static constexpr auto ProviderFunc = CASPutAdapter;
    static constexpr auto ServiceRequest = &ServiceT::RequestPut;
  };

  // Class encompasing the state and logic needed to serve a request.
  template <typename RequestT> class RequestHandler final : public CallData {
  public:
    using ResponseT = typename RequestTraits<RequestT>::ResponseT;
    using ServiceT = typename RequestTraits<RequestT>::ServiceT;

    RequestHandler(ServiceT *service, ServerCompletionQueue *cq,
                   RemoteCacheProvider *provider)
        : Service(service), CQ(cq), Provider(provider), Responder(&Ctx),
          Status(CallStatus::Create) {
      // Invoke the serving logic right away.
      proceed(true);
    }

  private:
    void proceed(bool ok) override {
      if (!ok) {
        Status = CallStatus::Finish;
      }

      switch (Status) {
      case CallStatus::Create:
        Status = CallStatus::Process;

        // As part of the initial \p CallStatus::Create state, we *request* that
        // the system starts processing \p RequestT requests. In this request,
        // "this" is the tag uniquely identifying the request (so that different
        // \p CallData instances can serve different requests concurrently), in
        // this case the memory address of this \p CallData instance.
        (Service->*RequestTraits<RequestT>::ServiceRequest)(
            &Ctx, &Request, &Responder, CQ, CQ, this);
        break;

      case CallStatus::Process:
        // Spawn a new \p RequestHandler instance to serve new clients while we
        // process the one for this request. The instance will deallocate itself
        // as part of its \p CallStatus::Finish state.
        new RequestHandler(Service, CQ, Provider);

        // The actual processing.
        Status = CallStatus::Finish;
        RequestTraits<RequestT>::ProviderFunc(
            Request, *Provider, [this](const ResponseT &Response) {
              Responder.Finish(Response, grpc::Status::OK, this);
            });
        break;

      case CallStatus::Finish:
        // Once in the \p CallStatus::Finish state, deallocate ourselves.
        delete this;
      }
    }

    // The means of communication with the gRPC runtime for an asynchronous
    // server.
    ServiceT *Service;
    // The producer-consumer queue for asynchronous server notifications.
    ServerCompletionQueue *CQ;
    RemoteCacheProvider *Provider;

    ServerContext Ctx;
    // What we get from the client.
    RequestT Request;
    // The means to respond back to the client.
    ServerAsyncResponseWriter<ResponseT> Responder;

    // A state machine for processing a request.
    enum class CallStatus { Create, Process, Finish };
    CallStatus Status; // The current serving state.
  };

  // This can be run in multiple threads if needed.
  void HandleRpcs() {
    // Spawn new \p RequestHandler instances to serve new clients. These will
    // get deallocated when they reach \p \p CallStatus::Finish state.
    new RequestHandler<GetValueRequest>(&KVService, CQ.get(),
                                        CacheProvider.get());
    new RequestHandler<PutValueRequest>(&KVService, CQ.get(),
                                        CacheProvider.get());
    new RequestHandler<CASLoadRequest>(&CASService, CQ.get(),
                                       CacheProvider.get());
    new RequestHandler<CASSaveRequest>(&CASService, CQ.get(),
                                       CacheProvider.get());
    new RequestHandler<CASGetRequest>(&CASService, CQ.get(),
                                      CacheProvider.get());
    new RequestHandler<CASPutRequest>(&CASService, CQ.get(),
                                      CacheProvider.get());

    void *tag; // uniquely identifies a request.
    bool ok;
    while (true) {
      // Block waiting to read the next event from the completion queue. The
      // event is uniquely identified by its tag, which in this case is the
      // memory address of a \p CallData instance.
      bool gotEvent = CQ->Next(&tag, &ok);
      if (!gotEvent)
        break;
      static_cast<CallData *>(tag)->proceed(ok);
    }
  }

  std::string SocketPath;
  std::unique_ptr<RemoteCacheProvider> CacheProvider;
  std::unique_ptr<ServerCompletionQueue> CQ;
  KeyValueDB::AsyncService KVService;
  CASDBService::AsyncService CASService;
  std::unique_ptr<Server> Server;
};

RemoteCacheServer::~RemoteCacheServer() = default;

void RemoteCacheServer::Start() { return Impl->Start(); }
void RemoteCacheServer::Listen() { return Impl->Listen(); }
void RemoteCacheServer::Shutdown() { return Impl->Shutdown(); }

RemoteCacheServer::RemoteCacheServer(
    std::unique_ptr<RemoteCacheServer::Implementation> Impl)
    : Impl(std::move(Impl)) {}

RemoteCacheServer::RemoteCacheServer(
    StringRef SocketPath, std::unique_ptr<RemoteCacheProvider> CacheProvider)
    : RemoteCacheServer(std::make_unique<RemoteCacheServer::Implementation>(
          SocketPath, std::move(CacheProvider))) {}