-
Notifications
You must be signed in to change notification settings - Fork 28
/
menelaus_web.erl
1685 lines (1552 loc) · 74.3 KB
/
menelaus_web.erl
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
%% @author Northscale <info@northscale.com>
%% @copyright 2009 NorthScale, Inc.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @doc Web server for menelaus.
-module(menelaus_web).
-author('NorthScale <info@northscale.com>').
% -behavior(ns_log_categorizing).
% the above is commented out because of the way the project is structured
-include_lib("eunit/include/eunit.hrl").
-include("menelaus_web.hrl").
-include("ns_common.hrl").
-include("ns_stats.hrl").
-ifdef(EUNIT).
-export([test/0]).
-endif.
-export([start_link/0,
start_link/1,
stop/0,
loop/3,
webconfig/0,
webconfig/1,
restart/0,
build_node_hostname/3,
build_nodes_info/0,
build_nodes_info_fun/3,
build_full_node_info/2,
handle_streaming/3,
is_system_provisioned/0,
checking_bucket_hostname_access/5]).
-export([ns_log_cat/1, ns_log_code_string/1, alert_key/1]).
-import(menelaus_util,
[server_header/0,
redirect_permanently/2,
concat_url_path/1,
reply_json/2,
reply_json/3,
get_option/2,
parse_validate_number/3]).
-define(AUTO_FAILLOVER_MIN_TIMEOUT, 30).
%% External API
start_link() ->
start_link(webconfig()).
start_link(Options) ->
{AppRoot, Options1} = get_option(approot, Options),
{DocRoot, Options2} = get_option(docroot, Options1),
Loop = fun (Req) ->
?MODULE:loop(Req, AppRoot, DocRoot)
end,
case mochiweb_http:start([{name, ?MODULE}, {loop, Loop} | Options2]) of
{ok, Pid} -> {ok, Pid};
Other ->
ns_log:log(?MODULE, ?START_FAIL,
"Failed to start web service: ~p~n", [Other]),
Other
end.
stop() ->
% Note that a supervisor might restart us right away.
mochiweb_http:stop(?MODULE).
restart() ->
% Depend on our supervision tree to restart us right away.
stop().
webconfig(Config) ->
Ip = case os:getenv("MOCHIWEB_IP") of
false -> "0.0.0.0";
Any -> Any
end,
Port = case os:getenv("MOCHIWEB_PORT") of
false ->
misc:node_rest_port(Config, node());
P -> list_to_integer(P)
end,
WebConfig = [{ip, Ip},
{port, Port},
{approot, menelaus_deps:local_path(["priv","public"],
?MODULE)}],
WebConfig.
webconfig() ->
webconfig(ns_config:get()).
loop(Req, AppRoot, DocRoot) ->
try
% Using raw_path so encoded slash characters like %2F are handed correctly,
% in that we delay converting %2F's to slash characters until after we split by slashes.
"/" ++ RawPath = Req:get(raw_path),
{Path, _, _} = mochiweb_util:urlsplit_path(RawPath),
PathTokens = lists:map(fun mochiweb_util:unquote/1, string:tokens(Path, "/")),
Action = case Req:get(method) of
Method when Method =:= 'GET'; Method =:= 'HEAD' ->
case PathTokens of
[] ->
{done, redirect_permanently("/index.html", Req)};
["versions"] ->
{done, handle_versions(Req)};
["pools"] ->
{auth_any_bucket, fun handle_pools/1};
["pools", Id] ->
{auth_any_bucket, fun check_and_handle_pool_info/2, [Id]};
["pools", Id, "stats"] ->
{auth_any_bucket, fun menelaus_stats:handle_bucket_stats/3,
[Id, all]};
["pools", Id, "overviewStats"] ->
{auth, fun menelaus_stats:handle_overview_stats/2, [Id]};
["poolsStreaming", Id] ->
{auth_any_bucket, fun handle_pool_info_streaming/2, [Id]};
["pools", PoolId, "buckets"] ->
{auth_any_bucket, fun menelaus_web_buckets:handle_bucket_list/2, [PoolId]};
["pools", PoolId, "saslBucketsStreaming"] ->
{auth, fun menelaus_web_buckets:handle_sasl_buckets_streaming/2, [PoolId]};
["pools", PoolId, "buckets", Id] ->
{auth_bucket_with_info, fun menelaus_web_buckets:handle_bucket_info/5,
[PoolId, Id]};
["pools", PoolId, "bucketsStreaming", Id] ->
{auth_bucket, fun menelaus_web_buckets:handle_bucket_info_streaming/3,
[PoolId, Id]};
["pools", PoolId, "buckets", Id, "stats"] ->
{auth_bucket, fun handle_abortable_bucket_stats/3,
[PoolId, Id]};
["pools", PoolId, "buckets", Id, "statsDirectory"] ->
{auth_bucket, fun menelaus_stats:serve_stats_directory/3,
[PoolId, Id]};
%% GET /pools/{PoolId}/buckets/{Id}/nodes
["pools", PoolId, "buckets", Id, "nodes"] ->
{auth_bucket, fun handle_bucket_node_list/3,
[PoolId, Id]};
%% GET /pools/{PoolId}/buckets/{Id}/nodes/{NodeId}
["pools", PoolId, "buckets", Id, "nodes", NodeId] ->
{auth_bucket, fun handle_bucket_node_info/4,
[PoolId, Id, NodeId]};
%% GET /pools/{PoolId}/buckets/{Id}/nodes/{NodeId}/stats
["pools", PoolId, "buckets", Id, "nodes", NodeId, "stats"] ->
{auth_bucket, fun handle_abortable_bucket_node_stats/4,
[PoolId, Id, NodeId]};
%% GET /pools/{PoolId}/buckets/{Id}/stats/{StatName}
["pools", PoolId, "buckets", Id, "stats", StatName] ->
{auth_bucket, fun handle_abortable_specific_stat_for_bucket/4,
[PoolId, Id, StatName]};
["nodeStatuses"] ->
{auth, fun handle_node_statuses/1};
["logs"] ->
{auth, fun menelaus_alert:handle_logs/1};
["alerts"] ->
{auth, fun menelaus_alert:handle_alerts/1};
["settings", "web"] ->
{auth, fun handle_settings_web/1};
["settings", "alerts"] ->
{auth, fun handle_settings_alerts/1};
["settings", "stats"] ->
{auth, fun handle_settings_stats/1};
["settings", "autoFailover"] ->
{auth, fun handle_settings_auto_failover/1};
["nodes", NodeId] ->
{auth, fun handle_node/2, [NodeId]};
["diag"] ->
{auth_cookie, fun diag_handler:handle_diag/1};
["diag", "vbuckets"] -> {auth, fun handle_diag_vbuckets/1};
["pools", PoolId, "rebalanceProgress"] ->
{auth, fun handle_rebalance_progress/2, [PoolId]};
["index.html"] ->
{done, serve_static_file(Req, {AppRoot, Path},
"text/html; charset=utf8",
[{"Pragma", "no-cache"},
{"Cache-Control", "must-revalidate"}])};
["docs" | _PRem ] ->
DocFile = string:sub_string(Path, 6),
{done, Req:serve_file(DocFile, DocRoot)};
["dot", Bucket] ->
{auth_cookie, fun handle_dot/2, [Bucket]};
["dotsvg", Bucket] ->
{auth_cookie, fun handle_dotsvg/2, [Bucket]};
["sasl_logs"] ->
{auth_cookie, fun diag_handler:handle_sasl_logs/1};
["erlwsh" | _] ->
{auth_cookie, fun (R) -> erlwsh_web:loop(R, erlwsh_deps:local_path(["priv", "www"])) end};
["images" | _] ->
{done, Req:serve_file(Path, AppRoot,
[{"Cache-Control", "max-age=30000000"}])};
_ ->
{done, Req:serve_file(Path, AppRoot,
[{"Cache-Control", "max-age=10"}])}
end;
'POST' ->
case PathTokens of
["engageCluster2"] ->
{auth, fun handle_engage_cluster2/1};
["completeJoin"] ->
{auth, fun handle_complete_join/1};
["node", "controller", "doJoinCluster"] ->
{auth, fun handle_join/1};
["nodes", NodeId, "controller", "settings"] ->
{auth, fun handle_node_settings_post/2,
[NodeId]};
["nodes", NodeId, "controller", "resources"] ->
{auth, fun handle_node_resources_post/2,
[NodeId]};
["settings", "web"] ->
{auth, fun handle_settings_web_post/1};
["settings", "alerts"] ->
{auth, fun handle_settings_alerts_post/1};
["settings", "alerts", "testEmail"] ->
{auth, fun handle_settings_alerts_send_test_email/1};
["settings", "stats"] ->
{auth, fun handle_settings_stats_post/1};
["settings", "autoFailover"] ->
{auth, fun handle_settings_auto_failover_post/1};
["settings", "autoFailover", "resetCount"] ->
{auth, fun handle_settings_auto_failover_reset_count/1};
["pools", PoolId] ->
{auth, fun handle_pool_settings/2,
[PoolId]};
["pools", _PoolId, "controller", "testWorkload"] ->
{auth, fun handle_traffic_generator_control_post/1};
["controller", "setupDefaultBucket"] ->
{auth, fun menelaus_web_buckets:handle_setup_default_bucket_post/1};
["controller", "ejectNode"] ->
{auth, fun handle_eject_post/1};
["controller", "addNode"] ->
{auth, fun handle_add_node/1};
["controller", "failOver"] ->
{auth, fun handle_failover/1};
["controller", "rebalance"] ->
{auth, fun handle_rebalance/1};
["controller", "reAddNode"] ->
{auth, fun handle_re_add_node/1};
["controller", "stopRebalance"] ->
{auth, fun handle_stop_rebalance/1};
["pools", PoolId, "buckets", Id] ->
{auth_bucket, fun menelaus_web_buckets:handle_bucket_update/3,
[PoolId, Id]};
["pools", PoolId, "buckets"] ->
{auth, fun menelaus_web_buckets:handle_bucket_create/2,
[PoolId]};
["pools", PoolId, "buckets", Id, "controller", "doFlush"] ->
{auth_bucket, fun menelaus_web_buckets:handle_bucket_flush/3,
[PoolId, Id]};
["logClientError"] -> {auth_any_bucket,
fun (R) ->
User = menelaus_auth:extract_auth(username, R),
ns_log:log(?MODULE, ?UI_SIDE_ERROR_REPORT,
"Client-side error-report for user ~p on node ~p:~nUser-Agent:~s~n~s~n",
[User, node(),
Req:get_header_value("user-agent"), binary_to_list(R:recv_body())]),
R:ok({"text/plain", add_header(), <<"">>})
end};
["diag", "eval"] -> {auth, fun handle_diag_eval/1};
["erlwsh" | _] ->
{done, erlwsh_web:loop(Req, erlwsh_deps:local_path(["priv", "www"]))};
_ ->
ns_log:log(?MODULE, 0001, "Invalid post received: ~p", [Req]),
{done, Req:not_found()}
end;
'DELETE' ->
case PathTokens of
["pools", PoolId, "buckets", Id] ->
{auth, fun menelaus_web_buckets:handle_bucket_delete/3, [PoolId, Id]};
["nodes", Node, "resources", LocationPath] ->
{auth, fun handle_resource_delete/3, [Node, LocationPath]};
_ ->
ns_log:log(?MODULE, 0002, "Invalid delete received: ~p as ~p", [Req, PathTokens]),
{done, Req:respond({405, add_header(), "Method Not Allowed"})}
end;
'PUT' ->
case PathTokens of
_ ->
ns_log:log(?MODULE, 0003, "Invalid put received: ~p", [Req]),
{done, Req:respond({405, add_header(), "Method Not Allowed"})}
end;
_ ->
ns_log:log(?MODULE, 0004, "Invalid request received: ~p", [Req]),
{done, Req:respond({405, add_header(), "Method Not Allowed"})}
end,
case Action of
{done, RV} -> RV;
{auth_cookie, F} -> menelaus_auth:apply_auth_cookie(Req, F, []);
{auth, F} -> menelaus_auth:apply_auth(Req, F, []);
{auth_cookie, F, Args} -> menelaus_auth:apply_auth_cookie(Req, F, Args);
{auth, F, Args} -> menelaus_auth:apply_auth(Req, F, Args);
{auth_bucket_with_info, F, [ArgPoolId, ArgBucketId | RestArgs]} ->
menelaus_web_buckets:checking_bucket_access(ArgPoolId, ArgBucketId, Req,
fun (Pool, Bucket) ->
apply(F, [ArgPoolId, ArgBucketId] ++ RestArgs ++ [Req, Pool, Bucket])
end);
{auth_bucket, F, [ArgPoolId, ArgBucketId | RestArgs]} ->
menelaus_web_buckets:checking_bucket_access(ArgPoolId, ArgBucketId, Req,
fun (_, _) ->
apply(F, [ArgPoolId, ArgBucketId] ++ RestArgs ++ [Req])
end);
{auth_any_bucket, F} -> menelaus_auth:apply_auth_bucket(Req, F, []);
{auth_any_bucket, F, Args} -> menelaus_auth:apply_auth_bucket(Req, F, Args)
end
catch
exit:normal ->
%% this happens when the client closed the connection
exit(normal);
Type:What ->
Report = ["web request failed",
{path, Req:get(path)},
{type, Type}, {what, What},
{trace, erlang:get_stacktrace()}], % todo: find a way to enable this for field info gathering
ns_log:log(?MODULE, 0019, "Server error during processing: ~p", [Report]),
reply_json(Req, [list_to_binary("Unexpected server error, request logged.")], 500)
end.
%% Internal API
implementation_version() ->
list_to_binary(proplists:get_value(ns_server, ns_info:version(), "unknown")).
handle_pools(Req) ->
Pools = [{struct,
[{name, <<"default">>},
{uri, list_to_binary(concat_url_path(["pools", "default"]))},
{streamingUri, list_to_binary(concat_url_path(["poolsStreaming", "default"]))}]}],
EffectivePools =
case is_system_provisioned() of
true -> Pools;
_ -> []
end,
reply_json(Req,{struct, [{pools, EffectivePools},
{isAdminCreds, menelaus_auth:is_under_admin(Req)},
{uuid, get_uuid()}
| build_versions()]}).
handle_engage_cluster2(Req) ->
Body = Req:recv_body(),
{struct, NodeKVList} = mochijson2:decode(Body),
%% a bit kludgy, but 100% correct way to protect ourselves when
%% everything will restart.
process_flag(trap_exit, true),
case ns_cluster:engage_cluster(NodeKVList) of
{ok, _} ->
handle_node("self", Req);
{error, _What, Message, _Nested} ->
reply_json(Req, [Message], 400)
end.
handle_complete_join(Req) ->
{struct, NodeKVList} = mochijson2:decode(Req:recv_body()),
erlang:process_flag(trap_exit, true),
case ns_cluster:complete_join(NodeKVList) of
{ok, _} ->
reply_json(Req, [], 200);
{error, _What, Message, _Nested} ->
reply_json(Req, [Message], 400)
end.
% Returns an UUID if it is already in the ns_config and generates
% a new one otherwise.
get_uuid() ->
case ns_config:search(uuid) of
false ->
Uuid = list_to_binary(uuid:to_string(uuid:srandom())),
Uuid;
{value, Uuid2} ->
Uuid2
end.
build_versions() ->
[{implementationVersion, implementation_version()},
{componentsVersion, {struct,
lists:map(fun ({K,V}) ->
{K, list_to_binary(V)}
end,
ns_info:version())}}].
handle_versions(Req) ->
reply_json(Req, {struct, build_versions()}).
% {"default", [
% {port, 11211},
% {buckets, [
% {"default", [
% {auth_plain, undefined},
% {size_per_node, 64}, % In MB.
% {cache_expiration_range, {0,600}}
% ]}
% ]}
% ]}
check_and_handle_pool_info(Id, Req) ->
case is_system_provisioned() of
true ->
Timeout = diag_handler:arm_timeout(23000),
try
handle_pool_info(Id, Req)
after
diag_handler:disarm_timeout(Timeout)
end;
_ ->
reply_json(Req, <<"unknown pool">>, 404)
end.
handle_pool_info(Id, Req) ->
UserPassword = menelaus_auth:extract_auth(Req),
LocalAddr = menelaus_util:local_addr(Req),
Query = Req:parse_qs(),
{WaitChangeS, PassedETag} = {proplists:get_value("waitChange", Query),
proplists:get_value("etag", Query)},
case WaitChangeS of
undefined -> reply_json(Req, build_pool_info(Id, UserPassword, normal, LocalAddr));
_ ->
WaitChange = list_to_integer(WaitChangeS),
menelaus_event:register_watcher(self()),
handle_pool_info_wait(Req, Id, UserPassword, LocalAddr, WaitChange, PassedETag)
end.
handle_pool_info_wait(Req, Id, UserPassword, LocalAddr, WaitChange, PassedETag) ->
Info = mochijson2:encode(build_pool_info(Id, UserPassword, stable, LocalAddr)),
%% ETag = base64:encode_to_string(crypto:sha(Info)),
ETag = integer_to_list(erlang:phash2(Info)),
if
ETag =:= PassedETag ->
receive
{notify_watcher, _} ->
timer:sleep(200), %% delay a bit to catch more notifications
handle_pool_info_wait(Req, Id, UserPassword, LocalAddr, 0, PassedETag);
_ ->
exit(normal)
after WaitChange ->
handle_pool_info_wait_tail(Req, Id, UserPassword, LocalAddr, ETag)
end;
true ->
handle_pool_info_wait_tail(Req, Id, UserPassword, LocalAddr, ETag)
end.
consume_notifications() ->
receive
{notify_watcher, _} -> consume_notifications()
after 0 ->
done
end.
handle_pool_info_wait_tail(Req, Id, UserPassword, LocalAddr, ETag) ->
menelaus_event:unregister_watcher(self()),
%% consume all notifications
consume_notifications(),
%% and reply
{struct, PList} = build_pool_info(Id, UserPassword, normal, LocalAddr),
Info = {struct, [{etag, list_to_binary(ETag)} | PList]},
reply_json(Req, Info).
build_pool_info(Id, UserPassword, InfoLevel, LocalAddr) ->
F = build_nodes_info_fun(menelaus_auth:check_auth(UserPassword), InfoLevel, LocalAddr),
Nodes = [F(N, undefined) || N <- ns_node_disco:nodes_wanted()],
BucketsVer = erlang:phash2(ns_bucket:get_bucket_names())
bxor erlang:phash2([{proplists:get_value(hostname, KV),
proplists:get_value(status, KV)} || {struct, KV} <- Nodes]),
BucketsInfo = {struct, [{uri,
list_to_binary(concat_url_path(["pools", Id, "buckets"])
++ "?v=" ++ integer_to_list(BucketsVer))}]},
RebalanceStatus = case ns_cluster_membership:get_rebalance_status() of
{running, _ProgressList} -> <<"running">>;
_ -> <<"none">>
end,
Uri = bin_concat_path(["pools", Id, "controller", "testWorkload"]),
Alerts = menelaus_web_alerts_srv:fetch_alerts(),
Controllers = {struct, [
{addNode, {struct, [{uri, <<"/controller/addNode">>}]}},
{rebalance, {struct, [{uri, <<"/controller/rebalance">>}]}},
{failOver, {struct, [{uri, <<"/controller/failOver">>}]}},
{reAddNode, {struct, [{uri, <<"/controller/reAddNode">>}]}},
{ejectNode, {struct, [{uri, <<"/controller/ejectNode">>}]}},
{testWorkload, {struct, [{uri, Uri}]}}]},
PropList0 = [{name, list_to_binary(Id)},
{alerts, Alerts},
{nodes, Nodes},
{buckets, BucketsInfo},
{controllers, Controllers},
{balanced, ns_cluster_membership:is_balanced()},
{failoverWarnings, ns_bucket:failover_warnings()},
{rebalanceStatus, RebalanceStatus},
{rebalanceProgressUri, bin_concat_path(["pools", Id, "rebalanceProgress"])},
{stopRebalanceUri, <<"/controller/stopRebalance">>},
{nodeStatusesUri, <<"/nodeStatuses">>},
{stats, {struct,
[{uri, bin_concat_path(["pools", Id, "stats"])}]}}],
PropList =
case InfoLevel of
normal ->
StorageTotals = [ {Key, {struct, StoragePList}}
|| {Key, StoragePList} <- ns_storage_conf:cluster_storage_info()],
[{storageTotals, {struct, StorageTotals}} | PropList0];
_ -> PropList0
end,
{struct, PropList}.
build_nodes_info() ->
F = build_nodes_info_fun(true, normal, "127.0.0.1"),
[F(N, undefined) || N <- ns_node_disco:nodes_wanted()].
%% builds health/warmup status of given node (w.r.t. given Bucket if
%% not undefined)
build_node_status(Node, Bucket, InfoNode, BucketsAll) ->
case proplists:get_bool(down, InfoNode) of
false ->
ReadyBuckets = proplists:get_value(ready_buckets, InfoNode),
NodeBucketNames = ns_bucket:node_bucket_names(Node, BucketsAll),
case Bucket of
undefined ->
case ordsets:is_subset(lists:sort(NodeBucketNames),
lists:sort(ReadyBuckets)) of
true ->
<<"healthy">>;
false ->
<<"warmup">>
end;
_ ->
case lists:member(Bucket, ReadyBuckets) of
true ->
<<"healthy">>;
false ->
case lists:member(Bucket, NodeBucketNames) of
true ->
<<"warmup">>;
false ->
<<"unhealthy">>
end
end
end;
true ->
<<"unhealthy">>
end.
build_nodes_info_fun(IncludeOtp, InfoLevel, LocalAddr) ->
OtpCookie = list_to_binary(atom_to_list(ns_node_disco:cookie_get())),
NodeStatuses = ns_doctor:get_nodes(),
Config = ns_config:get(),
BucketsAll = ns_bucket:get_buckets(Config),
fun(WantENode, Bucket) ->
InfoNode = case dict:find(WantENode, NodeStatuses) of
{ok, Info} -> Info;
error -> [down]
end,
KV = build_node_info(Config, WantENode, InfoNode, LocalAddr),
Status = build_node_status(WantENode, Bucket, InfoNode, BucketsAll),
KV1 = [{clusterMembership,
atom_to_binary(
ns_cluster_membership:get_cluster_membership(
WantENode, Config),
latin1)},
{status, Status}] ++ KV,
KV2 = case IncludeOtp of
true ->
[{otpNode,
list_to_binary(
atom_to_list(WantENode))},
{otpCookie, OtpCookie}|KV1];
false -> KV1
end,
KV3 = case Bucket of
undefined ->
KV2;
_ ->
Replication = proplists:get_value(replication,
InfoNode, []),
[{replication, proplists:get_value(Bucket,
Replication)}|KV2]
end,
KV4 = case InfoLevel of
stable -> KV3;
normal -> build_extra_node_info(Config, WantENode,
InfoNode, BucketsAll,
KV3)
end,
{struct, KV4}
end.
build_extra_node_info(Config, Node, InfoNode, _BucketsAll, Append) ->
{UpSecs, {MemoryTotal, MemoryAlloced, _}} =
{proplists:get_value(wall_clock, InfoNode, 0),
proplists:get_value(memory_data, InfoNode,
{0, 0, undefined})},
NodesBucketMemoryTotal = case ns_config:search_node_prop(Node,
Config,
memcached,
max_size) of
X when is_integer(X) -> X;
undefined -> (MemoryTotal * 4) div (5 * 1048576)
end,
NodesBucketMemoryAllocated = NodesBucketMemoryTotal,
[{systemStats, {struct, proplists:get_value(system_stats, InfoNode, [])}},
{interestingStats, {struct, proplists:get_value(interesting_stats, InfoNode, [])}},
%% TODO: deprecate this in API (we need 'stable' "startupTStamp"
%% first)
{uptime, list_to_binary(integer_to_list(UpSecs))},
%% TODO: deprecate this in API
{memoryTotal, erlang:trunc(MemoryTotal)},
%% TODO: deprecate this in API
{memoryFree, erlang:trunc(MemoryTotal - MemoryAlloced)},
%% TODO: deprecate this in API
{mcdMemoryReserved, erlang:trunc(NodesBucketMemoryTotal)},
%% TODO: deprecate this in API
{mcdMemoryAllocated, erlang:trunc(NodesBucketMemoryAllocated)}
| Append].
build_node_hostname(Config, Node, LocalAddr) ->
Host = case misc:node_name_host(Node) of
{_, "127.0.0.1"} -> LocalAddr;
{_Name, H} -> H
end,
Host ++ ":" ++ integer_to_list(misc:node_rest_port(Config, Node)).
build_node_info(Config, WantENode, InfoNode, LocalAddr) ->
DirectPort = ns_config:search_node_prop(WantENode, Config, memcached, port),
ProxyPort = ns_config:search_node_prop(WantENode, Config, moxi, port),
Versions = proplists:get_value(version, InfoNode, []),
Version = proplists:get_value(ns_server, Versions, "unknown"),
OS = proplists:get_value(system_arch, InfoNode, "unknown"),
HostName = build_node_hostname(Config, WantENode, LocalAddr),
[{hostname, list_to_binary(HostName)},
{clusterCompatibility, proplists:get_value(cluster_compatibility_version, InfoNode, 0)},
{version, list_to_binary(Version)},
{os, list_to_binary(OS)},
{ports, {struct, [{proxy, ProxyPort},
{direct, DirectPort}]}}
].
handle_pool_info_streaming(Id, Req) ->
UserPassword = menelaus_auth:extract_auth(Req),
LocalAddr = menelaus_util:local_addr(Req),
F = fun(InfoLevel) -> build_pool_info(Id, UserPassword, InfoLevel, LocalAddr) end,
handle_streaming(F, Req, undefined).
handle_streaming(F, Req, LastRes) ->
HTTPRes = Req:ok({"application/json; charset=utf-8",
server_header(),
chunked}),
%% Register to get config state change messages.
menelaus_event:register_watcher(self()),
Sock = Req:get(socket),
inet:setopts(Sock, [{active, true}]),
handle_streaming(F, Req, HTTPRes, LastRes).
streaming_inner(F, HTTPRes, LastRes) ->
Res = F(stable),
case Res =:= LastRes of
true ->
ok;
false ->
ResNormal = F(normal),
HTTPRes:write_chunk(mochijson2:encode(ResNormal)),
HTTPRes:write_chunk("\n\n\n\n")
end,
Res.
handle_streaming(F, Req, HTTPRes, LastRes) ->
Res =
try streaming_inner(F, HTTPRes, LastRes)
catch exit:normal ->
?log_info("closing streaming socket~n", []),
HTTPRes:write_chunk(""),
exit(normal)
end,
receive
{notify_watcher, _} -> ok;
_ ->
error_logger:info_msg("menelaus_web streaming socket closed by client~n"),
exit(normal)
after 25000 ->
ok
end,
handle_streaming(F, Req, HTTPRes, Res).
handle_join(Req) ->
%% paths:
%% cluster secured, admin logged in:
%% after creds work and node join happens,
%% 200 returned with Location header pointing
%% to new /pool/default
%% cluster not secured, after node join happens,
%% a 200 returned with Location header to new /pool/default,
%% 401 if request had
%% cluster either secured or not:
%% a 400 with json error message when join fails for whatever reason
%%
%% parameter example: clusterMemberHostIp=192%2E168%2E0%2E1&
%% clusterMemberPort=8091&
%% user=admin&password=admin123
%%
Params = Req:parse_post(),
ParsedOtherPort = (catch list_to_integer(proplists:get_value("clusterMemberPort", Params))),
% the erlang http client crashes if the port number is invalid, so we validate for ourselves here
NzV = if
is_integer(ParsedOtherPort) ->
if
ParsedOtherPort =< 0 -> <<"The port number must be greater than zero.">>;
ParsedOtherPort >65535 -> <<"The port number cannot be larger than 65535.">>;
true -> undefined
end;
true -> <<"The port number must be a number.">>
end,
OtherPort = if
NzV =:= undefined -> ParsedOtherPort;
true -> 0
end,
OtherHost = proplists:get_value("clusterMemberHostIp", Params),
OtherUser = proplists:get_value("user", Params),
OtherPswd = proplists:get_value("password", Params),
case lists:member(undefined,
[OtherHost, OtherPort, OtherUser, OtherPswd]) of
true -> ns_log:log(?MODULE, 0013, "Received request to join cluster missing a parameter.", []),
Req:respond({400, add_header(), "Attempt to join node to cluster received with missing parameters.\n"});
false ->
PossMsg = [NzV],
Msgs = lists:filter(fun (X) -> X =/= undefined end,
PossMsg),
case Msgs of
[] ->
handle_join_tail(Req, OtherHost, OtherPort, OtherUser, OtherPswd);
_ -> reply_json(Req, Msgs, 400)
end
end.
handle_join_tail(Req, OtherHost, OtherPort, OtherUser, OtherPswd) ->
process_flag(trap_exit, true),
{Username, Password} = case ns_config:search_prop(ns_config:get(), rest_creds, creds, []) of
[] -> {[], []};
[{U, PList} | _] ->
{U, proplists:get_value(password, PList)}
end,
RV = case ns_cluster:check_host_connectivity(OtherHost) of
{ok, MyIP} ->
{struct, MyPList} = build_full_node_info(node(), MyIP),
Hostname = misc:expect_prop_value(hostname, MyPList),
menelaus_rest:json_request_hilevel(post,
{OtherHost, OtherPort, "/controller/addNode",
"application/x-www-form-urlencoded",
mochiweb_util:urlencode([{<<"hostname">>, Hostname},
{<<"user">>, Username},
{<<"password">>, Password}])},
{OtherUser, OtherPswd});
X -> X
end,
case RV of
{ok, _} -> Req:respond({200, add_header(), []});
{client_error, JSON} ->
reply_json(Req, JSON, 400);
{error, _What, Message, _Nested} ->
reply_json(Req, [Message], 400)
end.
%% waits till only one node is left in cluster
do_eject_myself_rec(0, _) ->
exit(self_eject_failed);
do_eject_myself_rec(IterationsLeft, Period) ->
MySelf = node(),
case ns_node_disco:nodes_actual_proper() of
[MySelf] -> ok;
_ ->
timer:sleep(Period),
do_eject_myself_rec(IterationsLeft-1, Period)
end.
do_eject_myself() ->
ns_cluster:leave(),
do_eject_myself_rec(10, 250).
handle_eject_post(Req) ->
PostArgs = Req:parse_post(),
%
% either Eject a running node, or eject a node which is down.
%
% request is a urlencoded form with otpNode
%
% responses are 200 when complete
% 401 if creds were not supplied and are required
% 403 if creds were supplied and are incorrect
% 400 if the node to be ejected doesn't exist
%
OtpNodeStr = case proplists:get_value("otpNode", PostArgs) of
undefined -> undefined;
"Self" -> atom_to_list(node());
X -> X
end,
case OtpNodeStr of
undefined -> Req:respond({400, add_header(), "Bad Request\n"});
_ ->
OtpNode = list_to_atom(OtpNodeStr),
case ns_cluster_membership:get_cluster_membership(OtpNode) of
active ->
Req:respond({400, add_header(), "Cannot remove active server.\n"});
_ ->
do_handle_eject_post(Req, OtpNode)
end
end.
do_handle_eject_post(Req, OtpNode) ->
case OtpNode =:= node() of
true ->
do_eject_myself(),
Req:respond({200, [], []});
false ->
case lists:member(OtpNode, ns_node_disco:nodes_wanted()) of
true ->
ns_cluster:leave(OtpNode),
ns_log:log(?MODULE, ?NODE_EJECTED, "Node ejected: ~p from node: ~p",
[OtpNode, erlang:node()]),
Req:respond({200, add_header(), []});
false ->
% Node doesn't exist.
ns_log:log(?MODULE, 0018, "Request to eject nonexistant server failed. Requested node: ~p",
[OtpNode]),
Req:respond({400, add_header(), "Server does not exist.\n"})
end
end.
handle_pool_settings(_PoolId, Req) ->
Params = Req:parse_post(),
Node = node(),
Results = [case proplists:get_value("memoryQuota", Params) of
undefined -> ok;
X ->
{MinMemoryMB, MaxMemoryMB, QuotaErrorDetailsFun} =
ns_storage_conf:allowed_node_quota_range(),
case parse_validate_number(X, MinMemoryMB, MaxMemoryMB) of
{ok, Number} ->
{ok, fun () ->
ok = ns_storage_conf:change_memory_quota(Node, Number)
%% TODO: that should
%% really be a cluster setting
end};
invalid -> <<"The RAM Quota value must be a number.">>;
too_small ->
list_to_binary("The RAM Quota value is too small." ++ QuotaErrorDetailsFun());
too_large ->
list_to_binary("The RAM Quota value is too large." ++ QuotaErrorDetailsFun())
end
end],
case lists:filter(fun(ok) -> false;
({ok, _}) -> false;
(_) -> true
end, Results) of
[] ->
lists:foreach(fun ({ok, CommitF}) ->
CommitF();
(_) -> ok
end, Results),
Req:respond({200, add_header(), []});
Errs -> reply_json(Req, Errs, 400)
end.
handle_settings_web(Req) ->
reply_json(Req, build_settings_web()).
build_settings_web() ->
Config = ns_config:get(),
{U, P} = case ns_config:search_node_prop(Config, rest_creds, creds) of
[{User, Auth} | _] ->
{User, proplists:get_value(password, Auth, "")};
_NoneFound ->
{"", ""}
end,
Port = proplists:get_value(port, webconfig()),
build_settings_web(Port, U, P).
build_settings_web(Port, U, P) ->
{struct, [{port, Port},
{username, list_to_binary(U)},
{password, list_to_binary(P)}]}.
%% @doc Settings to en-/disable stats sending to some remote server
handle_settings_stats(Req) ->
reply_json(Req, {struct, build_settings_stats()}).
build_settings_stats() ->
Defaults = default_settings_stats_config(),
[{send_stats, SendStats}] = ns_config:search_prop(
ns_config:get(), settings, stats, Defaults),
[{sendStats, SendStats}].
default_settings_stats_config() ->
[{send_stats, false}].
handle_settings_stats_post(Req) ->
PostArgs = Req:parse_post(),
SendStats = proplists:get_value("sendStats", PostArgs),
case validate_settings_stats(SendStats) of
error ->
Req:respond({400, add_header(),
"The value of \"sendStats\" must be true or false."});
SendStats2 ->
ns_config:set(settings, [{stats, [{send_stats, SendStats2}]}]),
Req:respond({200, add_header(), []})
end.
validate_settings_stats(SendStats) ->
case SendStats of
"true" -> true;
"false" -> false;
_ -> error
end.
%% @doc Settings to en-/disable auto-failover
handle_settings_auto_failover(Req) ->
Config = build_settings_auto_failover(),
Enabled = proplists:get_value(enabled, Config),
Timeout = proplists:get_value(timeout, Config),
Count = proplists:get_value(count, Config),
reply_json(Req, {struct, [{enabled, Enabled},
{timeout, Timeout},
{count, Count}]}).
build_settings_auto_failover() ->
{value, Config} = ns_config:search(ns_config:get(), auto_failover_cfg),
Config.
handle_settings_auto_failover_post(Req) ->
PostArgs = Req:parse_post(),
ValidateOnly = proplists:get_value("just_validate", Req:parse_qs()) =:= "1",
Enabled = proplists:get_value("enabled", PostArgs),
Timeout = proplists:get_value("timeout", PostArgs),
% MaxNodes is hard-coded to 1 for now.
MaxNodes = "1",
case {ValidateOnly,
validate_settings_auto_failover(Enabled, Timeout, MaxNodes)} of
{false, [true, Timeout2, MaxNodes2]} ->
auto_failover:enable(Timeout2, MaxNodes2),
Req:respond({200, add_header(), []});
{false, false} ->
auto_failover:disable(),
Req:respond({200, add_header(), []});
{false, {error, Errors}} ->
Errors2 = [<<Msg/binary, "\n">> || {_, Msg} <- Errors],
Req:respond({400, add_header(), Errors2});
{true, {error, Errors}} ->
reply_json(Req, {struct, [{errors, {struct, Errors}}]}, 200);
% Validation only and no errors
{true, _}->
reply_json(Req, {struct, [{errors, null}]}, 200)
end.
validate_settings_auto_failover(Enabled, Timeout, MaxNodes) ->
Enabled2 = case Enabled of
"true" -> true;
"false" -> false;
_ -> {enabled, <<"The value of \"enabled\" must be true or false">>}
end,
case Enabled2 of
true ->
Errors = [is_valid_positive_integer_bigger_or_equal(Timeout, ?AUTO_FAILLOVER_MIN_TIMEOUT) orelse
{timeout, <<"The value of \"timeout\" must be a positive integer bigger or equal to 30">>},
is_valid_positive_integer(MaxNodes) orelse
{maxNodes, <<"The value of \"maxNodes\" must be a positive integer">>}],
case lists:filter(fun (E) -> E =/= true end, Errors) of
[] ->
[Enabled2, list_to_integer(Timeout),
list_to_integer(MaxNodes)];
Errors2 ->
{error, Errors2}
end;
false ->
Enabled2;
Error ->
{error, [Error]}
end.
is_valid_positive_integer(String) ->
Int = (catch list_to_integer(String)),
(is_integer(Int) andalso (Int > 0)).