/
menelaus_web_buckets.erl
2447 lines (2226 loc) · 106 KB
/
menelaus_web_buckets.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 Couchbase <info@couchbase.com>
%% @copyright 2009-Present Couchbase, Inc.
%%
%% Use of this software is governed by the Business Source License included
%% in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
%% in that file, in accordance with the Business Source License, use of this
%% software will be governed by the Apache License, Version 2.0, included in
%% the file licenses/APL2.txt.
%%
%% @doc handlers for bucket related REST API's
-module(menelaus_web_buckets).
-author('NorthScale <info@northscale.com>').
-include("menelaus_web.hrl").
-include("ns_common.hrl").
-include("couch_db.hrl").
-include("ns_stats.hrl").
-include("ns_bucket.hrl").
-include("cut.hrl").
-define(MAGMA_MIN_RAMQUOTA, 256).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-export([handle_bucket_list/1,
handle_bucket_info/3,
handle_sasl_buckets_streaming/2,
handle_bucket_info_streaming/3,
handle_bucket_delete/3,
handle_bucket_update/3,
handle_bucket_create/2,
create_bucket/3,
handle_bucket_flush/3,
handle_compact_bucket/3,
handle_purge_compact_bucket/3,
handle_cancel_bucket_compaction/3,
handle_compact_databases/3,
handle_cancel_databases_compaction/3,
handle_compact_view/4,
handle_cancel_view_compaction/4,
handle_ddocs_list/3,
handle_set_ddoc_update_min_changes/4,
handle_local_random_key/2,
handle_local_random_key/4,
maybe_cleanup_old_buckets/0,
serve_short_bucket_info/2,
serve_streaming_short_bucket_info/2,
get_ddocs_list/2]).
-import(menelaus_util,
[reply/2,
reply/3,
reply_text/3,
reply_json/2,
reply_json/3,
concat_url_path/1,
bin_concat_path/1,
bin_concat_path/2,
handle_streaming/2]).
-define(MAX_BUCKET_NAME_LEN, 100).
get_info_level(Req) ->
case proplists:get_value("basic_stats", mochiweb_request:parse_qs(Req)) of
undefined ->
normal;
_ ->
for_ui
end.
handle_bucket_list(Req) ->
Ctx = menelaus_web_node:get_context(Req, all, false, unstable),
Snapshot = menelaus_web_node:get_snapshot(Ctx),
BucketsUnsorted =
menelaus_auth:filter_accessible_buckets(
?cut({[{bucket, _}, settings], read}),
ns_bucket:get_bucket_names(Snapshot), Req),
Buckets = lists:sort(fun (A,B) -> A =< B end, BucketsUnsorted),
reply_json(Req, build_buckets_info(Req, Buckets, Ctx, get_info_level(Req))).
handle_bucket_info(_PoolId, Id, Req) ->
Ctx = menelaus_web_node:get_context(Req, [Id], false, unstable),
[Json] = build_buckets_info(Req, [Id], Ctx, get_info_level(Req)),
reply_json(Req, Json).
build_bucket_nodes_info(BucketName, BucketUUID, BucketConfig, Ctx) ->
%% Only list nodes this bucket is mapped to
F = menelaus_web_node:build_nodes_info_fun(Ctx),
Nodes = ns_bucket:get_servers(BucketConfig),
%% NOTE: there's potential inconsistency here between BucketConfig
%% and (potentially more up-to-date) vbuckets dict. Given that
%% nodes list is mostly informational I find it ok.
Dict = case vbucket_map_mirror:node_vbuckets_dict(BucketName) of
{ok, DV} -> DV;
{error, not_present} -> dict:new();
{error, no_map} -> dict:new()
end,
LocalAddr = menelaus_web_node:get_local_addr(Ctx),
add_couch_api_base_loop(Nodes, BucketName, BucketUUID, LocalAddr, F,
Dict, [], []).
add_couch_api_base_loop([], _BucketName, _BucketUUID, _LocalAddr, _F, _Dict, CAPINodes, NonCAPINodes) ->
CAPINodes ++ NonCAPINodes;
add_couch_api_base_loop([Node | RestNodes],
BucketName, BucketUUID, LocalAddr, F, Dict, CAPINodes, NonCAPINodes) ->
{struct, KV} = F(Node, BucketName),
case dict:find(Node, Dict) of
{ok, V} when V =/= [] ->
%% note this is generally always expected, but let's play safe just in case
S = {struct, add_couch_api_base(BucketName, BucketUUID, KV, Node, LocalAddr)},
add_couch_api_base_loop(RestNodes, BucketName, BucketUUID,
LocalAddr, F, Dict, [S | CAPINodes], NonCAPINodes);
_ ->
S = {struct, KV},
add_couch_api_base_loop(RestNodes, BucketName, BucketUUID,
LocalAddr, F, Dict, CAPINodes, [S | NonCAPINodes])
end.
add_couch_api_base(BucketName, BucketUUID, KV, Node, LocalAddr) ->
NodesKeysList = [{Node, couchApiBase}, {{ssl, Node}, couchApiBaseHTTPS}],
lists:foldl(fun({N, Key}, KVAcc) ->
case capi_utils:capi_bucket_url_bin(N, BucketName,
BucketUUID, LocalAddr) of
undefined ->
KVAcc;
Url ->
{ok, BCfg} = ns_bucket:get_bucket(BucketName),
case ns_bucket:bucket_type(BCfg) of
membase ->
[{Key, Url} | KVAcc];
_ ->
KVAcc
end
end
end, KV, NodesKeysList).
build_auto_compaction_info(BucketConfig) ->
case ns_bucket:is_persistent(BucketConfig) of
true ->
ACSettings = case proplists:get_value(autocompaction,
BucketConfig) of
undefined -> false;
false -> false;
ACSettingsX -> ACSettingsX
end,
case ACSettings of
false ->
[{autoCompactionSettings, false}];
_ ->
BackendStorage = ns_bucket:storage_backend(BucketConfig),
[{autoCompactionSettings,
menelaus_web_autocompaction:build_bucket_settings(
ACSettings, BackendStorage)}]
end;
false ->
case ns_bucket:storage_mode(BucketConfig) of
ephemeral ->
[];
undefined ->
%% When the bucket type is memcached.
[{autoCompactionSettings, false}]
end
end.
build_purge_interval_info(BucketConfig) ->
case ns_bucket:is_persistent(BucketConfig) of
true ->
case proplists:get_value(autocompaction, BucketConfig, false) of
false ->
[];
_Val ->
PInterval = case proplists:get_value(purge_interval,
BucketConfig) of
undefined ->
compaction_api:get_purge_interval(global);
PI -> PI
end,
[{purgeInterval, PInterval}]
end;
false ->
case ns_bucket:storage_mode(BucketConfig) of
ephemeral ->
[{purgeInterval, proplists:get_value(purge_interval,
BucketConfig)}];
undefined ->
%% When the bucket type is memcached.
[]
end
end.
build_eviction_policy(BucketConfig) ->
case ns_bucket:eviction_policy(BucketConfig) of
value_only ->
<<"valueOnly">>;
full_eviction ->
<<"fullEviction">>;
no_eviction ->
<<"noEviction">>;
nru_eviction ->
<<"nruEviction">>
end.
build_durability_min_level(BucketConfig) ->
case ns_bucket:durability_min_level(BucketConfig) of
undefined ->
<<"none">>;
none ->
<<"none">>;
majority ->
<<"majority">>;
majority_and_persist_on_master ->
<<"majorityAndPersistActive">>;
persist_to_majority ->
<<"persistToMajority">>
end.
build_buckets_info(Req, Buckets, Ctx, InfoLevel) ->
SkipMap = InfoLevel =/= streaming andalso
proplists:get_value(
"skipMap", mochiweb_request:parse_qs(Req)) =:= "true",
[build_bucket_info(BucketName, Ctx, InfoLevel, SkipMap) ||
BucketName <- Buckets].
build_bucket_info(Id, Ctx, InfoLevel, SkipMap) ->
Snapshot = menelaus_web_node:get_snapshot(Ctx),
{ok, BucketConfig} = ns_bucket:get_bucket(Id, Snapshot),
BucketUUID = ns_bucket:uuid(Id, Snapshot),
{lists:flatten(
[bucket_info_cache:build_short_bucket_info(Id, BucketConfig, Snapshot),
bucket_info_cache:build_ddocs(Id, BucketConfig),
[bucket_info_cache:build_vbucket_map(
menelaus_web_node:get_local_addr(Ctx), BucketConfig)
|| not SkipMap],
{localRandomKeyUri,
bucket_info_cache:build_pools_uri(["buckets", Id, "localRandomKey"])},
{controllers, {build_controllers(Id, BucketConfig)}},
{nodes,
menelaus_util:strip_json_struct(
build_bucket_nodes_info(Id, BucketUUID, BucketConfig, Ctx))},
{stats,
{[{uri, bucket_info_cache:build_pools_uri(["buckets", Id, "stats"])},
{directoryURI,
bucket_info_cache:build_pools_uri(["buckets", Id, "stats",
"Directory"])},
{nodeStatsListURI,
bucket_info_cache:build_pools_uri(["buckets", Id, "nodes"])}]}},
build_auto_compaction_info(BucketConfig),
build_purge_interval_info(BucketConfig),
build_replica_index(BucketConfig),
build_dynamic_bucket_info(InfoLevel, Id, BucketConfig, Ctx)])}.
build_replica_index(BucketConfig) ->
[{replicaIndex, proplists:get_value(replica_index, BucketConfig, true)} ||
ns_bucket:can_have_views(BucketConfig)].
build_controller(Id, Controller) ->
bucket_info_cache:build_pools_uri(["buckets", Id, "controller",
Controller]).
build_controllers(Id, BucketConfig) ->
[{compactAll, build_controller(Id, "compactBucket")},
{compactDB, build_controller(Id, "compactDatabases")},
{purgeDeletes, build_controller(Id, "unsafePurgeBucket")},
{startRecovery, build_controller(Id, "startRecovery")} |
[{flush, build_controller(Id, "doFlush")} ||
proplists:get_value(flush_enabled, BucketConfig, false)]].
build_bucket_stats(for_ui, Id, Ctx) ->
Config = menelaus_web_node:get_config(Ctx),
Snapshot = menelaus_web_node:get_snapshot(Ctx),
StorageTotals = [{Key, {StoragePList}}
|| {Key, StoragePList} <-
ns_storage_conf:cluster_storage_info(Config,
Snapshot)],
[{storageTotals, {StorageTotals}} | menelaus_stats:basic_stats(Id)];
build_bucket_stats(_, Id, _) ->
menelaus_stats:basic_stats(Id).
build_dynamic_bucket_info(streaming, _Id, _BucketConfig, _) ->
[];
build_dynamic_bucket_info(InfoLevel, Id, BucketConfig, Ctx) ->
[[{replicaNumber, ns_bucket:num_replicas(BucketConfig)},
{threadsNumber, proplists:get_value(num_threads, BucketConfig,
?NUM_WORKER_THREADS)},
{quota, {[{ram, ns_bucket:ram_quota(BucketConfig)},
{rawRAM, ns_bucket:raw_ram_quota(BucketConfig)}]}},
{basicStats, {build_bucket_stats(InfoLevel, Id, Ctx)}},
{evictionPolicy, build_eviction_policy(BucketConfig)},
{storageBackend, ns_bucket:storage_backend(BucketConfig)},
{durabilityMinLevel, build_durability_min_level(BucketConfig)},
build_pitr_dynamic_bucket_info(BucketConfig),
build_magma_bucket_info(BucketConfig),
{conflictResolutionType,
ns_bucket:conflict_resolution_type(BucketConfig)}],
case cluster_compat_mode:is_enterprise() of
true ->
[{maxTTL, proplists:get_value(max_ttl, BucketConfig, 0)},
{compressionMode,
proplists:get_value(compression_mode, BucketConfig, off)}];
false ->
[]
end,
case ns_bucket:drift_thresholds(BucketConfig) of
undefined ->
[];
{DriftAheadThreshold, DriftBehindThreshold} ->
[{driftAheadThresholdMs, DriftAheadThreshold},
{driftBehindThresholdMs, DriftBehindThreshold}]
end].
build_pitr_dynamic_bucket_info(BucketConfig) ->
case ns_bucket:bucket_type(BucketConfig) of
memcached ->
%% memcached buckets don't support pitr.
[];
_ ->
[{pitrEnabled, ns_bucket:pitr_enabled(BucketConfig)},
{pitrGranularity, ns_bucket:pitr_granularity(BucketConfig)},
{pitrMaxHistoryAge, ns_bucket:pitr_max_history_age(BucketConfig)}]
end.
build_magma_bucket_info(BucketConfig) ->
case ns_bucket:storage_mode(BucketConfig) of
magma ->
[{storageQuotaPercentage,
proplists:get_value(storage_quota_percentage, BucketConfig,
?MAGMA_STORAGE_QUOTA_PERCENTAGE)}];
_ ->
[]
end.
handle_sasl_buckets_streaming(_PoolId, Req) ->
LocalAddr = menelaus_util:local_addr(Req),
F = fun (_, _) ->
List = [build_sasl_bucket_info({Id, BucketConfig}, LocalAddr) ||
{Id, BucketConfig} <- ns_bucket:get_buckets()],
{just_write, {[{buckets, List}]}}
end,
handle_streaming(F, Req).
build_sasl_bucket_nodes(BucketConfig, LocalAddr) ->
{nodes,
[{[{hostname, menelaus_web_node:build_node_hostname(
ns_config:latest(), N, LocalAddr)},
{ports, {[{direct,
service_ports:get_port(
memcached_port, ns_config:latest(), N)}]}}]} ||
N <- ns_bucket:get_servers(BucketConfig)]}.
build_sasl_bucket_info({Id, BucketConfig}, LocalAddr) ->
{lists:flatten(
[bucket_info_cache:build_name_and_locator(Id, BucketConfig),
bucket_info_cache:build_vbucket_map(LocalAddr, BucketConfig),
build_sasl_bucket_nodes(BucketConfig, LocalAddr)])}.
build_streaming_info(Id, Req, LocalAddr, UpdateID) ->
ns_server_stats:notify_counter(<<"build_streaming_info">>),
case ns_bucket:bucket_exists(Id, direct) of
true ->
menelaus_web_cache:lookup_or_compute_with_expiration(
{build_bucket_info, Id, LocalAddr},
fun () ->
Ctx = menelaus_web_node:get_context(
{ip, LocalAddr}, [Id], false, stable),
[Info] = build_buckets_info(Req, [Id], Ctx, streaming),
{Info, 1000, UpdateID}
end,
fun (_Key, _Value, OldUpdateID) ->
UpdateID > OldUpdateID
end);
false ->
exit(normal)
end.
handle_bucket_info_streaming(_PoolId, Id, Req) ->
LocalAddr = menelaus_util:local_addr(Req),
handle_streaming(
fun(_Stability, UpdateID) ->
{just_write,
build_streaming_info(Id, Req, LocalAddr, UpdateID)}
end, Req).
handle_bucket_delete(_PoolId, BucketId, Req) ->
menelaus_web_rbac:assert_no_users_upgrade(),
?log_debug("Received request to delete bucket \"~s\"; will attempt to delete", [BucketId]),
case ns_orchestrator:delete_bucket(BucketId) of
ok ->
ns_audit:delete_bucket(Req, BucketId),
?MENELAUS_WEB_LOG(?BUCKET_DELETED, "Deleted bucket \"~s\"~n", [BucketId]),
reply(Req, 200);
rebalance_running ->
reply_json(Req, {struct, [{'_', <<"Cannot delete buckets during rebalance.\r\n">>}]}, 503);
in_recovery ->
reply_json(Req, {struct, [{'_', <<"Cannot delete buckets when cluster is in recovery mode.\r\n">>}]}, 503);
{shutdown_failed, _} ->
reply_json(Req, {struct, [{'_', <<"Bucket deletion not yet complete, but will continue.\r\n">>}]}, 500);
{exit, {not_found, _}, _} ->
reply_text(Req, "The bucket to be deleted was not found.\r\n", 404)
end.
respond_bucket_created(Req, PoolId, BucketId) ->
reply(Req, 202, [{"Location", concat_url_path(["pools", PoolId, "buckets", BucketId])}]).
-record(bv_ctx, {
validate_only,
ignore_warnings,
new,
bucket_name,
bucket_config,
all_buckets,
kv_nodes,
max_replicas,
cluster_storage_totals,
cluster_version,
is_enterprise,
is_developer_preview}).
init_bucket_validation_context(IsNew, BucketName, Req) ->
ValidateOnly = (proplists:get_value("just_validate", mochiweb_request:parse_qs(Req)) =:= "1"),
IgnoreWarnings = (proplists:get_value("ignore_warnings", mochiweb_request:parse_qs(Req)) =:= "1"),
init_bucket_validation_context(IsNew, BucketName, ValidateOnly, IgnoreWarnings).
init_bucket_validation_context(IsNew, BucketName, ValidateOnly,
IgnoreWarnings) ->
Config = ns_config:get(),
Snapshot =
chronicle_compat:get_snapshot(
[ns_bucket:fetch_snapshot(all, _),
ns_cluster_membership:fetch_snapshot(_)], #{ns_config => Config}),
KvNodes = ns_cluster_membership:service_active_nodes(Snapshot, kv),
ServerGroups = ns_cluster_membership:server_groups(Snapshot),
init_bucket_validation_context(
IsNew, BucketName,
ns_bucket:get_buckets(Snapshot),
KvNodes, ServerGroups,
ns_storage_conf:cluster_storage_info(Config, Snapshot),
ValidateOnly, IgnoreWarnings,
cluster_compat_mode:get_compat_version(),
cluster_compat_mode:is_enterprise(),
cluster_compat_mode:is_developer_preview()).
init_bucket_validation_context(IsNew, BucketName, AllBuckets,
KvNodes, ServerGroups,
ClusterStorageTotals,
ValidateOnly, IgnoreWarnings,
ClusterVersion, IsEnterprise,
IsDeveloperPreview) ->
KvServerGroups =
ns_cluster_membership:get_nodes_server_groups(KvNodes, ServerGroups),
NumKvNodes = length(KvNodes),
%% Maximum number of replicas that we'll be able to place in the current
%% cluster configuration.
MaxReplicas =
case ns_cluster_membership:rack_aware(KvServerGroups) of
true ->
min(length(KvServerGroups), NumKvNodes) - 1;
false ->
NumKvNodes - 1
end,
BucketConfig =
case lists:keyfind(BucketName, 1, AllBuckets) of
false ->
false;
{_, V} ->
V
end,
#bv_ctx{
validate_only = ValidateOnly,
ignore_warnings = IgnoreWarnings,
new = IsNew,
bucket_name = BucketName,
all_buckets = AllBuckets,
kv_nodes = KvNodes,
max_replicas = MaxReplicas,
bucket_config = BucketConfig,
cluster_storage_totals = ClusterStorageTotals,
cluster_version = ClusterVersion,
is_enterprise = IsEnterprise,
is_developer_preview = IsDeveloperPreview
}.
handle_bucket_update(_PoolId, BucketId, Req) ->
menelaus_web_rbac:assert_no_users_upgrade(),
Params = mochiweb_request:parse_post(Req),
handle_bucket_update_inner(BucketId, Req, Params, 32).
handle_bucket_update_inner(_BucketId, _Req, _Params, 0) ->
exit(bucket_update_loop);
handle_bucket_update_inner(BucketId, Req, Params, Limit) ->
Ctx = init_bucket_validation_context(false, BucketId, Req),
case {Ctx#bv_ctx.validate_only, Ctx#bv_ctx.ignore_warnings,
parse_bucket_params(Ctx, Params)} of
{_, _, {errors, Errors, JSONSummaries}} ->
RV = {struct, [{errors, {struct, Errors}},
{summaries, {struct, JSONSummaries}}]},
reply_json(Req, RV, 400);
{false, _, {ok, ParsedProps, _}} ->
BucketType = proplists:get_value(bucketType, ParsedProps),
StorageMode = proplists:get_value(storage_mode, ParsedProps,
undefined),
UpdatedProps = ns_bucket:extract_bucket_props(ParsedProps),
case ns_orchestrator:update_bucket(BucketType, StorageMode,
BucketId, UpdatedProps) of
ok ->
ns_audit:modify_bucket(Req, BucketId, BucketType, UpdatedProps),
DisplayBucketType = ns_bucket:display_type(BucketType,
StorageMode),
ale:info(?USER_LOGGER, "Updated bucket \"~s\" (of type ~s) properties:~n~p",
[BucketId, DisplayBucketType, UpdatedProps]),
reply(Req, 200);
rebalance_running ->
reply_text(Req,
"Cannot update bucket "
"while rebalance is running.", 503);
in_recovery ->
reply_text(Req,
"Cannot update bucket "
"while recovery is in progress.", 503);
{exit, {not_found, _}, _} ->
%% if this happens then our validation raced, so repeat everything
handle_bucket_update_inner(BucketId, Req, Params, Limit-1)
end;
{true, true, {ok, _, JSONSummaries}} ->
reply_json(Req, {struct, [{errors, {struct, []}},
{summaries, {struct, JSONSummaries}}]}, 200);
{true, false, {ok, ParsedProps, JSONSummaries}} ->
FinalErrors = perform_warnings_validation(Ctx, ParsedProps, []),
reply_json(Req, {struct, [{errors, {struct, FinalErrors}},
{summaries, {struct, JSONSummaries}}]},
case FinalErrors of
[] -> 202;
_ -> 400
end)
end.
maybe_cleanup_old_buckets() ->
case ns_config_auth:is_system_provisioned() of
true ->
ok;
false ->
true = ns_node_disco:nodes_wanted() =:= [node()],
ns_storage_conf:delete_unused_buckets_db_files()
end.
create_bucket(Req, Name, Params) ->
Ctx = init_bucket_validation_context(true, Name, false, false),
do_bucket_create(Req, Name, Params, Ctx).
do_bucket_create(Req, Name, ParsedProps) ->
BucketType = proplists:get_value(bucketType, ParsedProps),
StorageMode = proplists:get_value(storage_mode, ParsedProps, undefined),
BucketProps = ns_bucket:extract_bucket_props(ParsedProps),
maybe_cleanup_old_buckets(),
case ns_orchestrator:create_bucket(BucketType, Name, BucketProps) of
ok ->
ns_audit:create_bucket(Req, Name, BucketType, BucketProps),
DisplayBucketType = ns_bucket:display_type(BucketType, StorageMode),
?MENELAUS_WEB_LOG(?BUCKET_CREATED, "Created bucket \"~s\" of type: ~s~n~p",
[Name, DisplayBucketType, BucketProps]),
ok;
{error, {already_exists, _}} ->
{errors, [{name, <<"Bucket with given name already exists">>}]};
{error, {still_exists, _}} ->
{errors_500, [{'_', <<"Bucket with given name still exists">>}]};
{error, {invalid_name, _}} ->
{errors, [{name, <<"Name is invalid.">>}]};
rebalance_running ->
{errors_500, [{'_', <<"Cannot create buckets during rebalance">>}]};
in_recovery ->
{errors_500, [{'_', <<"Cannot create buckets when cluster is in recovery mode">>}]}
end.
do_bucket_create(Req, Name, Params, Ctx) ->
MaxBuckets = ns_bucket:get_max_buckets(),
case length(Ctx#bv_ctx.all_buckets) >= MaxBuckets of
true ->
{{struct, [{'_', iolist_to_binary(io_lib:format("Cannot create more than ~w buckets", [MaxBuckets]))}]}, 400};
false ->
case {Ctx#bv_ctx.validate_only, Ctx#bv_ctx.ignore_warnings,
parse_bucket_params(Ctx, Params)} of
{_, _, {errors, Errors, JSONSummaries}} ->
{{struct, [{errors, {struct, Errors}},
{summaries, {struct, JSONSummaries}}]}, 400};
{false, _, {ok, ParsedProps, _}} ->
case do_bucket_create(Req, Name, ParsedProps) of
ok -> ok;
{errors, Errors} ->
?log_debug("Failed to create bucket '~s' with 40X error(s): ~p",
[Name, Errors]),
{{struct, Errors}, 400};
{errors_500, Errors} ->
?log_debug("Failed to create bucket '~s' with 50X error(s): ~p",
[Name, Errors]),
{{struct, Errors}, 503}
end;
{true, true, {ok, _, JSONSummaries}} ->
{{struct, [{errors, {struct, []}},
{summaries, {struct, JSONSummaries}}]}, 200};
{true, false, {ok, ParsedProps, JSONSummaries}} ->
FinalErrors = perform_warnings_validation(Ctx, ParsedProps, []),
{{struct, [{errors, {struct, FinalErrors}},
{summaries, {struct, JSONSummaries}}]},
case FinalErrors of
[] -> 200;
_ -> 400
end}
end
end.
handle_bucket_create(PoolId, Req) ->
menelaus_web_rbac:assert_no_users_upgrade(),
Params = mochiweb_request:parse_post(Req),
Name = proplists:get_value("name", Params),
Ctx = init_bucket_validation_context(true, Name, Req),
case do_bucket_create(Req, Name, Params, Ctx) of
ok ->
respond_bucket_created(Req, PoolId, Name);
{Struct, Code} ->
reply_json(Req, Struct, Code)
end.
perform_warnings_validation(Ctx, ParsedProps, Errors) ->
Errors ++
num_replicas_warnings_validation(Ctx, proplists:get_value(num_replicas, ParsedProps)).
num_replicas_warnings_validation(_Ctx, undefined) ->
[];
num_replicas_warnings_validation(Ctx, NReplicas) ->
Warnings =
if
NReplicas > Ctx#bv_ctx.max_replicas ->
["you do not have enough data servers or "
"server groups to support this number of replicas"];
true ->
[]
end ++
case {Ctx#bv_ctx.new, Ctx#bv_ctx.bucket_config} of
{true, _} ->
[];
{_, false} ->
[];
{false, BucketConfig} ->
case ns_bucket:num_replicas(BucketConfig) of
NReplicas ->
[];
_ ->
["changing replica number may require rebalance"]
end
end,
Msg = case Warnings of
[] ->
[];
[A] ->
A;
[B, C] ->
B ++ " and " ++ C
end,
case Msg of
[] ->
[];
_ ->
[{replicaNumber, ?l2b("Warning: " ++ Msg ++ ".")}]
end.
handle_bucket_flush(_PoolId, Id, Req) ->
XDCRDocs = goxdcr_rest:find_all_replication_docs(),
case lists:any(
fun (PList) ->
erlang:binary_to_list(proplists:get_value(source, PList)) =:= Id
end, XDCRDocs) of
false ->
do_handle_bucket_flush(Id, Req);
true ->
reply_json(Req, {struct, [{'_', <<"Cannot flush buckets with outgoing XDCR">>}]}, 503)
end.
do_handle_bucket_flush(BucketName, Req) ->
case ns_orchestrator:flush_bucket(BucketName) of
ok ->
ns_audit:flush_bucket(Req, BucketName),
reply(Req, 200);
rebalance_running ->
reply_json(Req, {struct, [{'_', <<"Cannot flush buckets during rebalance">>}]}, 503);
in_recovery ->
reply_json(Req, {struct, [{'_', <<"Cannot flush buckets when cluster is in recovery mode">>}]}, 503);
bucket_not_found ->
reply(Req, 404);
flush_disabled ->
reply_json(Req, {struct, [{'_', <<"Flush is disabled for the bucket">>}]}, 400);
_ ->
reply_json(Req, {struct, [{'_', <<"Flush failed with unexpected error. Check server logs for details.">>}]}, 500)
end.
-record(ram_summary, {
total, % total cluster quota
other_buckets,
per_node, % per node quota of this bucket
nodes_count, % node count of this bucket
this_alloc,
this_used, % part of this bucket which is used already
free}). % total - other_buckets - this_alloc.
% So it's: Amount of cluster quota available for allocation
-record(hdd_summary, {
total, % total cluster disk space
other_data, % disk space used by something other than our data
other_buckets, % space used for other buckets
this_used, % space already used by this bucket
free}). % total - other_data - other_buckets - this_alloc
% So it's kind of: Amount of cluster disk space available of allocation,
% but with a number of 'but's.
parse_bucket_params(Ctx, Params) ->
RV = parse_bucket_params_without_warnings(Ctx, Params),
case {Ctx#bv_ctx.ignore_warnings, RV} of
{_, {ok, _, _} = X} -> X;
{false, {errors, Errors, Summaries, OKs}} ->
{errors, perform_warnings_validation(Ctx, OKs, Errors), Summaries};
{true, {errors, Errors, Summaries, _}} ->
{errors, Errors, Summaries}
end.
parse_bucket_params_without_warnings(Ctx, Params) ->
{OKs, Errors} = basic_bucket_params_screening(Ctx ,Params),
ClusterStorageTotals = Ctx#bv_ctx.cluster_storage_totals,
IsNew = Ctx#bv_ctx.new,
CurrentBucket = proplists:get_value(currentBucket, OKs),
HasRAMQuota = lists:keyfind(ram_quota, 1, OKs) =/= false,
RAMSummary = if
HasRAMQuota ->
interpret_ram_quota(Ctx, CurrentBucket, OKs,
ClusterStorageTotals);
true ->
interpret_ram_quota(Ctx, CurrentBucket,
[{ram_quota, 0} | OKs],
ClusterStorageTotals)
end,
HDDSummary = interpret_hdd_quota(CurrentBucket, OKs, ClusterStorageTotals, Ctx),
JSONSummaries = [{ramSummary, {struct, ram_summary_to_proplist(RAMSummary)}},
{hddSummary, {struct, hdd_summary_to_proplist(HDDSummary)}}],
Errors2 = case {CurrentBucket, IsNew} of
{undefined, _} -> Errors;
{_, true} -> Errors;
{_, false} ->
case {proplists:get_value(bucketType, OKs),
ns_bucket:bucket_type(CurrentBucket)} of
{undefined, _} -> Errors;
{NewType, NewType} -> Errors;
{_NewType, _OldType} ->
[{bucketType, <<"Cannot change bucket type.">>}
| Errors]
end
end,
RAMErrors =
if
RAMSummary#ram_summary.free < 0 ->
[{ramQuota, <<"RAM quota specified is too large to be provisioned into this cluster.">>}];
RAMSummary#ram_summary.this_alloc < RAMSummary#ram_summary.this_used ->
[{ramQuota, <<"RAM quota cannot be set below current usage.">>}];
true ->
[]
end,
TotalErrors = RAMErrors ++ Errors2,
if
TotalErrors =:= [] ->
{ok, OKs, JSONSummaries};
true ->
{errors, TotalErrors, JSONSummaries, OKs}
end.
additional_bucket_params_validation(Params, Ctx) ->
NumReplicas = get_value_from_parms_or_bucket(num_replicas, Params, Ctx),
DurabilityLevel = get_value_from_parms_or_bucket(durability_min_level,
Params, Ctx),
NodesCount = length(get_nodes(Ctx)),
Err1 = case {NumReplicas, DurabilityLevel, NodesCount} of
{0, _, _} -> [];
{_, none, _} -> [];
{3, _, _} -> [{durability_min_level,
<<"Durability minimum level cannot be specified with "
"3 replicas">>}];
%% memcached bucket
{undefined, undefined, _} -> [];
{_, _, 1} -> [{durability_min_level,
<<"You do not have enough data servers to support this "
"durability level">>}];
{_, _, _} -> []
end,
StorageMode = get_value_from_parms_or_bucket(storage_mode, Params, Ctx),
RamQuota = get_value_from_parms_or_bucket(ram_quota, Params, Ctx),
Err2 = case {StorageMode, RamQuota} of
{magma, RamQuota}
when RamQuota < ?MAGMA_MIN_RAMQUOTA * 1024 * 1024 ->
RamQ = list_to_binary(integer_to_list(?MAGMA_MIN_RAMQUOTA)),
[{ramQuota,
<<"Ram quota for magma must be at least ", RamQ/binary,
" MiB">>}];
{_, _} ->
[]
end,
Err1 ++ Err2.
%% Get the value from the params. If it wasn't specified and this isn't
%% a bucket creation then get the existing value from the bucket config.
get_value_from_parms_or_bucket(Key, Params,
#bv_ctx{bucket_config = BucketConfig,
new = IsNew}) ->
case proplists:get_value(Key, Params) of
undefined ->
case IsNew of
true -> undefined;
false -> proplists:get_value(Key, BucketConfig, undefined)
end;
Value -> Value
end.
basic_bucket_params_screening(#bv_ctx{bucket_config = false, new = false}, _Params) ->
{[], [{name, <<"Bucket with given name doesn't exist">>}]};
basic_bucket_params_screening(Ctx, Params) ->
CommonParams = validate_common_params(Ctx, Params),
TypeSpecificParams =
validate_bucket_type_specific_params(CommonParams, Params, Ctx),
Candidates = CommonParams ++ TypeSpecificParams,
assert_candidates(Candidates),
%% Basic parameter checking has been done. Take the non-error key/values
%% and do additional checking (e.g. relationships between different
%% keys).
OKs = [{K, V} || {ok, K, V} <- Candidates],
Errors = [{K, V} || {error, K, V} <- Candidates],
AdditionalErrors = additional_bucket_params_validation(OKs, Ctx),
{OKs, Errors ++ AdditionalErrors}.
validate_common_params(#bv_ctx{bucket_name = BucketName,
bucket_config = BucketConfig, new = IsNew,
all_buckets = AllBuckets}, Params) ->
[{ok, name, BucketName},
parse_validate_flush_enabled(Params, IsNew),
validate_bucket_name(IsNew, BucketConfig, BucketName, AllBuckets),
parse_validate_ram_quota(Params, BucketConfig),
parse_validate_other_buckets_ram_quota(Params),
validate_moxi_port(Params)].
validate_bucket_type_specific_params(CommonParams, Params,
#bv_ctx{new = IsNew,
bucket_config = BucketConfig,
cluster_version = Version,
is_enterprise = IsEnterprise,
is_developer_preview =
IsDeveloperPreview}) ->
BucketType = get_bucket_type(IsNew, BucketConfig, Params),
case BucketType of
memcached ->
validate_memcached_bucket_params(CommonParams, Params, IsNew,
BucketConfig);
membase ->
validate_membase_bucket_params(CommonParams, Params, IsNew,
BucketConfig, Version, IsEnterprise,
IsDeveloperPreview);
_ ->
validate_unknown_bucket_params(Params)
end.
validate_memcached_params(Params) ->
case proplists:get_value("replicaNumber", Params) of
undefined ->
ignore;
_ ->
{error, replicaNumber,
<<"replicaNumber is not valid for memcached buckets">>}
end.
validate_memcached_bucket_params(CommonParams, Params, IsNew, BucketConfig) ->
[{ok, bucketType, memcached},
validate_memcached_params(Params),
quota_size_error(CommonParams, memcached, IsNew, BucketConfig)].
validate_membase_bucket_params(CommonParams, Params,
IsNew, BucketConfig, Version, IsEnterprise,
IsDeveloperPreview) ->
ReplicasNumResult = validate_replicas_number(Params, IsNew),
BucketParams =
[{ok, bucketType, membase},
ReplicasNumResult,
parse_validate_replica_index(Params, ReplicasNumResult, IsNew),
parse_validate_threads_number(Params, IsNew),
parse_validate_eviction_policy(Params, BucketConfig, IsNew),
quota_size_error(CommonParams, membase, IsNew, BucketConfig),
parse_validate_storage_mode(Params, BucketConfig, IsNew, Version,
IsEnterprise),
parse_validate_durability_min_level(Params, BucketConfig, IsNew,
Version),
parse_validate_pitr_enabled(Params, IsNew, IsDeveloperPreview),
parse_validate_pitr_granularity(Params, IsNew, IsDeveloperPreview),
parse_validate_pitr_max_history_age(Params, IsNew, IsDeveloperPreview),
parse_validate_storage_quota_percentage(Params, BucketConfig, IsNew, Version,
IsEnterprise),
parse_validate_max_ttl(Params, BucketConfig, IsNew, IsEnterprise),
parse_validate_compression_mode(Params, BucketConfig, IsNew,
IsEnterprise)
| validate_bucket_auto_compaction_settings(Params)],
validate_bucket_purge_interval(Params, BucketConfig, IsNew) ++
get_conflict_resolution_type_and_thresholds(Params, BucketConfig, IsNew) ++
BucketParams.
validate_unknown_bucket_params(Params) ->
[{error, bucketType, <<"invalid bucket type">>}
| validate_bucket_auto_compaction_settings(Params)].
parse_validate_flush_enabled(Params, IsNew) ->
validate_with_missing(proplists:get_value("flushEnabled", Params),
"0", IsNew, fun parse_validate_flush_enabled/1).
validate_bucket_name(_IsNew, _BucketConfig, [] = _BucketName, _AllBuckets) ->
{error, name, <<"Bucket name cannot be empty">>};
validate_bucket_name(_IsNew, _BucketConfig, undefined = _BucketName, _AllBuckets) ->
{error, name, <<"Bucket name needs to be specified">>};
validate_bucket_name(_IsNew, _BucketConfig, BucketName, _AllBuckets)
when length(BucketName) > ?MAX_BUCKET_NAME_LEN ->
{error, name, ?l2b(io_lib:format("Bucket name cannot exceed ~p characters",
[?MAX_BUCKET_NAME_LEN]))};
validate_bucket_name(true = _IsNew, _BucketConfig, BucketName, AllBuckets) ->
case ns_bucket:is_valid_bucket_name(BucketName) of
{error, invalid} ->
{error, name,
<<"Bucket name can only contain characters in range A-Z, a-z, 0-9 "
"as well as underscore, period, dash & percent. Consult the documentation.">>};
{error, reserved} ->
{error, name, <<"This name is reserved for the internal use.">>};
{error, starts_with_dot} ->
{error, name, <<"Bucket name cannot start with dot.">>};
_ ->
%% we have to check for conflict here because we were looking
%% for BucketConfig using case sensetive search (in basic_bucket_params_screening/4)
%% but we do not allow buckets with the same names in a different register
case ns_bucket:name_conflict(BucketName, AllBuckets) of
false ->
ignore;
_ ->
{error, name, <<"Bucket with given name already exists">>}
end
end;
validate_bucket_name(false = _IsNew, BucketConfig, _BucketName, _AllBuckets) ->
true = (BucketConfig =/= false),
{ok, currentBucket, BucketConfig}.
validate_moxi_port(Params) ->
do_validate_moxi_port(proplists:get_value("proxyPort", Params)).
do_validate_moxi_port(undefined) ->
ignore;
do_validate_moxi_port("none") ->
%% needed for pre-6.5 clusters only
{ok, moxi_port, undefined};
do_validate_moxi_port(_) ->
{error, proxyPort,
<<"Setting proxy port is not allowed on this version of the cluster">>}.
get_bucket_type(false = _IsNew, BucketConfig, _Params)
when is_list(BucketConfig) ->
ns_bucket:bucket_type(BucketConfig);
get_bucket_type(_IsNew, _BucketConfig, Params) ->
case proplists:get_value("bucketType", Params) of
"memcached" -> memcached;
"membase" -> membase;
"couchbase" -> membase;
"ephemeral" -> membase;
undefined -> membase;
_ -> invalid
end.
quota_size_error(CommonParams, BucketType, IsNew, BucketConfig) ->
case lists:keyfind(ram_quota, 2, CommonParams) of
{ok, ram_quota, RAMQuota} ->
{MinQuota, Msg}
= case BucketType of