Server.cpp
12 KB
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
//===--- Server.cpp - gRPC-based Remote Index Server ---------------------===//
//
// 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 "Index.pb.h"
#include "index/Index.h"
#include "index/Serialization.h"
#include "index/Symbol.h"
#include "index/remote/marshalling/Marshalling.h"
#include "support/Logger.h"
#include "support/Shutdown.h"
#include "support/ThreadsafeFS.h"
#include "support/Trace.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/VirtualFileSystem.h"
#include <chrono>
#include <grpc++/grpc++.h>
#include <grpc++/health_check_service_interface.h>
#include <memory>
#include <thread>
#include "Index.grpc.pb.h"
namespace clang {
namespace clangd {
namespace remote {
namespace {
static constexpr char Overview[] = R"(
This is an experimental remote index implementation. The server opens Dex and
awaits gRPC lookup requests from the client.
)";
llvm::cl::opt<std::string> IndexPath(llvm::cl::desc("<INDEX FILE>"),
llvm::cl::Positional, llvm::cl::Required);
llvm::cl::opt<std::string> IndexRoot(llvm::cl::desc("<PROJECT ROOT>"),
llvm::cl::Positional, llvm::cl::Required);
llvm::cl::opt<Logger::Level> LogLevel{
"log",
llvm::cl::desc("Verbosity of log messages written to stderr"),
values(clEnumValN(Logger::Error, "error", "Error messages only"),
clEnumValN(Logger::Info, "info", "High level execution tracing"),
clEnumValN(Logger::Debug, "verbose", "Low level details")),
llvm::cl::init(Logger::Info),
};
llvm::cl::opt<std::string> TraceFile(
"trace-file",
llvm::cl::desc("Path to the file where tracer logs will be stored"));
llvm::cl::opt<bool> PrettyPrint{
"pretty",
llvm::cl::desc("Pretty-print JSON output in the trace"),
llvm::cl::init(false),
};
llvm::cl::opt<std::string> ServerAddress(
"server-address", llvm::cl::init("0.0.0.0:50051"),
llvm::cl::desc("Address of the invoked server. Defaults to 0.0.0.0:50051"));
class RemoteIndexServer final : public SymbolIndex::Service {
public:
RemoteIndexServer(clangd::SymbolIndex &Index, llvm::StringRef IndexRoot)
: Index(Index) {
llvm::SmallString<256> NativePath = IndexRoot;
llvm::sys::path::native(NativePath);
ProtobufMarshaller = std::unique_ptr<Marshaller>(new Marshaller(
/*RemoteIndexRoot=*/llvm::StringRef(NativePath),
/*LocalIndexRoot=*/""));
}
private:
grpc::Status Lookup(grpc::ServerContext *Context,
const LookupRequest *Request,
grpc::ServerWriter<LookupReply> *Reply) override {
trace::Span Tracer("LookupRequest");
auto Req = ProtobufMarshaller->fromProtobuf(Request);
if (!Req) {
elog("Can not parse LookupRequest from protobuf: {0}", Req.takeError());
return grpc::Status::CANCELLED;
}
unsigned Sent = 0;
unsigned FailedToSend = 0;
Index.lookup(*Req, [&](const clangd::Symbol &Item) {
auto SerializedItem = ProtobufMarshaller->toProtobuf(Item);
if (!SerializedItem) {
elog("Unable to convert Symbol to protobuf: {0}",
SerializedItem.takeError());
++FailedToSend;
return;
}
LookupReply NextMessage;
*NextMessage.mutable_stream_result() = *SerializedItem;
Reply->Write(NextMessage);
++Sent;
});
LookupReply LastMessage;
LastMessage.set_final_result(true);
Reply->Write(LastMessage);
SPAN_ATTACH(Tracer, "Sent", Sent);
SPAN_ATTACH(Tracer, "Failed to send", FailedToSend);
return grpc::Status::OK;
}
grpc::Status FuzzyFind(grpc::ServerContext *Context,
const FuzzyFindRequest *Request,
grpc::ServerWriter<FuzzyFindReply> *Reply) override {
trace::Span Tracer("FuzzyFindRequest");
auto Req = ProtobufMarshaller->fromProtobuf(Request);
if (!Req) {
elog("Can not parse FuzzyFindRequest from protobuf: {0}",
Req.takeError());
return grpc::Status::CANCELLED;
}
unsigned Sent = 0;
unsigned FailedToSend = 0;
bool HasMore = Index.fuzzyFind(*Req, [&](const clangd::Symbol &Item) {
auto SerializedItem = ProtobufMarshaller->toProtobuf(Item);
if (!SerializedItem) {
elog("Unable to convert Symbol to protobuf: {0}",
SerializedItem.takeError());
++FailedToSend;
return;
}
FuzzyFindReply NextMessage;
*NextMessage.mutable_stream_result() = *SerializedItem;
Reply->Write(NextMessage);
++Sent;
});
FuzzyFindReply LastMessage;
LastMessage.set_final_result(HasMore);
Reply->Write(LastMessage);
SPAN_ATTACH(Tracer, "Sent", Sent);
SPAN_ATTACH(Tracer, "Failed to send", FailedToSend);
return grpc::Status::OK;
}
grpc::Status Refs(grpc::ServerContext *Context, const RefsRequest *Request,
grpc::ServerWriter<RefsReply> *Reply) override {
trace::Span Tracer("RefsRequest");
auto Req = ProtobufMarshaller->fromProtobuf(Request);
if (!Req) {
elog("Can not parse RefsRequest from protobuf: {0}", Req.takeError());
return grpc::Status::CANCELLED;
}
unsigned Sent = 0;
unsigned FailedToSend = 0;
bool HasMore = Index.refs(*Req, [&](const clangd::Ref &Item) {
auto SerializedItem = ProtobufMarshaller->toProtobuf(Item);
if (!SerializedItem) {
elog("Unable to convert Ref to protobuf: {0}",
SerializedItem.takeError());
++FailedToSend;
return;
}
RefsReply NextMessage;
*NextMessage.mutable_stream_result() = *SerializedItem;
Reply->Write(NextMessage);
++Sent;
});
RefsReply LastMessage;
LastMessage.set_final_result(HasMore);
Reply->Write(LastMessage);
SPAN_ATTACH(Tracer, "Sent", Sent);
SPAN_ATTACH(Tracer, "Failed to send", FailedToSend);
return grpc::Status::OK;
}
grpc::Status Relations(grpc::ServerContext *Context,
const RelationsRequest *Request,
grpc::ServerWriter<RelationsReply> *Reply) override {
trace::Span Tracer("RelationsRequest");
auto Req = ProtobufMarshaller->fromProtobuf(Request);
if (!Req) {
elog("Can not parse RelationsRequest from protobuf: {0}",
Req.takeError());
return grpc::Status::CANCELLED;
}
unsigned Sent = 0;
unsigned FailedToSend = 0;
Index.relations(
*Req, [&](const SymbolID &Subject, const clangd::Symbol &Object) {
auto SerializedItem = ProtobufMarshaller->toProtobuf(Subject, Object);
if (!SerializedItem) {
elog("Unable to convert Relation to protobuf: {0}",
SerializedItem.takeError());
++FailedToSend;
return;
}
RelationsReply NextMessage;
*NextMessage.mutable_stream_result() = *SerializedItem;
Reply->Write(NextMessage);
++Sent;
});
RelationsReply LastMessage;
LastMessage.set_final_result(true);
Reply->Write(LastMessage);
SPAN_ATTACH(Tracer, "Sent", Sent);
SPAN_ATTACH(Tracer, "Failed to send", FailedToSend);
return grpc::Status::OK;
}
std::unique_ptr<Marshaller> ProtobufMarshaller;
clangd::SymbolIndex &Index;
};
// Detect changes in \p IndexPath file and load new versions of the index
// whenever they become available.
void hotReload(clangd::SwapIndex &Index, llvm::StringRef IndexPath,
llvm::vfs::Status &LastStatus,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> &FS) {
auto Status = FS->status(IndexPath);
// Requested file is same as loaded index: no reload is needed.
if (!Status || (Status->getLastModificationTime() ==
LastStatus.getLastModificationTime() &&
Status->getSize() == LastStatus.getSize()))
return;
vlog("Found different index version: existing index was modified at {0}, new "
"index was modified at {1}. Attempting to reload.",
LastStatus.getLastModificationTime(), Status->getLastModificationTime());
LastStatus = *Status;
std::unique_ptr<clang::clangd::SymbolIndex> NewIndex = loadIndex(IndexPath);
if (!NewIndex) {
elog("Failed to load new index. Old index will be served.");
return;
}
Index.reset(std::move(NewIndex));
log("New index version loaded. Last modification time: {0}, size: {1} bytes.",
Status->getLastModificationTime(), Status->getSize());
}
void runServerAndWait(clangd::SymbolIndex &Index, llvm::StringRef ServerAddress,
llvm::StringRef IndexPath) {
RemoteIndexServer Service(Index, IndexRoot);
grpc::EnableDefaultHealthCheckService(true);
grpc::ServerBuilder Builder;
Builder.AddListeningPort(ServerAddress.str(),
grpc::InsecureServerCredentials());
Builder.RegisterService(&Service);
std::unique_ptr<grpc::Server> Server(Builder.BuildAndStart());
log("Server listening on {0}", ServerAddress);
std::thread ServerShutdownWatcher([&]() {
static constexpr auto WatcherFrequency = std::chrono::seconds(5);
while (!clang::clangd::shutdownRequested())
std::this_thread::sleep_for(WatcherFrequency);
Server->Shutdown();
});
Server->Wait();
ServerShutdownWatcher.join();
}
} // namespace
} // namespace remote
} // namespace clangd
} // namespace clang
using clang::clangd::elog;
int main(int argc, char *argv[]) {
using namespace clang::clangd::remote;
llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
llvm::sys::SetInterruptFunction(&clang::clangd::requestShutdown);
if (!llvm::sys::path::is_absolute(IndexRoot)) {
llvm::errs() << "Index root should be an absolute path.\n";
return -1;
}
llvm::errs().SetBuffered();
// Don't flush stdout when logging for thread safety.
llvm::errs().tie(nullptr);
clang::clangd::StreamLogger Logger(llvm::errs(), LogLevel);
clang::clangd::LoggingSession LoggingSession(Logger);
llvm::Optional<llvm::raw_fd_ostream> TracerStream;
std::unique_ptr<clang::clangd::trace::EventTracer> Tracer;
if (!TraceFile.empty()) {
std::error_code EC;
TracerStream.emplace(TraceFile, EC,
llvm::sys::fs::FA_Read | llvm::sys::fs::FA_Write);
if (EC) {
TracerStream.reset();
elog("Error while opening trace file {0}: {1}", TraceFile, EC.message());
} else {
// FIXME(kirillbobyrev): Also create metrics tracer to track latency and
// accumulate other request statistics.
Tracer = clang::clangd::trace::createJSONTracer(*TracerStream,
/*PrettyPrint=*/false);
clang::clangd::vlog("Successfully created a tracer.");
}
}
llvm::Optional<clang::clangd::trace::Session> TracingSession;
if (Tracer)
TracingSession.emplace(*Tracer);
clang::clangd::RealThreadsafeFS TFS;
auto FS = TFS.view(llvm::None);
auto Status = FS->status(IndexPath);
if (!Status) {
elog("{0} does not exist.", IndexPath);
return Status.getError().value();
}
auto Index = std::make_unique<clang::clangd::SwapIndex>(
clang::clangd::loadIndex(IndexPath));
if (!Index) {
llvm::errs() << "Failed to open the index.\n";
return -1;
}
std::thread HotReloadThread([&Index, &Status, &FS]() {
llvm::vfs::Status LastStatus = *Status;
static constexpr auto RefreshFrequency = std::chrono::seconds(90);
while (!clang::clangd::shutdownRequested()) {
hotReload(*Index, llvm::StringRef(IndexPath), LastStatus, FS);
std::this_thread::sleep_for(RefreshFrequency);
}
});
runServerAndWait(*Index, ServerAddress, IndexPath);
HotReloadThread.join();
}