-
Notifications
You must be signed in to change notification settings - Fork 350
Expand file tree
/
Copy pathEdenServer.cpp
More file actions
3297 lines (3004 loc) · 123 KB
/
EdenServer.cpp
File metadata and controls
3297 lines (3004 loc) · 123 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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#include "eden/fs/service/EdenServer.h"
#include <cpptoml.h>
#include <algorithm>
#include <chrono>
#include <sys/stat.h>
#include <fstream>
#include <functional>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include "eden/fs/service/HeartbeatManager.h"
#include <fb303/ServiceData.h>
#include <fmt/core.h>
#include <folly/Exception.h>
#include <folly/FileUtil.h>
#include <folly/SocketAddress.h>
#include <folly/json/json.h>
#ifdef __APPLE__
#include <folly/Subprocess.h> // @manual
#endif
#include <folly/chrono/Conv.h>
#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/thread_factory/NamedThreadFactory.h>
#include <folly/io/async/AsyncSignalHandler.h>
#include <folly/io/async/HHWheelTimer.h>
#include <folly/logging/xlog.h>
#include <folly/portability/SysTypes.h>
#include <folly/stop_watch.h>
#include <gflags/gflags.h>
#include <thrift/lib/cpp/concurrency/ThreadManager.h>
#include <thrift/lib/cpp2/async/ServerPublisherStream.h>
#include <thrift/lib/cpp2/async/ServerStream.h>
#include <thrift/lib/cpp2/server/ParallelConcurrencyController.h>
#include <thrift/lib/cpp2/server/RoundRobinRequestPile.h>
#include <thrift/lib/cpp2/server/ThriftProcessor.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <csignal>
#include "common/network/Hostname.h"
#include "eden/common/telemetry/RequestMetricsScope.h"
#include "eden/common/telemetry/SessionInfo.h"
#include "eden/common/telemetry/StructuredLoggerFactory.h"
#include "eden/common/utils/EnumValue.h"
#include "eden/common/utils/FaultInjector.h"
#include "eden/common/utils/FileUtils.h"
#include "eden/common/utils/PathFuncs.h"
#include "eden/common/utils/ProcessInfoCache.h"
#include "eden/common/utils/TimeUtil.h"
#include "eden/common/utils/UnboundedQueueExecutor.h"
#include "eden/common/utils/UserInfo.h"
#include "eden/fs/config/CheckoutConfig.h"
#include "eden/fs/config/MountProtocol.h"
#include "eden/fs/config/TomlConfig.h"
#include "eden/fs/inodes/EdenMount.h"
#include "eden/fs/inodes/FileInode.h"
#include "eden/fs/inodes/InodeAccessLogger.h"
#include "eden/fs/inodes/InodeBase.h"
#include "eden/fs/inodes/InodeMap.h"
#include "eden/fs/inodes/ServerState.h"
#include "eden/fs/inodes/TreeInode.h"
#include "eden/fs/journal/Journal.h"
#include "eden/fs/nfs/NfsServer.h"
#include "eden/fs/notifications/NullNotifier.h"
#include "eden/fs/privhelper/PrivHelper.h"
#include "eden/fs/service/EdenCPUThreadPool.h"
#include "eden/fs/service/EdenServiceHandler.h"
#include "eden/fs/service/StartupLogger.h"
#include "eden/fs/service/StartupStatusSubscriber.h"
#include "eden/fs/service/ThriftStreamStartupStatusSubscriber.h"
#include "eden/fs/service/ThriftUtil.h"
#include "eden/fs/service/UsageService.h"
#include "eden/fs/service/gen-cpp2/eden_types.h"
#include "eden/fs/store/BackingStoreLogger.h"
#include "eden/fs/store/BlobCache.h"
#include "eden/fs/store/EmptyBackingStore.h"
#include "eden/fs/store/LocalStore.h"
#include "eden/fs/store/MemoryLocalStore.h"
#include "eden/fs/store/ObjectStore.h"
#include "eden/fs/store/RocksDbLocalStore.h"
#include "eden/fs/store/SqliteLocalStore.h"
#include "eden/fs/store/TreeCache.h"
#include "eden/fs/store/hg/SaplingBackingStore.h"
#include "eden/fs/takeover/TakeoverData.h"
#include "eden/fs/telemetry/EdenStats.h"
#include "eden/fs/telemetry/EdenStructuredLogger.h"
#include "eden/fs/telemetry/IScribeLogger.h"
#include "eden/fs/telemetry/LogEvent.h"
#include "eden/fs/utils/Clock.h"
#include "eden/fs/utils/EdenError.h"
#include "eden/fs/utils/EdenTaskQueue.h"
#include "eden/fs/utils/FsChannelTypes.h"
#include "eden/fs/utils/NfsSocket.h"
#include "eden/fs/utils/NotImplemented.h"
#include "eden/fs/utils/ProcUtil.h"
#ifdef EDEN_HAVE_USAGE_SERVICE
#include "eden/fs/service/facebook/EdenFSSmartPlatformServiceEndpoint.h" // @manual
#endif
#ifdef EDEN_HAVE_SERVER_OBSERVER
#include "common/fb303/cpp/ThreadPoolExecutorCounters.h" // @manual
#include "eden/fs/service/facebook/ServerObserver.h" // @manual
#endif
#ifndef _WIN32
#include <sys/wait.h>
#include "eden/fs/fuse/FuseChannel.h"
#include "eden/fs/inodes/Overlay.h"
#include "eden/fs/notifications/CommandNotifier.h"
#include "eden/fs/takeover/TakeoverClient.h"
#include "eden/fs/takeover/TakeoverServer.h"
#endif
#ifdef _WIN32
#include "eden/fs/notifications/WindowsNotifier.h" // @manual
#endif // !_WIN32
DEFINE_bool(
debug,
false,
"run fuse in debug mode"); // TODO: remove; no longer needed
DEFINE_bool(
takeover,
false,
"If another edenfs process is already running, "
"attempt to gracefully takeover its mount points.");
DEFINE_bool(
enable_fault_injection,
false,
"Enable the fault injection framework.");
#define DEFAULT_STORAGE_ENGINE "rocksdb"
#define SUPPORTED_STORAGE_ENGINES "rocksdb|sqlite|memory"
DEFINE_string(
local_storage_engine_unsafe,
"",
"Select storage engine. " DEFAULT_STORAGE_ENGINE
" is the default. "
"possible choices are (" SUPPORTED_STORAGE_ENGINES
"). "
"memory is currently very dangerous as you will "
"lose state across restarts and graceful restarts! "
"This flag will only be used on the first invocation");
DEFINE_int64(
start_delay_minutes,
10,
"Initial delay before first background inode unload");
DEFINE_int64(
unload_age_minutes,
6 * 60,
"Minimum age of the inodes to be unloaded in background");
using apache::thrift::ThriftServer;
using folly::Future;
using folly::makeFuture;
using folly::makeFutureWith;
using folly::StringPiece;
using folly::Unit;
using std::make_shared;
using std::optional;
using std::shared_ptr;
using std::string;
using namespace std::chrono_literals;
namespace {
using namespace facebook::eden;
std::shared_ptr<Notifier> getPlatformNotifier(
std::shared_ptr<ReloadableConfig> config,
std::shared_ptr<StructuredLogger> logger,
std::string version) {
#if defined(_WIN32)
/*
* If the E-Menu is disabled, we should create a Null Notifier
* that no-ops when EdenFS attempts to send notifications
* through it.
*/
if (config->getEdenConfig()->enableEdenMenu.getValue()) {
/*
* The startTime we're passing will be slightly different than the actual
* start time... However, this doesn't matter too much. We will already be
* showing a slightly incorrect uptime because the E-Menu won't update the
* uptime until the user re-clicks on the "About EdenFS" menu option
*/
try {
auto notifier = std::make_shared<WindowsNotifier>(
config, logger, version, std::chrono::steady_clock::now());
notifier->initialize();
return notifier;
} catch (const std::exception& ex) {
auto reason = folly::exceptionStr(ex);
XLOGF(WARN, "Couldn't start E-Menu: {}", reason);
logger->logEvent(EMenuStartupFailure{reason.toStdString()});
}
}
return std::make_shared<NullNotifier>(config);
#else
(void)version;
(void)logger;
return std::make_shared<CommandNotifier>(config);
#endif // _WIN32
}
constexpr StringPiece kRocksDBPath{"storage/rocks-db"};
constexpr StringPiece kSqlitePath{"storage/sqlite.db"};
constexpr StringPiece kSlStorePrefix{"store.sapling"};
#ifndef _WIN32
constexpr StringPiece kFuseRequestPrefix{"fuse"};
#endif
#ifdef __APPLE__
constexpr StringPiece kNFSStatPrefix{"nfs"};
#endif
constexpr StringPiece kStateConfig{"config.toml"};
std::optional<std::string> getUnixDomainSocketPath(
const folly::SocketAddress& address) {
return AF_UNIX == address.getFamily() ? std::make_optional(address.getPath())
: std::nullopt;
}
#ifdef __APPLE__
folly::Try<folly::dynamic> collectNFSUtilStats() {
try {
SpawnedProcess::Options opts;
opts.pipeStdout();
opts.pipeStderr();
auto nfsStatProc =
SpawnedProcess({"nfsstat", "-f", "JSON"}, std::move(opts));
std::string nfsStatOutputString = nfsStatProc.communicate().first;
nfsStatProc.waitTimeout(1s);
return folly::Try<folly::dynamic>(folly::parseJson(nfsStatOutputString));
} catch (const std::exception& e) {
return folly::Try<folly::dynamic>(e);
}
}
#endif
std::string getCounterNameForImportMetric(
RequestMetricsScope::RequestStage stage,
RequestMetricsScope::RequestMetric metric,
std::optional<SaplingBackingStore::SaplingImportObject> object =
std::nullopt) {
if (object.has_value()) {
// base prefix . stage . object . metric
return folly::to<std::string>(
kSlStorePrefix,
".",
RequestMetricsScope::stringOfHgImportStage(stage),
".",
SaplingBackingStore::stringOfSaplingImportObject(object.value()),
".",
RequestMetricsScope::stringOfRequestMetric(metric));
}
// base prefix . stage . metric
return folly::to<std::string>(
kSlStorePrefix,
".",
RequestMetricsScope::stringOfHgImportStage(stage),
".",
RequestMetricsScope::stringOfRequestMetric(metric));
}
#ifndef _WIN32
std::string getCounterNameForFuseRequests(
RequestMetricsScope::RequestStage stage,
RequestMetricsScope::RequestMetric metric,
const EdenMount* mount) {
auto mountName = basename(mount->getPath().view());
// prefix . mount . stage . metric
return folly::to<std::string>(
kFuseRequestPrefix,
".",
mountName,
".",
RequestMetricsScope::stringOfFuseRequestStage(stage),
".",
RequestMetricsScope::stringOfRequestMetric(metric));
}
#endif
#ifdef __linux__
// **not safe to call this function from a fuse thread**
// this gets the kernels view of the number of pending requests, to do this, it
// stats the fuse mount root in the filesystem which could call into the FUSE
// daemon which could cause a deadlock.
size_t getNumberPendingFuseRequests(const EdenMount* mount) {
constexpr StringPiece kFuseInfoDir{"/sys/fs/fuse/connections"};
constexpr StringPiece kFusePendingRequestFile{"waiting"};
auto mount_path = mount->getPath().c_str();
struct stat file_metadata;
folly::checkUnixError(
lstat(mount_path, &file_metadata),
"unable to get FUSE device number for mount ",
basename(mount->getPath().view()));
auto pending_request_path = folly::to<std::string>(
kFuseInfoDir,
kDirSeparator,
file_metadata.st_dev,
kDirSeparator,
kFusePendingRequestFile);
auto pending_requests = readFile(canonicalPath(pending_request_path));
return pending_requests.hasValue()
? folly::to<size_t>(pending_requests.value())
: 0;
}
#endif // __linux__
std::shared_ptr<folly::Executor> makeCheckoutRevisionThreads(
bool useCheckoutExecutor,
std::shared_ptr<const EdenConfig>& edenConfig) {
if (useCheckoutExecutor) {
return std::make_shared<UnboundedQueueExecutor>(
edenConfig->numCheckoutThreads.getValue(),
"CheckoutRevisionThreadPool");
}
return nullptr;
}
} // namespace
namespace facebook::eden {
class EdenServer::ThriftServerEventHandler
: public apache::thrift::server::TServerEventHandler,
public folly::AsyncSignalHandler {
public:
explicit ThriftServerEventHandler(EdenServer* edenServer)
: AsyncSignalHandler{nullptr},
edenServer_{edenServer},
stoppingFromSignal_{false} {}
void preServe(const folly::SocketAddress* address) override {
if (edenServer_->getServerState()
->getEdenConfig()
->thriftUseCustomPermissionChecking.getValue()) {
if (auto path = getUnixDomainSocketPath(*address)) {
folly::checkUnixError(
chmod(path->c_str(), 0777), "failed to chmod ", *path, " to 777");
}
}
// preServe() will be called from the thrift server thread once when it is
// about to start serving.
//
// Register for SIGINT and SIGTERM. We do this in preServe() so we can use
// the thrift server's EventBase to process the signal callbacks.
auto eventBase = folly::EventBaseManager::get()->getEventBase();
attachEventBase(eventBase);
registerSignalHandler(SIGINT);
registerSignalHandler(SIGTERM);
#ifndef _WIN32
registerSignalHandler(SIGCHLD);
#endif
runningPromise_.setValue();
}
void signalReceived(int sig) noexcept override {
switch (sig) {
#ifndef _WIN32
case SIGCHLD:
XLOG(DBG4, "got SIGCHLD");
{
// Clean up zombie processes (ex. `sl debugrefreshconfig`).
int status;
pid_t pid;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
XLOGF(DBG5, "waited pid {} status {}", pid, status);
}
}
return;
#endif
case SIGINT:
case SIGTERM:
if (stoppingFromSignal_) {
XLOGF(INFO, "already stopping due to signal {}", sig);
} else {
stoppingFromSignal_ = true;
XLOGF(INFO, "stopping due to signal {}", sig);
auto shutdownTimeout = edenServer_->getServerState()
->getEdenConfig()
->sigtermShutdownTimeout.getValue();
if (sig == SIGINT || shutdownTimeout.count() == 0) {
// Unregister signal handler if either:
// - sig is SIGINT (this way, the process exits immediately when
// you mash ctrl-c).
// - shutdownTimeout is disabled.
//
// Unregistering the signal handler causes us to exit immediately
// via default signal handling the next time we get the signal.
XLOGF(INFO, "unregistering signal handler for signal {}", sig);
unregisterSignalHandler(sig);
} else {
// Otherwise we are using shutdownTimeout. Schedule a call to
// _exit() after the timeout.
XLOGF(
INFO,
"scheduling _exit() if not done shutting down in {}",
durationToString(shutdownTimeout));
edenServer_->getMainEventBase()->runAfterDelay(
[sig, shutdownTimeout] {
XLOGF(
INFO,
"_exit()ing after {} timeout on signal {}",
durationToString(shutdownTimeout),
sig);
folly::LoggerDB::get().flushAllHandlers();
_exit(1);
},
std::chrono::duration_cast<std::chrono::milliseconds>(
shutdownTimeout)
.count());
}
#ifndef _WIN32
// Record the signal that caused daemon to
// stop. The next edenFS startup record this
// signal in the silent daemon exit logger
edenServer_->createDaemonExitSignalFile(sig);
#endif
// Stop the server.
edenServer_->stop();
}
}
}
/**
* Return a Future that will be fulfilled once the thrift server is bound to
* its socket and is ready to accept connections.
*/
folly::SemiFuture<Unit> getThriftRunningFuture() {
return runningPromise_.getSemiFuture();
}
private:
EdenServer* edenServer_{nullptr};
folly::Promise<Unit> runningPromise_;
bool stoppingFromSignal_;
};
static constexpr folly::StringPiece kNfsReadCount60{"nfs.read_us.count.60"};
static constexpr folly::StringPiece kNfsReadDirCount60{
"nfs.readdir_us.count.60"};
static constexpr folly::StringPiece kNfsReadDirPlusCount60{
"nfs.readdirplus_us.count.60"};
static constexpr folly::StringPiece kFsChannelTaskCount{"fs.task.count"};
static constexpr folly::StringPiece kMemoryVmRssBytes{"memory_vm_rss_bytes"};
#ifdef __APPLE__
static constexpr folly::StringPiece kMemoryCompressedBytes{
"memory_compressed_bytes"};
static constexpr folly::StringPiece kMemoryFootprintBytes{
"memory_footprint_bytes"};
#endif
EdenServer::EdenServer(
std::vector<std::string> originalCommandLine,
UserInfo userInfo,
EdenStatsPtr edenStats,
SessionInfo sessionInfo,
std::unique_ptr<PrivHelper> privHelper,
std::shared_ptr<const EdenConfig> edenConfig,
ActivityRecorderFactory activityRecorderFactory,
BackingStoreFactory* backingStoreFactory,
std::shared_ptr<IScribeLogger> scribeLogger,
std::shared_ptr<StartupStatusChannel> startupStatusChannel,
std::string version)
: originalCommandLine_{std::move(originalCommandLine)},
edenDir_{edenConfig->edenDir.getValue()},
activityRecorderFactory_{std::move(activityRecorderFactory)},
backingStoreFactory_{backingStoreFactory},
config_{std::make_shared<ReloadableConfig>(edenConfig)},
mountPoints_{std::make_shared<folly::Synchronized<MountMap>>(
MountMap{kPathMapDefaultCaseSensitive})},
// Store a pointer to the EventBase that will be used to drive
// the main thread. The runServer() code will end up driving this
// EventBase.
mainEventBase_{folly::EventBaseManager::get()->getEventBase()},
structuredLogger_{
makeDefaultStructuredLogger<EdenStructuredLogger, EdenStatsPtr>(
edenConfig->scribeLogger.getValue(),
edenConfig->scribeCategory.getValue(),
sessionInfo,
edenStats.copy())},
notificationsStructuredLogger_{
makeDefaultStructuredLogger<EdenStructuredLogger, EdenStatsPtr>(
edenConfig->scribeLogger.getValue(),
edenConfig->notificationsScribeCategory.getValue(),
sessionInfo,
edenStats.copy())},
heartbeatManager_{
std::make_unique<HeartbeatManager>(edenDir_, structuredLogger_)},
serverState_{make_shared<ServerState>(
std::move(userInfo),
std::move(edenStats),
std::move(sessionInfo),
std::move(privHelper),
std::make_shared<EdenCPUThreadPool>(
edenConfig->edenCpuPoolNumThreads.getValue()),
std::make_shared<UnboundedQueueExecutor>(
edenConfig->numFsChannelThreads.getValue(),
"FsChannelThreadPool"),
std::make_shared<UnixClock>(),
std::make_shared<ProcessInfoCache>(),
structuredLogger_,
notificationsStructuredLogger_,
std::move(scribeLogger),
config_,
*edenConfig,
mainEventBase_,
getPlatformNotifier(config_, structuredLogger_, version),
FLAGS_enable_fault_injection)},
blobCache_{BlobCache::create(
serverState_->getReloadableConfig(),
serverState_->getStats().copy())},
treeCache_{TreeCache::create(
serverState_->getReloadableConfig(),
serverState_->getStats().copy())},
version_{std::move(version)},
thriftUseResourcePools_{edenConfig->thriftUseResourcePools.getValue()},
thriftUseSerialExecution_{
edenConfig->thriftUseSerialExecution.getValue()},
thriftUseCheckoutExecutor_{
edenConfig->thriftUseCheckoutExecutor.getValue()},
checkoutRevisionExecutor_{
makeCheckoutRevisionThreads(thriftUseCheckoutExecutor_, edenConfig)},
progressManager_{
std::make_unique<folly::Synchronized<EdenServer::ProgressManager>>()},
startupStatusChannel_{std::move(startupStatusChannel)} {
auto counters = fb303::ServiceData::get()->getDynamicCounters();
registerInodePopulationReportsCallback();
for (auto stage : RequestMetricsScope::requestStages) {
for (auto metric : RequestMetricsScope::requestMetrics) {
for (auto object : SaplingBackingStore::saplingImportObjects) {
auto counterName = getCounterNameForImportMetric(stage, metric, object);
counters->registerCallback(counterName, [this, stage, object, metric] {
auto individual_counters = this->collectSaplingBackingStoreCounters(
[stage, object, metric](const SaplingBackingStore& store) {
return store.getImportMetric(stage, object, metric);
});
return RequestMetricsScope::aggregateMetricCounters(
metric, individual_counters);
});
}
auto summaryCounterName = getCounterNameForImportMetric(stage, metric);
counters->registerCallback(summaryCounterName, [this, stage, metric] {
std::vector<size_t> individual_counters;
for (auto object : SaplingBackingStore::saplingImportObjects) {
auto more_counters = this->collectSaplingBackingStoreCounters(
[stage, object, metric](const SaplingBackingStore& store) {
return store.getImportMetric(stage, object, metric);
});
individual_counters.insert(
individual_counters.end(),
more_counters.begin(),
more_counters.end());
}
return RequestMetricsScope::aggregateMetricCounters(
metric, individual_counters);
});
}
}
counters->registerCallback(kFsChannelTaskCount, [this] {
auto fsChannelExecutor = this->getServerState()->getFsChannelThreadPool();
if (auto ex = std::dynamic_pointer_cast<folly::CPUThreadPoolExecutor>(
fsChannelExecutor)) {
return ex->getTaskQueueSize();
}
if (auto ex = std::dynamic_pointer_cast<UnboundedQueueExecutor>(
fsChannelExecutor)) {
return ex->getTaskQueueSize();
}
return (size_t)0;
});
counters->registerCallback(kMemoryVmRssBytes, [] {
auto memoryStats = facebook::eden::proc_util::readMemoryStats();
if (memoryStats) {
return memoryStats->resident;
} else {
return (size_t)0;
}
});
#ifdef __APPLE__
// On macOS, export extra memory counters
counters->registerCallback(kMemoryCompressedBytes, [] {
auto memoryStats = facebook::eden::proc_util::readMemoryStats();
if (memoryStats && memoryStats->compressed) {
return memoryStats->compressed.value();
} else {
return (size_t)0;
}
});
counters->registerCallback(kMemoryFootprintBytes, [] {
auto memoryStats = facebook::eden::proc_util::readMemoryStats();
if (memoryStats && memoryStats->footprint) {
return memoryStats->footprint.value();
} else {
return (size_t)0;
}
});
// On macOS, export the NFS clients/servers counters
if (config_->getEdenConfig()->updateNFSStatsInterval.getValue() > 0ms) {
auto result = collectNFSUtilStats();
if (result.hasValue()) {
for (const auto& nfsStatsCounter : kNfsStatsToEdenStatsMap_) {
auto counterName = mapCounterNameForNFSStat(nfsStatsCounter);
if (counterName.has_value()) {
counters->registerCallback(
counterName.value(), [this, nfsStatsCounter] {
auto result =
this->getNFSStatCounterValue(nfsStatsCounter.first);
if (result.has_value()) {
return result.value();
} else {
return 0LL;
}
});
} else {
// This is not an error, just log it and continue.
// This only happen on registration time, not during runtime per
// counter. It notify us that we have a NFS counter in the map that
// is not reported by Apple.
XLOGF(
DFATAL,
"macOS doesn't report any stat for: {}",
nfsStatsCounter.first);
}
}
} else {
auto error = result.exception();
// This is not a fatal error, just log it and continue.
// This only happen on registration time, not during runtime per
// counter.
XLOGF(
ERR,
"Failed to collect NFS clients/servers counters: {}",
error.what());
}
}
#endif
}
EdenServer::~EdenServer() {
auto counters = fb303::ServiceData::get()->getDynamicCounters();
unregisterInodePopulationReportsCallback();
for (auto stage : RequestMetricsScope::requestStages) {
for (auto metric : RequestMetricsScope::requestMetrics) {
for (auto object : SaplingBackingStore::saplingImportObjects) {
auto counterName = getCounterNameForImportMetric(stage, metric, object);
counters->unregisterCallback(counterName);
}
auto summaryCounterName = getCounterNameForImportMetric(stage, metric);
counters->unregisterCallback(summaryCounterName);
}
}
counters->unregisterCallback(kFsChannelTaskCount);
#ifdef __APPLE__
counters->unregisterCallback(kMemoryCompressedBytes);
counters->unregisterCallback(kMemoryFootprintBytes);
for (const auto& nfsStatsCounter : kNfsStatsToEdenStatsMap_) {
auto counterName = mapCounterNameForNFSStat(nfsStatsCounter);
if (counterName.has_value()) {
counters->unregisterCallback(counterName.value());
}
}
#endif
}
#ifdef __APPLE__
std::optional<std::string> EdenServer::mapCounterNameForNFSStat(
std::pair<std::string, std::string> nfsStatsCounter) {
auto result = this->getNFSStatCounterValue(nfsStatsCounter.first);
if (result.has_value()) {
return fmt::format(
fmt::runtime(kNFSStatPrefix.str() + ".{}"),
nfsStatsCounter.second); // e.g. "nfs.requests"
} else {
return std::nullopt;
}
}
std::optional<long long> EdenServer::getNFSStatCounterValue(
std::string nfsStatsCounterMacOSName) {
if (!this->updateNFSStatsIfNeeded()) {
// Unable to collect NFS stats
return std::nullopt;
}
try {
std::vector<std::string> tokens;
folly::split('.', nfsStatsCounterMacOSName, tokens);
return nfsStatOutput_[tokens[0]][tokens[1]][tokens[2]].asInt();
} catch (const std::exception&) {
return std::nullopt;
}
}
bool EdenServer::updateNFSStatsIfNeeded() {
auto now = std::chrono::steady_clock::now();
auto last = lastTimeUpdatedNfsStat_.wlock();
if (now >=
*last + config_->getEdenConfig()->updateNFSStatsInterval.getValue()) {
auto result = collectNFSUtilStats();
*last = std::chrono::steady_clock::now();
if (!result.hasValue()) {
// Unable to collect NFS stats
return false;
}
nfsStatOutput_ = result.value();
}
return true;
}
#endif
namespace cursor_helper {
// https://vt100.net/docs/vt510-rm/CPL.html
// The cursor is moved to the start of the nth preceding line
std::string move_cursor_up(size_t n) {
return fmt::format("\x1b\x5b{}F", n);
}
// https://vt100.net/docs/vt510-rm/ED.html
// Erases characters from the cursor through to the end of the display
std::string clear_to_bottom() {
return "\x1b\x5bJ";
}
} // namespace cursor_helper
void EdenServer::ProgressManager::updateProgressState(
size_t progressIndex,
uint16_t percent) {
if (progressIndex < totalInProgress) {
progresses[progressIndex].fsckPercentComplete = percent;
progresses[progressIndex].fsckStarted = true;
}
}
void EdenServer::ProgressManager::finishProgress(size_t progressIndex) {
progresses[progressIndex].mountFinished = true;
totalFinished++;
totalInProgress--;
}
void EdenServer::ProgressManager::markFailed(size_t progressIndex) {
progresses[progressIndex].mountFailed = true;
totalFailed++;
totalInProgress--;
}
void EdenServer::ProgressManager::printProgresses(
std::shared_ptr<StartupLogger> logger,
std::optional<std::string_view> errorMessage) {
std::string prepare;
std::string content;
if (totalLinesPrinted) {
prepare = cursor_helper::move_cursor_up(totalLinesPrinted);
totalLinesPrinted = 0;
}
prepare += cursor_helper::clear_to_bottom();
// we intentionally don't include the lines here in totalLinesPrinted so that
// they won't be erased next time.
if (errorMessage.has_value()) {
content += errorMessage.value();
}
size_t printedFinished = 0;
size_t printedFailed = 0;
size_t printedInProgress = 0;
for (auto& it : progresses) {
if (it.mountFinished) {
content += fmt::format("Successfully remounted {}\n", it.mountPath);
printedFinished++;
} else if (it.mountFailed) {
content += fmt::format("Failed to remount {}\n", it.mountPath);
printedFailed++;
} else if (!it.fsckStarted) {
content += fmt::format("Remounting {}\n", it.mountPath);
printedInProgress++;
} else {
content += fmt::format(
"[{:21}] {:>3}%: fsck on {}{}",
std::string(it.fsckPercentComplete * 2, '=') + ">",
it.fsckPercentComplete * 10,
it.localDir,
"\n");
printedInProgress++;
}
totalLinesPrinted++;
if (totalLinesPrinted == kMaxProgressLines) {
content += fmt::format(
"and {} finished, {} failed, {} in progress...",
totalFinished - printedFinished,
totalFailed - printedFailed,
totalInProgress - printedInProgress);
break;
}
}
logger->logVerbose(prepare + content);
totalLinesPrinted++;
}
void EdenServer::ProgressManager::manageProgress(
std::shared_ptr<StartupLogger> logger,
size_t progressIndex,
uint16_t percent) {
updateProgressState(progressIndex, percent);
printProgresses(logger);
}
size_t EdenServer::ProgressManager::registerEntry(
std::string&& mountPath,
std::string&& localDir) {
auto progressIndex = progresses.size();
progresses.emplace_back(std::move(mountPath), std::move(localDir));
totalInProgress++;
return progressIndex;
}
folly::SemiFuture<Unit> EdenServer::unmountAll() {
std::vector<folly::SemiFuture<Unit>> futures;
{
const auto mountPoints = mountPoints_->wlock();
for (auto& entry : *mountPoints) {
auto& info = entry.second;
// Note: capturing the shared_ptr<EdenMount> here in the thenTry() lambda
// is important to ensure that the EdenMount object cannot be destroyed
// before EdenMount::unmount() completes.
auto mount = info.edenMount;
auto future = mount->unmount({}).defer(
[mount, unmountFuture = info.unmountPromise.getFuture()](
auto&& result) mutable {
if (result.hasValue()) {
return std::move(unmountFuture);
} else {
XLOGF(
ERR,
"Failed to perform unmount for \"{}\": {}",
mount->getPath(),
result.exception().what());
return makeFuture<Unit>(result.exception());
}
});
futures.push_back(std::move(future));
}
}
// Use collectAll() rather than collect() to wait for all of the unmounts
// to complete, and only check for errors once everything has finished.
return folly::collectAll(futures).deferValue(
[](std::vector<folly::Try<Unit>> results) {
for (const auto& result : results) {
result.throwUnlessValue();
}
});
}
#ifndef _WIN32
Future<TakeoverData> EdenServer::stopMountsForTakeover(
folly::Promise<std::optional<TakeoverData>>&& takeoverPromise) {
std::vector<Future<optional<TakeoverData::MountInfo>>> futures;
{
const auto mountPoints = mountPoints_->wlock();
for (auto& [mountPath, info] : *mountPoints) {
try {
info.takeoverPromise.emplace();
auto future = info.takeoverPromise->getFuture();
FsChannel* fsChannel = info.edenMount->getFsChannel();
if (!fsChannel) {
return EDEN_BUG_FUTURE(TakeoverData)
<< "Takeover isn't (yet) supported during mount initialization."
<< "Mount State "
<< folly::to_underlying(info.edenMount->getState());
}
XLOGF(DBG7, "Calling takeoverStop on {} channel", fsChannel->getName());
if (fsChannel->takeoverStop()) {
// Success! Takeover has begun.
} else {
return EDEN_BUG_FUTURE(TakeoverData)
<< "Takeover isn't (yet) supported for " << fsChannel->getName()
<< " mounts. Mount state: "
<< folly::to_underlying(info.edenMount->getState());
}
futures.emplace_back(std::move(future).thenValue(
[self = this,
edenMount = info.edenMount](TakeoverData::MountInfo takeover)
-> Future<optional<TakeoverData::MountInfo>> {
auto fuseChannelInfo =
std::get_if<FuseChannelData>(&takeover.channelInfo);
auto nfsChannelInfo =
std::get_if<NfsChannelData>(&takeover.channelInfo);
if (!fuseChannelInfo && !nfsChannelInfo) {
return std::nullopt;
}
auto& fd = fuseChannelInfo ? fuseChannelInfo->fd
: nfsChannelInfo->nfsdSocketFd;
if (!fd) {
return std::nullopt;
}
return self->serverState_->getPrivHelper()
->takeoverShutdown(edenMount->getPath().view())
.thenValue([takeover = std::move(takeover)](auto&&) mutable {
return std::move(takeover);
});
}));
} catch (...) {
auto ew = folly::exception_wrapper{std::current_exception()};
XLOGF(
ERR, "Error while stopping \"{}\" for takeover: {}", mountPath, ew);
futures.push_back(
makeFuture<optional<TakeoverData::MountInfo>>(std::move(ew)));
}
}
}
// Use collectAll() rather than collect() to wait for all of the unmounts
// to complete, and only check for errors once everything has finished.
// We should not be using .via(&InlineExecutor::instance()) here, this is
// unsafe and deadlock prone. See eden/fs/docs/Futures.md for more details.
return folly::collectAll(futures)
.via(&folly::InlineExecutor::instance())
.thenValue([takeoverPromise = std::move(takeoverPromise)](
std::vector<folly::Try<optional<TakeoverData::MountInfo>>>
results) mutable {
TakeoverData data;
data.takeoverComplete = std::move(takeoverPromise);
data.mountPoints.reserve(results.size());
for (auto& result : results) {
// If something went wrong shutting down a mount point,
// log the error but continue trying to perform graceful takeover
// of the other mount points.
if (!result.hasValue()) {
// TODO: Log this type of error either in the new process or the old
// process.
XLOGF(
ERR,
"error stopping mount during takeover shutdown: {}",
result.exception().what());
continue;
}
// result might be a successful Try with an empty Optional.
// This could happen if the mount point was unmounted while we were
// in the middle of stopping it for takeover. Just skip this mount
// in this case.
if (!result.value().has_value()) {
// TODO: Log this type of error either in the new process or the old
// process.
XLOG(WARN, "mount point was unmounted during takeover shutdown");
continue;
}
data.mountPoints.emplace_back(std::move(result.value().value()));
}
return data;
});
}
#endif
void EdenServer::startPeriodicTasks() {
auto config = serverState_->getReloadableConfig()->getEdenConfig();
if (config->enableOBCOnEden.getValue()) {
// Get the hostname without the ".facebook.com" suffix