Repository navigation
Expand file tree
/
Copy pathadmin-request-handler.cpp
More file actions
1408 lines (1300 loc) · 47.7 KB
/
Copy pathadmin-request-handler.cpp
File metadata and controls
1408 lines (1300 loc) · 47.7 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
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/server/admin-request-handler.h"
#include "hphp/runtime/base/apc-file-storage.h"
#include "hphp/runtime/base/apc-stats.h"
#include "hphp/runtime/base/datetime.h"
#include "hphp/runtime/base/hhprof.h"
#include "hphp/runtime/base/http-client.h"
#include "hphp/runtime/base/init-fini-node.h"
#include "hphp/runtime/base/ini-setting.h"
#include "hphp/runtime/base/memory-manager.h"
#include "hphp/runtime/base/preg.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/rds.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/base/timestamp.h"
#include "hphp/runtime/base/thread-hooks.h"
#include "hphp/runtime/base/unit-cache.h"
#include "hphp/runtime/vm/jit/cg-meta.h"
#include "hphp/runtime/vm/jit/fixup.h"
#include "hphp/runtime/vm/debug/debug.h"
#include "hphp/runtime/vm/jit/mcgen.h"
#include "hphp/runtime/vm/jit/prof-data.h"
#include "hphp/runtime/vm/jit/relocation.h"
#include "hphp/runtime/vm/jit/tc.h"
#include "hphp/runtime/vm/named-entity.h"
#include "hphp/runtime/vm/repo.h"
#include "hphp/runtime/vm/type-profile.h"
#include "hphp/runtime/ext/apc/ext_apc.h"
#include "hphp/runtime/ext/json/ext_json.h"
#include "hphp/runtime/ext/xenon/ext_xenon.h"
#include "hphp/runtime/server/http-request-handler.h"
#include "hphp/runtime/server/http-server.h"
#include "hphp/runtime/server/memory-stats.h"
#include "hphp/runtime/server/pagelet-server.h"
#include "hphp/runtime/server/rpc-request-handler.h"
#include "hphp/runtime/server/server-stats.h"
#include "hphp/util/alloc.h"
#include "hphp/util/hphp-config.h"
#include "hphp/util/logger.h"
#include "hphp/util/mutex.h"
#include "hphp/util/process.h"
#include "hphp/util/build-info.h"
#include "hphp/util/stacktrace-profiler.h"
#include "hphp/util/timer.h"
#ifdef ENABLE_EXTENSION_MYSQL
#include "hphp/runtime/ext/mysql/mysql_stats.h"
#endif
#include <folly/Conv.h>
#include <folly/Random.h>
#include <folly/portability/Unistd.h>
#include <cstdio>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
#ifdef GOOGLE_CPU_PROFILER
#include <gperftools/profiler.h>
#include "hphp/runtime/base/file-util.h"
#endif
namespace HPHP {
using std::endl;
using std::string;
///////////////////////////////////////////////////////////////////////////////
IMPLEMENT_THREAD_LOCAL(AccessLog::ThreadData,
AdminRequestHandler::s_accessLogThreadData);
AccessLog AdminRequestHandler::s_accessLog(
&(AdminRequestHandler::getAccessLogThreadData));
AdminRequestHandler::AdminRequestHandler(int timeout) :
RequestHandler(timeout) {
}
// Helper machinery for jemalloc-stats-print command.
#ifdef USE_JEMALLOC
struct malloc_write {
char *s;
size_t slen;
size_t smax;
bool oom;
};
void malloc_write_init(malloc_write *mw) {
mw->s = nullptr;
mw->slen = 0;
mw->smax = 0;
mw->oom = false;
}
void malloc_write_fini(malloc_write *mw) {
if (mw->s != nullptr) {
free(mw->s);
malloc_write_init(mw);
}
}
static void malloc_write_cb(void *cbopaque, const char *s) {
malloc_write* mw = (malloc_write*)cbopaque;
size_t slen = strlen(s);
if (mw->oom) {
return;
}
if (mw->slen + slen+1 >= mw->smax) {
assert(mw->slen + slen > 0);
char* ts = (char*)realloc(mw->s, (mw->slen + slen) << 1);
if (ts == nullptr) {
mw->oom = true;
return;
}
mw->s = ts;
mw->smax = (mw->slen + slen) << 1;
}
memcpy(&mw->s[mw->slen], s, slen+1);
mw->slen += slen;
}
extern unsigned low_arena;
#endif
void WarnIfNotOK(Transport* transport) {
auto code = static_cast<Transport::StatusCode>(transport->getResponseCode());
if (code != Transport::StatusCode::OK) {
Logger::Warning("Non-OK response from admin server: %d %s",
static_cast<int>(code),
transport->getResponseInfo().c_str());
}
}
#ifdef HPHP_TRACE
namespace {
/*
* Task to trace a total of 'count' requests whose URL contain 'url', using the
* module:level,... specificaion 'spec' (see HPHP::Trace).
*
* To ensure an unbroken trace output stream, the task is held locally by the
* thread currently tracing its request. If filtering on URL, threads may pass
* the task around to find matches faster. Concurrent tasks are not supported.
*/
struct TraceTask {
const std::string spec;
const std::string url;
int64_t count;
};
std::atomic<TraceTask*> s_traceTask{nullptr}; // Task up for grabs.
__thread TraceTask* tl_traceTask{nullptr};
InitFiniNode s_traceRequestStart([]() {
if (!tl_traceTask && !s_traceTask.load(std::memory_order_acquire)) return;
if (!tl_traceTask) {
// Try grab the task.
tl_traceTask = s_traceTask.exchange(nullptr, std::memory_order_acq_rel);
}
if (!tl_traceTask) return; // We lost the race; nothing to do.
if (tl_traceTask->count == 0) {
// Task already complete.
Trace::trace("Trace complete at %d\n", (int)time(nullptr));
Trace::setTraceThread("");
delete tl_traceTask;
tl_traceTask = nullptr;
return;
}
const string url = g_context->getRequestUrl();
if (url.find(tl_traceTask->url) == string::npos) {
// URL mismatch; hand task back (and discard any unlikely colliding task).
delete s_traceTask.exchange(tl_traceTask, std::memory_order_acq_rel);
tl_traceTask = nullptr;
Trace::setTraceThread("");
} else {
// Work on task.
--tl_traceTask->count;
const auto spec = tl_traceTask->spec;
Trace::setTraceThread(spec);
Trace::trace("Trace for %s at %d using spec %s\n",
url.c_str(), (int)time(nullptr), spec.c_str());
}
}, InitFiniNode::When::RequestStart, "trace");
std::string getTraceOutputFile() {
return folly::sformat("{}/hphp.{}.log",
RuntimeOption::RemoteTraceOutputDir, (int64_t)getpid());
}
} // namespace
#endif // HPHP_TRACE
void AdminRequestHandler::logToAccessLog(Transport* transport) {
GetAccessLog().onNewRequest();
GetAccessLog().log(transport, nullptr);
WarnIfNotOK(transport);
}
void AdminRequestHandler::setupRequest(Transport* transport) {
g_context.getCheck();
GetAccessLog().onNewRequest();
}
void AdminRequestHandler::teardownRequest(Transport* transport) noexcept {
SCOPE_EXIT { hphp_memory_cleanup(); };
GetAccessLog().log(transport, nullptr);
WarnIfNotOK(transport);
}
void AdminRequestHandler::handleRequest(Transport *transport) {
transport->addHeader("Content-Type", "text/plain");
std::string cmd = transport->getCommand();
do {
if (cmd == "" || cmd == "help") {
string usage =
"/stop: stop the web server\n"
" instance-id optional, if specified, instance ID has to match\n"
"/free-mem: ask allocator to release unused memory to system\n"
"/prepare-to-stop: ask the server to prepare for stopping\n"
"/flush-logs: trigger batching log-writers to flush all content\n"
"/translate: translate hex encoded stacktrace in 'stack' param\n"
" stack required, stack trace to translate\n"
" build-id optional, if specified, build ID has to match\n"
" bare optional, whether to display frame ordinates\n"
"/build-id: returns build id that's passed in from command line"
"\n"
"/instance-id: instance id that's passed in from command line\n"
"/compiler-id: returns the compiler id that built this app\n"
"/repo-schema: return the repo schema id used by this app\n"
"/ini-get-all: dump all settings as JSON\n"
"/check-load: how many threads are actively handling requests\n"
"/check-queued: how many http requests are queued waiting to be\n"
" handled\n"
"/check-health: return json containing basic load/usage stats\n"
"/check-ev: how many http requests are active by libevent\n"
"/check-pl-load: how many pagelet threads are actively handling\n"
" requests\n"
"/check-pl-queued: how many pagelet requests are queued waiting to\n"
" be handled\n"
"/check-sql: report SQL table statistics\n"
"/check-sat how many satellite threads are actively handling\n"
" requests and queued waiting to be handled\n"
"/status.xml: show server status in XML\n"
"/status.json: show server status in JSON\n"
"/status.html: show server status in HTML\n"
"/memory.xml: show memory status in XML\n"
"/memory.json: show memory status in JSON\n"
"/memory.html: show memory status in HTML\n"
"/stats-on: main switch: enable server stats\n"
"/stats-off: main switch: disable server stats\n"
"/stats-clear: clear all server stats\n"
"/stats-web: turn on/off server page stats (CPU and gen time)\n"
"/stats-mem: turn on/off memory statistics\n"
"/stats-sql: turn on/off SQL statistics\n"
"/stats-mutex: turn on/off mutex statistics\n"
" sampling optional, default 1000\n"
"/stats.keys: list all available keys\n"
" from optional, <timestamp>, or <-n> second ago\n"
" to optional, <timestamp>, or <-n> second ago\n"
"/stats.kvp: show server stats in key-value pairs\n"
" from optional, <timestamp>, or <-n> second ago\n"
" to optional, <timestamp>, or <-n> second ago\n"
" agg optional, aggragation: *, url, code\n"
" keys optional, <key>,<key/hit>,<key/sec>,<:regex:>\n"
" url optional, only stats of this page or URL\n"
" code optional, only stats of pages returning this code\n"
"/xenon-snap: generate a Xenon snapshot, which is logged later\n"
"/const-ss: get const_map_size\n"
"/static-strings: get number of static strings\n"
"/static-strings-rds: ... that correspond to defined constants\n"
"/dump-static-strings: dump static strings to /tmp/static_strings\n"
"/random-static-strings: return randomly selected static strings\n"
" count number of strings to return, default 1\n"
"/dump-apc: dump all current value in APC to /tmp/apc_dump\n"
"/dump-apc-info: show basic APC stats\n"
"/dump-apc-meta: dump meta information for all objects in APC to\n"
" /tmp/apc_dump_meta\n"
"/advise-out-apc: forcibly madvise out APC prime data\n"
"/random-apc: dump the key and size of a random APC entry\n"
" count number of entries to return\n"
"/pcre-cache-size: get pcre cache map size\n"
"/dump-pcre-cache: dump cached pcre's to /tmp/pcre_cache\n"
"/dump-array-info: dump array tracer info to /tmp/array_tracer_dump\n"
"/start-stacktrace-profiler: set enable_stacktrace_profiler to true\n"
"/relocate: relocate translations\n"
" random optional, default false, relocate random subset\n"
" all optional, default false, relocate all translations\n"
" time optional, default 20 (seconds)\n"
#ifdef HPHP_TRACE
"/trace-request: write trace for next request(s) to "
+ getTraceOutputFile() + "\n"
" spec module:level,... spec; see hphp/util/trace.h\n"
" count optional, total requests to trace (default: 1)\n"
" url optional, trace only if URL contains \'url\'\n"
#endif
#ifdef GOOGLE_CPU_PROFILER
"/prof-cpu-on: turn on CPU profiler\n"
"/prof-cpu-off: turn off CPU profiler\n"
#endif
#ifdef EXECUTION_PROFILER
"/prof-exe: returns sampled execution profile\n"
#endif
"/vm-tcspace: show space used by translator caches\n"
"/vm-tcaddr: show addresses of translation cache sections\n"
"/vm-dump-tc: dump translation cache to /tmp/tc_dump_a and\n"
" /tmp/tc_dump_astub\n"
"/vm-namedentities:show size of the NamedEntityTable\n"
"/thread-mem-usage:show memory usage per thread\n"
"/proxy: set up request proxy\n"
" origin URL to proxy requests to\n"
" percentage percentage of requests to proxy\n"
"/load-factor: get or set load factor\n"
" set optional, set new load factor (default 1.0,"
" valid range [-1.0, 10.0])\n"
;
#ifdef USE_TCMALLOC
if (MallocExtensionInstance) {
usage.append(
"/tcmalloc-stats: get internal tcmalloc stats\n"
"/tcmalloc-set-tc: set max mem tcmalloc thread-cache can use\n"
);
}
#endif
#ifdef USE_JEMALLOC
if (mallctl) {
usage.append(
"/jemalloc-stats: get internal jemalloc stats\n"
"/jemalloc-stats-print:\n"
" get comprehensive jemalloc stats in\n"
" human-readable form\n"
"/jemalloc-prof-activate:\n"
" activate heap profiling\n"
"/jemalloc-prof-deactivate:\n"
" deactivate heap profiling\n"
"/jemalloc-prof-dump:\n"
" dump heap profile\n"
" file optional, filesystem path\n"
"/jemalloc-prof-request:\n"
" dump thread-local heap profile in\n"
" the next request that runs\n"
" file optional, filesystem path\n"
);
#ifdef ENABLE_HHPROF
usage.append(
"/hhprof/start: start profiling\n"
" requestType \"all\" or \"next\"*\n"
" url profile next matching url for \"next\"\n"
" lgSample lg sample rate\n"
" profileType \"current\"* or \"cumulative\"\n"
"/hhprof/status: configuration and current dump status\n"
"/hhprof/stop: stop profiling\n"
"/pprof/cmdline: program command line\n"
"/pprof/heap: heap dump\n"
"/pprof/symbol: symbol lookup\n"
);
#endif // ENABLE_HHPROF
}
#endif // USE_JEMALLOC
transport->sendString(usage);
break;
}
bool needs_password = (cmd != "build-id") && (cmd != "compiler-id") &&
(cmd != "instance-id") && (cmd != "flush-logs")
#if defined(ENABLE_HHPROF) && defined(USE_JEMALLOC)
&& (mallctl == nullptr || (
(cmd != "hhprof/start")
&& (cmd != "hhprof/status")
&& (cmd != "hhprof/stop")
&& (cmd != "pprof/cmdline")
&& (cmd != "pprof/heap")
&& (cmd != "pprof/symbol")))
#endif
;
if (needs_password && !RuntimeOption::AdminPasswords.empty()) {
std::set<std::string>::const_iterator iter =
RuntimeOption::AdminPasswords.find(transport->getParam("auth"));
if (iter == RuntimeOption::AdminPasswords.end()) {
transport->sendString("Unauthorized", 401);
break;
}
} else {
if (needs_password && !RuntimeOption::AdminPassword.empty() &&
RuntimeOption::AdminPassword != transport->getParam("auth")) {
transport->sendString("Unauthorized", 401);
break;
}
}
if (cmd == "stop") {
string instanceId = transport->getParam("instance-id");
if (!instanceId.empty() && instanceId != RuntimeOption::InstanceId) {
transport->sendString("Instance ID doesn't match.", 500);
break;
}
transport->sendString("OK\n");
Logger::Info("Got admin port stop request from %s",
transport->getRemoteHost());
HttpServer::Server->stop();
break;
}
if (cmd == "free-mem") {
auto pid = getpid();
const auto before = Process::GetProcessRSS(pid);
std::string errStr;
if (purge_all(&errStr)) {
const auto after = Process::GetProcessRSS(pid);
transport->sendString(
folly::sformat("Purged {} -> {} MB RSS", before, after).c_str());
} else {
transport->sendString(errStr.c_str(), 500);
}
break;
}
if (cmd == "prepare-to-stop") {
Logger::Info("Got admin port prepare-to-stop request from %s",
transport->getRemoteHost());
MemInfo info, newInfo;
Process::GetMemoryInfo(info);
HttpServer::PrepareToStop();
// We may consider purge_all() here, too. But since requests
// are still coming in, it may not be very useful, and has some
// performance penalties.
// TODO: evaluate the effect of sync() and uncomment if
// desirable. It is blocking and can take some time, so do it
// in a separate thread.
// std::thread t{sync};
// t.detach();
transport->sendString("OK\n");
Process::GetMemoryInfo(newInfo);
Logger::FInfo("free/cached/buffer {}/{}/{} -> {}/{}/{}",
info.freeMb, info.cachedMb, info.buffersMb,
newInfo.freeMb, newInfo.cachedMb, newInfo.buffersMb);
break;
}
if (cmd == "flush-logs") {
transport->sendString("OK\n");
Logger::FlushAll();
HttpRequestHandler::GetAccessLog().flushAllWriters();
AdminRequestHandler::GetAccessLog().flushAllWriters();
RPCRequestHandler::GetAccessLog().flushAllWriters();
break;
}
if (cmd == "set-log-level") {
string result("OK\n");
string level = transport->getParam("level");
if (level == "None") {
Logger::LogLevel = Logger::LogNone;
} else if (level == "Error") {
Logger::LogLevel = Logger::LogError;
} else if (level == "Warning") {
Logger::LogLevel = Logger::LogWarning;
} else if (level == "Info") {
Logger::LogLevel = Logger::LogInfo;
} else if (level == "Verbose") {
Logger::LogLevel = Logger::LogVerbose;
} else {
result = "Failed to set log level\n";
}
transport->sendString(result);
break;
}
#ifdef HPHP_TRACE
if (cmd == "trace-request") {
Trace::ensureInit(getTraceOutputFile());
// Just discard any existing task.
delete s_traceTask.exchange(
new TraceTask{transport->getParam("spec"),
transport->getParam("url"),
std::max(transport->getInt64Param("count"), 1ll)},
std::memory_order_acq_rel);
transport->sendString("OK\n");
break;
}
#endif
if (cmd == "build-id") {
transport->sendString(RuntimeOption::BuildId, 200);
break;
}
if (cmd == "instance-id") {
transport->sendString(RuntimeOption::InstanceId, 200);
break;
}
if (cmd == "compiler-id") {
transport->sendString(compilerId().begin(), 200);
break;
}
if (cmd == "repo-schema") {
transport->sendString(repoSchemaId().begin(), 200);
break;
}
if (cmd == "translate") {
string buildId = transport->getParam("build-id");
if (!buildId.empty() && buildId != RuntimeOption::BuildId) {
transport->sendString("Build ID doesn't match.", 500);
break;
}
string translated = translate_stack(transport->getParam("stack").c_str(),
transport->getParam("bare").empty());
transport->sendString(translated);
break;
}
if (strncmp(cmd.c_str(), "check", 5) == 0 &&
handleCheckRequest(cmd, transport)) {
break;
}
if (strncmp(cmd.c_str(), "status", 6) == 0 &&
handleStatusRequest(cmd, transport)) {
break;
}
if (strncmp(cmd.c_str(),"memory", 6) == 0 &&
handleMemoryRequest(cmd, transport)) {
break;
}
if (strncmp(cmd.c_str(), "stats", 5) == 0 &&
handleStatsRequest(cmd, transport)) {
break;
}
if (strncmp(cmd.c_str(), "prof", 4) == 0 &&
handleProfileRequest(cmd, transport)) {
break;
}
if (strncmp(cmd.c_str(), "dump-apc", 8) == 0 &&
handleDumpCacheRequest(cmd, transport)) {
break;
}
if (strncmp(cmd.c_str(), "xenon-snap", 10) == 0) {
static int64_t s_lastSampleTime = 0;
auto const current = TimeStamp::Current();
if (current > s_lastSampleTime) {
s_lastSampleTime = current;
Xenon::getInstance().surpriseAll();
}
transport->sendString("a Xenon sample will be collected\n", 200);
break;
}
if (strncmp(cmd.c_str(), "const-ss", 8) == 0 &&
handleConstSizeRequest(cmd, transport)) {
break;
}
if (strncmp(cmd.c_str(), "static-strings", 14) == 0 &&
handleStaticStringsRequest(cmd, transport)) {
break;
}
if (strncmp(cmd.c_str(), "dump-static-strings", 19) == 0) {
auto filename = transport->getParam("file");
if (filename == "") filename = "/tmp/static_strings";
handleDumpStaticStringsRequest(cmd, filename);
transport->sendString("OK\n");
break;
}
if (strncmp(cmd.c_str(), "random-static-strings", 21) == 0) {
handleRandomStaticStringsRequest(cmd, transport);
break;
}
if (strncmp(cmd.c_str(), "vm-", 3) == 0 &&
handleVMRequest(cmd, transport)) {
break;
}
if (cmd == "proxy") {
handleProxyRequest(cmd, transport);
break;
}
if (!strcmp(cmd.c_str(), "thread-mem")) {
transport->sendString(get_thread_mem_usage());
break;
}
if (cmd == "pcre-cache-size") {
std::ostringstream size;
size << preg_pcre_cache_size() << endl;
transport->sendString(size.str());
break;
}
if (cmd == "dump-pcre-cache") {
auto filename = transport->getParam("file");
if (filename == "") filename = "/tmp/pcre_cache";
pcre_dump_cache(filename);
transport->sendString("OK\n");
break;
}
if (cmd == "start-stacktrace-profiler") {
enable_stacktrace_profiler = true;
transport->sendString("OK\n");
break;
}
if (cmd == "relocate") {
auto randomParam = transport->getParam("random");
auto allParam = transport->getParam("all");
auto time = transport->getIntParam("time");
bool random = randomParam == "true" || randomParam == "1";
if (allParam == "true" || allParam == "1") {
jit::tc::liveRelocate(-2);
} else if (random || time == 0) {
jit::tc::liveRelocate(random);
} else {
jit::tc::liveRelocate(time);
}
transport->sendString("OK\n");
break;
}
if (cmd == "advise-out-apc") {
if (!apcExtension::Enable) {
transport->sendString("No APC\n");
break;
}
apc_advise_out();
transport->sendString("Done\n");
break;
}
if (strncmp(cmd.c_str(), "random-apc", 10) == 0 &&
handleRandomApcRequest(cmd, transport)) {
break;
}
if (cmd == "load-factor") {
auto const factorStr = transport->getParam("set");
if (factorStr.empty()) {
std::ostringstream oss;
oss << std::fixed << std::setprecision(3)
<< HttpServer::LoadFactor.load();
transport->sendString(oss.str());
break;
}
double factor = 1.0;
if (sscanf(factorStr.c_str(), "%lf", &factor) < 1 ||
factor > 10 || factor < -1) {
transport->sendString("Invalid load factor spec: " + factorStr, 400);
break;
}
HttpServer::LoadFactor.store(factor, std::memory_order_relaxed);
transport->sendString(folly::sformat("Load factor updated to {}\n",
factor));
Logger::Info("Load factor updated to %lf", factor);
break;
}
if (cmd == "ini-get-all") {
auto out = IniSetting::GetAllAsJSON();
transport->sendString(out.c_str());
break;
}
#ifdef USE_TCMALLOC
if (MallocExtensionInstance) {
if (cmd == "tcmalloc-stats") {
std::ostringstream stats;
size_t user_allocated, heap_size, slack_bytes;
size_t pageheap_free, pageheap_unmapped;
size_t tc_max, tc_allocated;
MallocExtensionInstance()->
GetNumericProperty("generic.current_allocated_bytes",
&user_allocated);
MallocExtensionInstance()->
GetNumericProperty("generic.heap_size", &heap_size);
MallocExtensionInstance()->
GetNumericProperty("tcmalloc.slack_bytes", &slack_bytes);
MallocExtensionInstance()->
GetNumericProperty("tcmalloc.pageheap_free_bytes", &pageheap_free);
MallocExtensionInstance()->
GetNumericProperty("tcmalloc.pageheap_unmapped_bytes",
&pageheap_unmapped);
MallocExtensionInstance()->
GetNumericProperty("tcmalloc.max_total_thread_cache_bytes",
&tc_max);
MallocExtensionInstance()->
GetNumericProperty("tcmalloc.current_total_thread_cache_bytes",
&tc_allocated);
stats << "<tcmalloc-stats>" << endl;
stats << " <user_allocated>" << user_allocated << "</user_allocated>"
<< endl;
stats << " <heap_size>" << heap_size << "</heap_size>" << endl;
stats << " <slack_bytes>" << slack_bytes << "</slack_bytes>" << endl;
stats << " <pageheap_free>" << pageheap_free
<< "</pageheap_free>" << endl;
stats << " <pageheap_unmapped>" << pageheap_unmapped
<< "</pageheap_unmapped>" << endl;
stats << " <thread_cache_max>" << tc_max
<< "</thread_cache_max>" << endl;
stats << " <thread_cache_allocated>" << tc_allocated
<< "</thread_cache_allocated>" << endl;
stats << "</tcmalloc-stats>" << endl;
transport->sendString(stats.str());
break;
}
if (cmd == "tcmalloc-set-tc") {
size_t tc_max;
MallocExtensionInstance()->
GetNumericProperty("tcmalloc.max_total_thread_cache_bytes", &tc_max);
size_t tcache = transport->getInt64Param("s");
bool retval = MallocExtensionInstance()->
SetNumericProperty("tcmalloc.max_total_thread_cache_bytes", tcache);
transport->sendString(retval == true ? "OK\n" : "FAILED\n");
break;
}
}
#endif
#ifdef USE_JEMALLOC
if (mallctl) {
assert(mallctlnametomib && mallctlbymib);
if (cmd == "jemalloc-stats") {
// Force jemalloc to update stats cached for use by mallctl().
uint32_t error = 0;
if (mallctlWrite<uint64_t>("epoch", 1, true) != 0) {
error = 1;
}
auto call_mallctl = [&](const char* statName) {
size_t value = 0;
if (mallctlRead(statName, &value, true) != 0) {
error = 1;
}
return value;
};
size_t allocated = call_mallctl("stats.allocated");
size_t active = call_mallctl("stats.active");
size_t mapped = call_mallctl("stats.mapped");
size_t low_mapped = call_mallctl(
folly::format("stats.arenas.{}.mapped",
low_arena).str().c_str());
size_t low_small_allocated = call_mallctl(
folly::format("stats.arenas.{}.small.allocated",
low_arena).str().c_str());
size_t low_large_allocated = call_mallctl(
folly::format("stats.arenas.{}.large.allocated",
low_arena).str().c_str());
size_t low_active = call_mallctl(
folly::format("stats.arenas.{}.pactive",
low_arena).str().c_str()) *
sysconf(_SC_PAGESIZE);
std::ostringstream stats;
stats << "<jemalloc-stats>" << endl;
stats << " <allocated>" << allocated << "</allocated>" << endl;
stats << " <active>" << active << "</active>" << endl;
stats << " <mapped>" << mapped << "</mapped>" << endl;
stats << " <low_mapped>" << low_mapped << "</low_mapped>" << endl;
stats << " <low_allocated>"
<< (low_small_allocated + low_large_allocated)
<< "</low_allocated>" << endl;
stats << " <low_active>"
<< low_active
<< "</low_active>" << endl;
stats << " <error>" << error << "</error>" << endl;
stats << "</jemalloc-stats>" << endl;
transport->sendString(stats.str());
break;
}
if (cmd == "jemalloc-stats-print") {
malloc_write mwo;
malloc_write_init(&mwo);
malloc_stats_print(malloc_write_cb, (void *)&mwo, "");
if (mwo.oom) {
malloc_write_fini(&mwo);
transport->sendString("OOM\n");
break;
}
transport->sendString(mwo.s);
malloc_write_fini(&mwo);
break;
}
if (cmd == "jemalloc-prof-activate") {
int err = jemalloc_pprof_enable();
if (err) {
std::ostringstream estr;
estr << "Error " << err << " in mallctl(\"prof.active\", ...)"
<< endl;
transport->sendString(estr.str());
} else {
transport->sendString("OK\n");
}
break;
}
if (cmd == "jemalloc-prof-deactivate") {
int err = jemalloc_pprof_disable();
if (err) {
std::ostringstream estr;
estr << "Error " << err << " in mallctl(\"prof.active\", ...)"
<< endl;
transport->sendString(estr.str());
} else {
transport->sendString("OK\n");
}
break;
}
if (cmd == "jemalloc-prof-dump") {
string f = transport->getParam("file");
int err = jemalloc_pprof_dump(f, true);
if (err) {
std::ostringstream estr;
estr << "Error " << err << " in mallctl(\"prof.dump\", ...";
if (!f.empty()) {
estr << ", \"" << f << "\", ...";
}
estr << ")" << endl;
transport->sendString(estr.str());
break;
}
transport->sendString("OK\n");
break;
}
if (cmd == "jemalloc-prof-request") {
auto f = transport->getParam("file");
bool success = MemoryManager::triggerProfiling(f);
if (success) {
transport->sendString("OK\n");
} else {
transport->sendString("Request profiling already triggered\n");
}
break;
}
#ifdef ENABLE_HHPROF
if (cmd == "hhprof/start") {
HHProf::HandleHHProfStart(transport);
break;
}
if (cmd == "hhprof/status") {
HHProf::HandleHHProfStatus(transport);
break;
}
if (cmd == "hhprof/stop") {
HHProf::HandleHHProfStop(transport);
break;
}
if (cmd == "pprof/cmdline") {
HHProf::HandlePProfCmdline(transport);
break;
}
if (cmd == "pprof/heap") {
HHProf::HandlePProfHeap(transport);
break;
}
if (cmd == "pprof/symbol") {
HHProf::HandlePProfSymbol(transport);
break;
}
#endif // ENABLE_HHPROF
}
#endif // USE_JEMALLOC
transport->sendString("Unknown command: " + cmd + "\n", 404);
} while (0);
transport->onSendEnd();
}
void AdminRequestHandler::abortRequest(Transport *transport) {
g_context.getCheck();
transport->sendString("Service Unavailable", 503);
transport->onSendEnd();
}
///////////////////////////////////////////////////////////////////////////////
// stats commands
static bool toggle_switch(Transport *transport, bool &setting) {
setting = !setting;
transport->sendString(setting ? "On\n" : "Off\n");
return true;
}
static bool send_report(Transport *transport) {
std::string keys = transport->getParam ("keys");
std::string prefix = transport->getParam ("prefix");
std::string out;
ServerStats::Report(out, keys, prefix);
transport->replaceHeader("Content-Type", "text/plain");
transport->sendString(out);
return true;
}
static bool send_status(Transport *transport, Writer::Format format,
const char *mime) {
string out;
ServerStats::ReportStatus(out, format);
transport->replaceHeader("Content-Type", mime);
transport->sendString(out);
return true;
}
extern size_t hhbc_arena_capacity();
bool AdminRequestHandler::handleCheckRequest(const std::string &cmd,
Transport *transport) {
if (cmd == "check-load") {
int count = HttpServer::Server->getPageServer()->getActiveWorker();
transport->sendString(folly::to<std::string>(count));
return true;
}
if (cmd == "check-ev") {
int count =
HttpServer::Server->getPageServer()->getLibEventConnectionCount();
transport->sendString(folly::to<string>(count));
return true;
}
if (cmd == "check-queued") {
int count = HttpServer::Server->getPageServer()->getQueuedJobs();
transport->sendString(folly::to<string>(count));
return true;
}
if (cmd == "check-health") {
std::stringstream out;
bool first = true;
out << "{" << endl;
auto appendStat = [&](folly::StringPiece name, int64_t value) {
out << folly::format("{} \"{}\":{}\n", first ? "" : ",", name, value);
first = false;
};
HPHP::Server* server = HttpServer::Server->getPageServer();
appendStat("load", server->getActiveWorker());
appendStat("queued", server->getQueuedJobs());
appendStat("hhbc-roarena-capac", hhbc_arena_capacity());
auto const memInfos = jit::tc::getTCMemoryUsage();
for (auto const info : memInfos) {
auto isMain = info.name == "main";
appendStat(folly::format("tc-{}size",
isMain ? "" : info.name).str(),
info.used);
}
appendStat("rds", rds::usedBytes());
appendStat("rds-local", rds::usedLocalBytes());
appendStat("rds-persistent", rds::usedPersistentBytes());
appendStat("catch-traces", jit::numCatchTraces());
appendStat("fixups", jit::FixupMap::size());
appendStat("units", numLoadedUnits());
appendStat("funcs", Func::nextFuncId());
appendStat("named-entities", NamedEntity::tableSize());
appendStat("static-strings", makeStaticStringCount());
appendStat("request-count", requestCount());
appendStat("single-jit-requests", singleJitRequestCount());
/*
* We're only using globalProfData() here because admin requests don't call
* requestInitProfData(). Normal request threads should always use
* profData() which provides much better guarantees about the lifetime of
* the returned object.
*/
if (auto profData = jit::globalProfData()) {
appendStat("prof-funcs", profData->profilingFuncs());
appendStat("prof-bc", profData->profilingBCSize());
appendStat("opt-funcs", profData->optimizedFuncs());
}
if (RuntimeOption::EvalEnableReusableTC) {
for (auto const info : memInfos) {
appendStat(folly::format("tc-{}-allocs", info.name).str(), info.allocs);
appendStat(folly::format("tc-{}-frees", info.name).str(), info.frees);