forked from tikv/pd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregion.go
More file actions
987 lines (908 loc) · 31.5 KB
/
region.go
File metadata and controls
987 lines (908 loc) · 31.5 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
// Copyright 2016 TiKV Project Authors.
//
// 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.
package api
import (
"container/heap"
"fmt"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/unrolled/render"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/tikv/pd/pkg/core"
"github.com/tikv/pd/pkg/errs"
"github.com/tikv/pd/pkg/keyspace"
"github.com/tikv/pd/pkg/response"
"github.com/tikv/pd/pkg/statistics"
"github.com/tikv/pd/pkg/utils/apiutil"
"github.com/tikv/pd/pkg/utils/typeutil"
"github.com/tikv/pd/server"
)
type regionHandler struct {
svr *server.Server
rd *render.Render
}
func newRegionHandler(svr *server.Server, rd *render.Render) *regionHandler {
return ®ionHandler{
svr: svr,
rd: rd,
}
}
// GetRegionByID returns the region info by region ID.
//
// @Tags region
// @Summary Search for a region by region ID.
// @Param id path integer true "Region Id"
// @Produce json
// @Success 200 {object} response.RegionInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /region/id/{id} [get]
func (h *regionHandler) GetRegionByID(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
vars := mux.Vars(r)
regionIDStr := vars["id"]
regionID, err := strconv.ParseUint(regionIDStr, 10, 64)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
if regionID == 0 {
h.rd.JSON(w, http.StatusBadRequest, errs.ErrRegionInvalidID.FastGenByArgs())
return
}
regionInfo := rc.GetRegion(regionID)
failpoint.Inject("RejectGetRegionByIDWhenAccessLeader", func() {
if h.svr.GetMember().IsServing() {
regionInfo = nil
}
})
if regionInfo == nil {
h.rd.JSON(w, http.StatusNotFound, errs.ErrRegionNotFound.FastGenByArgs(regionID).Error())
return
}
b, err := response.MarshalRegionInfoJSON(r.Context(), regionInfo)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
// GetRegion returns the region info by region key.
//
// @Tags region
// @Summary Search for a region by a key. GetRegion is named to be consistent with gRPC
// @Param key path string true "Region key"
// @Produce json
// @Success 200 {object} response.RegionInfo
// @Router /region/key/{key} [get]
func (h *regionHandler) GetRegion(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
vars := mux.Vars(r)
key, err := url.QueryUnescape(vars["key"])
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
// decode hex if query has params with hex format
paramsByte := [][]byte{[]byte(key)}
paramsByte, err = apiutil.ParseHexKeys(r.URL.Query().Get("format"), paramsByte)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
regionInfo := rc.GetRegionByKey(paramsByte[0])
if regionInfo == nil {
h.rd.JSON(w, http.StatusNotFound, errs.ErrRegionNotFound.FastGenByArgs().Error())
return
}
b, err := response.MarshalRegionInfoJSON(r.Context(), regionInfo)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
// CheckRegionsReplicated checks if regions in the given key ranges are replicated.
//
// @Tags region
// @Summary Check if regions in the given key ranges are replicated. Returns 'REPLICATED', 'INPROGRESS', or 'PENDING'. 'PENDING' means that there is at least one region pending for scheduling. Similarly, 'INPROGRESS' means there is at least one region in scheduling.
// @Param startKey query string true "Regions start key, hex encoded"
// @Param endKey query string true "Regions end key, hex encoded"
// @Produce plain
// @Success 200 {string} string "INPROGRESS"
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/replicated [get]
func (h *regionsHandler) CheckRegionsReplicated(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
rawStartKey := vars["startKey"]
rawEndKey := vars["endKey"]
state, err := h.Handler.CheckRegionsReplicated(rawStartKey, rawEndKey)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
h.rd.JSON(w, http.StatusOK, state)
}
type regionsHandler struct {
*server.Handler
svr *server.Server
rd *render.Render
}
func newRegionsHandler(svr *server.Server, rd *render.Render) *regionsHandler {
return ®ionsHandler{
Handler: svr.GetHandler(),
svr: svr,
rd: rd,
}
}
// GetRegions returns all regions in the cluster.
//
// @Tags region
// @Summary List all regions in the cluster.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Router /regions [get]
func (h *regionsHandler) GetRegions(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
regions := rc.GetRegions()
failpoint.Inject("slowRequest", func() {
// Simulate a slow request.
<-time.After(5 * time.Second)
})
b, err := response.MarshalRegionsInfoJSON(r.Context(), regions)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
// ScanRegions returns all regions in the given range [startKey, endKey).
//
// @Tags region
// @Summary List regions in a given range [startKey, endKey).
// @Param key query string true "Region range start key"
// @Param endkey query string true "Region range end key"
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/key [get]
func (h *regionsHandler) ScanRegions(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
query := r.URL.Query()
paramsByte := [][]byte{[]byte(query.Get("key")), []byte(query.Get("end_key"))}
paramsByte, err := apiutil.ParseHexKeys(query.Get("format"), paramsByte)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
limit, err := h.AdjustLimit(query.Get("limit"))
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
regions := rc.ScanRegions(paramsByte[0], paramsByte[1], limit)
b, err := response.MarshalRegionsInfoJSON(r.Context(), regions)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
// GetRegionCount returns the count of all regions in the cluster.
//
// @Tags region
// @Summary Get count of regions.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Router /regions/count [get]
func (h *regionsHandler) GetRegionCount(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
count := rc.GetTotalRegionCount()
h.rd.JSON(w, http.StatusOK, &response.RegionsInfo{Count: count})
}
// GetStoreRegions returns all regions of a specific store.
//
// @Tags region
// @Summary List all regions of a specific store.
// @Param id path integer true "Store Id"
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/store/{id} [get]
func (h *regionsHandler) GetStoreRegions(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
// get type from query
typ := r.URL.Query().Get("type")
if len(typ) == 0 {
typ = string(core.AllInSubTree)
}
regions, err := rc.GetStoreRegionsByTypeInSubTree(uint64(id), core.SubTreeRegionType(typ))
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
b, err := response.MarshalRegionsInfoJSON(r.Context(), regions)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
// GetKeyspaceRegions returns all regions of a specific keyspace ID.
//
// @Tags region
// @Summary List regions belongs to the given keyspace ID.
// @Param keyspace_id query string true "Keyspace ID"
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/keyspace/id/{id} [get]
func (h *regionsHandler) GetKeyspaceRegions(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
vars := mux.Vars(r)
keyspaceIDStr := vars["id"]
if keyspaceIDStr == "" {
h.rd.JSON(w, http.StatusBadRequest, "keyspace id is empty")
return
}
keyspaceID64, err := strconv.ParseUint(keyspaceIDStr, 10, 32)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
keyspaceID := uint32(keyspaceID64)
keyspaceManager := h.svr.GetKeyspaceManager()
if _, err := keyspaceManager.LoadKeyspaceByID(keyspaceID); err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
limit, err := h.AdjustLimit(r.URL.Query().Get("limit"))
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
regionBound := keyspace.MakeRegionBound(keyspaceID)
regions := rc.ScanRegions(regionBound.RawLeftBound, regionBound.RawRightBound, limit)
if limit <= 0 || limit > len(regions) {
txnRegion := rc.ScanRegions(regionBound.TxnLeftBound, regionBound.TxnRightBound, limit-len(regions))
regions = append(regions, txnRegion...)
}
b, err := response.MarshalRegionsInfoJSON(r.Context(), regions)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
// GetMissPeerRegions returns all regions that miss peer.
//
// @Tags region
// @Summary List all regions that miss peer.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/miss-peer [get]
func (h *regionsHandler) GetMissPeerRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.MissPeer, r)
}
func (h *regionsHandler) getRegionsByType(
w http.ResponseWriter,
typ statistics.RegionStatisticType,
r *http.Request,
) {
handler := h.svr.GetHandler()
regions, err := handler.GetRegionsByType(typ)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
b, err := response.MarshalRegionsInfoJSON(r.Context(), regions)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
// GetExtraPeerRegions returns all regions that has extra peer.
//
// @Tags region
// @Summary List all regions that has extra peer.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/extra-peer [get]
func (h *regionsHandler) GetExtraPeerRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.ExtraPeer, r)
}
// GetPendingPeerRegions returns all regions that has pending peer.
//
// @Tags region
// @Summary List all regions that has pending peer.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/pending-peer [get]
func (h *regionsHandler) GetPendingPeerRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.PendingPeer, r)
}
// GetDownPeerRegions returns all regions that has down peer.
//
// @Tags region
// @Summary List all regions that has down peer.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/down-peer [get]
func (h *regionsHandler) GetDownPeerRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.DownPeer, r)
}
// GetLearnerPeerRegions returns all regions that has learner peer.
//
// @Tags region
// @Summary List all regions that has learner peer.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/learner-peer [get]
func (h *regionsHandler) GetLearnerPeerRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.LearnerPeer, r)
}
// GetOfflinePeerRegions returns all regions that has offline peer.
//
// @Tags region
// @Summary List all regions that has offline peer.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/offline-peer [get]
func (h *regionsHandler) GetOfflinePeerRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.OfflinePeer, r)
}
// GetOverSizedRegions returns all regions that are oversized.
//
// @Tags region
// @Summary List all regions that are oversized.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/oversized-region [get]
func (h *regionsHandler) GetOverSizedRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.OversizedRegion, r)
}
// GetUndersizedRegions returns all regions that are undersized.
//
// @Tags region
// @Summary List all regions that are undersized.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/undersized-region [get]
func (h *regionsHandler) GetUndersizedRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.UndersizedRegion, r)
}
// GetEmptyRegions returns all regions that are empty.
//
// @Tags region
// @Summary List all empty regions.
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 500 {string} string "PD server failed to proceed the request."
// @Router /regions/check/empty-region [get]
func (h *regionsHandler) GetEmptyRegions(w http.ResponseWriter, r *http.Request) {
h.getRegionsByType(w, statistics.EmptyRegion, r)
}
// HistItem is used to represent a histogram item.
type HistItem struct {
Start int64 `json:"start"`
End int64 `json:"end"`
Count int64 `json:"count"`
}
type histSlice []*HistItem
func (hist histSlice) Len() int {
return len(hist)
}
func (hist histSlice) Swap(i, j int) {
hist[i], hist[j] = hist[j], hist[i]
}
func (hist histSlice) Less(i, j int) bool {
return hist[i].Start < hist[j].Start
}
// GetSizeHistogram returns the size histogram of all regions.
//
// @Tags region
// @Summary Get size of histogram.
// @Param bound query integer false "Size bound of region histogram" minimum(1)
// @Produce json
// @Success 200 {array} HistItem
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/check/hist-size [get]
func (h *regionsHandler) GetSizeHistogram(w http.ResponseWriter, r *http.Request) {
bound := minRegionHistogramSize
bound, err := calBound(bound, r)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
rc := getCluster(r)
regions := rc.GetRegions()
histSizes := make([]int64, 0, len(regions))
for _, region := range regions {
histSizes = append(histSizes, region.GetApproximateSize())
}
histItems := calHist(bound, &histSizes)
h.rd.JSON(w, http.StatusOK, histItems)
}
// GetKeysHistogram returns the keys histogram of all regions.
//
// @Tags region
// @Summary Get keys of histogram.
// @Param bound query integer false "Key bound of region histogram" minimum(1000)
// @Produce json
// @Success 200 {array} HistItem
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/check/hist-keys [get]
func (h *regionsHandler) GetKeysHistogram(w http.ResponseWriter, r *http.Request) {
bound := minRegionHistogramKeys
bound, err := calBound(bound, r)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
rc := getCluster(r)
regions := rc.GetRegions()
histKeys := make([]int64, 0, len(regions))
for _, region := range regions {
histKeys = append(histKeys, region.GetApproximateKeys())
}
histItems := calHist(bound, &histKeys)
h.rd.JSON(w, http.StatusOK, histItems)
}
func calBound(bound int, r *http.Request) (int, error) {
if boundStr := r.URL.Query().Get("bound"); boundStr != "" {
boundInput, err := strconv.Atoi(boundStr)
if err != nil {
return -1, err
}
if bound < boundInput {
bound = boundInput
}
}
return bound, nil
}
func calHist(bound int, list *[]int64) *[]*HistItem {
var histMap = make(map[int64]int)
for _, item := range *list {
multiple := item / int64(bound)
if oldCount, ok := histMap[multiple]; ok {
histMap[multiple] = oldCount + 1
} else {
histMap[multiple] = 1
}
}
histItems := make([]*HistItem, 0, len(histMap))
for multiple, count := range histMap {
histInfo := &HistItem{}
histInfo.Start = multiple * int64(bound)
histInfo.End = (multiple+1)*int64(bound) - 1
histInfo.Count = int64(count)
histItems = append(histItems, histInfo)
}
sort.Sort(histSlice(histItems))
return &histItems
}
// GetRangeHoles returns all range holes without any region info.
//
// @Tags region
// @Summary List all range holes without any region info.
// @Produce json
// @Success 200 {object} [][]string
// @Router /regions/range-holes [get]
func (h *regionsHandler) GetRangeHoles(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
h.rd.JSON(w, http.StatusOK, rc.GetRangeHoles())
}
// GetRegionSiblings returns the sibling regions of a specific region.
//
// @Tags region
// @Summary List sibling regions of a specific region.
// @Param id path integer true "Region Id"
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Failure 404 {string} string "The region does not exist."
// @Router /regions/sibling/{id} [get]
func (h *regionsHandler) GetRegionSiblings(w http.ResponseWriter, r *http.Request) {
rc := getCluster(r)
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
region := rc.GetRegion(uint64(id))
if region == nil {
h.rd.JSON(w, http.StatusNotFound, errs.ErrRegionNotFound.FastGenByArgs(uint64(id)).Error())
return
}
left, right := rc.GetAdjacentRegions(region)
b, err := response.MarshalRegionsInfoJSON(r.Context(), []*core.RegionInfo{left, right})
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
const (
minRegionHistogramSize = 1
minRegionHistogramKeys = 1000
)
// GetTopWriteFlowRegions returns the regions with the highest write flow.
//
// @Tags region
// @Summary List regions with the highest write flow.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/writeflow [get]
func (h *regionsHandler) GetTopWriteFlowRegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool { return a.GetBytesWritten() < b.GetBytesWritten() })
}
// GetTopWriteQueryRegions returns the regions with the highest write query flow.
//
// @Tags region
// @Summary List regions with the highest write flow.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/writequery [get]
func (h *regionsHandler) GetTopWriteQueryRegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool {
return a.GetWriteQueryNum() < b.GetWriteQueryNum()
})
}
// GetTopReadFlowRegions returns the regions with the highest read flow.
//
// @Tags region
// @Summary List regions with the highest read flow.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/readflow [get]
func (h *regionsHandler) GetTopReadFlowRegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool { return a.GetBytesRead() < b.GetBytesRead() })
}
// GetTopReadQueryRegions returns the regions with the highest read query flow.
//
// @Tags region
// @Summary List regions with the highest write flow.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/readquery [get]
func (h *regionsHandler) GetTopReadQueryRegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool {
return a.GetReadQueryNum() < b.GetReadQueryNum()
})
}
// GetTopConfVerRegions returns the regions with the largest conf version.
//
// @Tags region
// @Summary List regions with the largest conf version.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/confver [get]
func (h *regionsHandler) GetTopConfVerRegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool {
return a.GetMeta().GetRegionEpoch().GetConfVer() < b.GetMeta().GetRegionEpoch().GetConfVer()
})
}
// GetTopVersionRegions returns the regions with the largest version.
//
// @Tags region
// @Summary List regions with the largest version.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/version [get]
func (h *regionsHandler) GetTopVersionRegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool {
return a.GetMeta().GetRegionEpoch().GetVersion() < b.GetMeta().GetRegionEpoch().GetVersion()
})
}
// GetTopSizeRegions returns the regions with the largest size.
//
// @Tags region
// @Summary List regions with the largest size.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/size [get]
func (h *regionsHandler) GetTopSizeRegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool {
return a.GetApproximateSize() < b.GetApproximateSize()
})
}
// GetTopKeysRegions returns the regions with the largest keys.
//
// @Tags region
// @Summary List regions with the largest keys.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/keys [get]
func (h *regionsHandler) GetTopKeysRegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool {
return a.GetApproximateKeys() < b.GetApproximateKeys()
})
}
// GetTopCPURegions returns the regions with the highest CPU usage.
//
// @Tags region
// @Summary List regions with the highest CPU usage.
// @Param limit query integer false "Limit count" default(16)
// @Produce json
// @Success 200 {object} response.RegionsInfo
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/cpu [get]
func (h *regionsHandler) GetTopCPURegions(w http.ResponseWriter, r *http.Request) {
h.getTopNRegions(w, r, func(a, b *core.RegionInfo) bool {
return a.GetCPUUsage() < b.GetCPUUsage()
})
}
// AccelerateRegionsScheduleInRange accelerates regions scheduling in a given range.
//
// @Tags region
// @Summary Accelerate regions scheduling a in given range, only receive hex format for keys
// @Accept json
// @Param body body object true "json params"
// @Param limit query integer false "Limit count" default(256)
// @Produce json
// @Success 200 {string} string "Accelerate regions scheduling in a given range [startKey, endKey)"
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/accelerate-schedule [post]
func (h *regionsHandler) AccelerateRegionsScheduleInRange(w http.ResponseWriter, r *http.Request) {
var input map[string]any
if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil {
return
}
rawStartKey, ok1 := input["start_key"].(string)
rawEndKey, ok2 := input["end_key"].(string)
if !ok1 || !ok2 {
h.rd.JSON(w, http.StatusBadRequest, "start_key or end_key is not string")
return
}
limit, err := h.AdjustLimit(r.URL.Query().Get("limit"), 256 /*default limit*/)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
err = h.Handler.AccelerateRegionsScheduleInRange(rawStartKey, rawEndKey, limit)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Text(w, http.StatusOK, fmt.Sprintf("Accelerate regions scheduling in a given range [%s,%s)", rawStartKey, rawEndKey))
}
// AccelerateRegionsScheduleInRanges accelerates regions scheduling in given ranges.
//
// @Tags region
// @Summary Accelerate regions scheduling in given ranges, only receive hex format for keys
// @Accept json
// @Param body body object true "json params"
// @Param limit query integer false "Limit count" default(256)
// @Produce json
// @Success 200 {string} string "Accelerate regions scheduling in given ranges [startKey1, endKey1), [startKey2, endKey2), ..."
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/accelerate-schedule/batch [post]
func (h *regionsHandler) AccelerateRegionsScheduleInRanges(w http.ResponseWriter, r *http.Request) {
var input []map[string]any
if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil {
return
}
limit, err := h.AdjustLimit(r.URL.Query().Get("limit"), 256 /*default limit*/)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
var msgBuilder strings.Builder
msgBuilder.Grow(128)
msgBuilder.WriteString("Accelerate regions scheduling in given ranges: ")
var startKeys, endKeys [][]byte
for _, rg := range input {
startKey, rawStartKey, err := apiutil.ParseKey("start_key", rg)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
endKey, rawEndKey, err := apiutil.ParseKey("end_key", rg)
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
startKeys = append(startKeys, startKey)
endKeys = append(endKeys, endKey)
msgBuilder.WriteString(fmt.Sprintf("[%s,%s), ", rawStartKey, rawEndKey))
}
err = h.Handler.AccelerateRegionsScheduleInRanges(startKeys, endKeys, limit)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Text(w, http.StatusOK, msgBuilder.String())
}
func (h *regionsHandler) getTopNRegions(w http.ResponseWriter, r *http.Request, less func(a, b *core.RegionInfo) bool) {
rc := getCluster(r)
limit, err := h.AdjustLimit(r.URL.Query().Get("limit"))
if err != nil {
h.rd.JSON(w, http.StatusBadRequest, err.Error())
return
}
regions := TopNRegions(rc.GetRegions(), less, limit)
b, err := response.MarshalRegionsInfoJSON(r.Context(), regions)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.Data(w, http.StatusOK, b)
}
// ScatterRegions scatters regions by given key ranges or regions id distributed by given group with given retry limit.
//
// @Tags region
// @Summary Scatter regions by given key ranges or regions id distributed by given group with given retry limit
// @Accept json
// @Param body body object true "json params"
// @Produce json
// @Success 200 {string} string "Scatter regions by given key ranges or regions id distributed by given group with given retry limit"
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/scatter [post]
func (h *regionsHandler) ScatterRegions(w http.ResponseWriter, r *http.Request) {
var input map[string]any
if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil {
return
}
rawStartKey, ok1 := input["start_key"].(string)
rawEndKey, ok2 := input["end_key"].(string)
group, _ := input["group"].(string)
retryLimit := 5
if rl, ok := input["retry_limit"].(float64); ok {
retryLimit = int(rl)
}
opsCount, failures, err := func() (int, map[uint64]error, error) {
if ok1 && ok2 {
return h.ScatterRegionsByRange(rawStartKey, rawEndKey, group, retryLimit)
}
ids, ok := typeutil.JSONToUint64Slice(input["regions_id"])
if !ok {
return 0, nil, errors.New("regions_id is invalid")
}
return h.ScatterRegionsByID(ids, group, retryLimit)
}()
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
s := h.BuildScatterRegionsResp(opsCount, failures)
h.rd.JSON(w, http.StatusOK, &s)
}
// SplitRegions splits regions by given split keys.
//
// @Tags region
// @Summary Split regions with given split keys
// @Accept json
// @Param body body object true "json params"
// @Produce json
// @Success 200 {string} string "Split regions with given split keys"
// @Failure 400 {string} string "The input is invalid."
// @Router /regions/split [post]
func (h *regionsHandler) SplitRegions(w http.ResponseWriter, r *http.Request) {
var input map[string]any
if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil {
return
}
s, ok := input["split_keys"]
if !ok {
h.rd.JSON(w, http.StatusBadRequest, "split_keys should be provided.")
return
}
rawSplitKeys := s.([]any)
if len(rawSplitKeys) < 1 {
h.rd.JSON(w, http.StatusBadRequest, "empty split keys.")
return
}
retryLimit := 5
if rl, ok := input["retry_limit"].(float64); ok {
retryLimit = int(rl)
}
s, err := h.Handler.SplitRegions(r.Context(), rawSplitKeys, retryLimit)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
h.rd.JSON(w, http.StatusOK, &s)
}
// RegionHeap implements heap.Interface, used for selecting top n regions.
type RegionHeap struct {
regions []*core.RegionInfo
less func(a, b *core.RegionInfo) bool
}
func (h *RegionHeap) Len() int { return len(h.regions) }
func (h *RegionHeap) Less(i, j int) bool { return h.less(h.regions[i], h.regions[j]) }
func (h *RegionHeap) Swap(i, j int) { h.regions[i], h.regions[j] = h.regions[j], h.regions[i] }
// Push pushes an element x onto the heap.
func (h *RegionHeap) Push(x any) {
h.regions = append(h.regions, x.(*core.RegionInfo))
}
// Pop removes the minimum element (according to Less) from the heap and returns
// it.
func (h *RegionHeap) Pop() any {
pos := len(h.regions) - 1
x := h.regions[pos]
h.regions[pos] = nil // avoid memory leak
h.regions = h.regions[:pos]
return x
}
// Min returns the minimum region from the heap.
func (h *RegionHeap) Min() *core.RegionInfo {
if h.Len() == 0 {
return nil
}
return h.regions[0]
}
// TopNRegions returns top n regions according to the given rule.
func TopNRegions(regions []*core.RegionInfo, less func(a, b *core.RegionInfo) bool, n int) []*core.RegionInfo {
if n <= 0 {
return nil
}
hp := &RegionHeap{
regions: make([]*core.RegionInfo, 0, n),
less: less,
}
for _, r := range regions {
if hp.Len() < n {
heap.Push(hp, r)
continue
}
if less(hp.Min(), r) {
heap.Pop(hp)
heap.Push(hp, r)
}
}
res := make([]*core.RegionInfo, hp.Len())
for i := hp.Len() - 1; i >= 0; i-- {
res[i] = heap.Pop(hp).(*core.RegionInfo)
}
return res
}