/
PartitionInfo.java
732 lines (661 loc) · 28.4 KB
/
PartitionInfo.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.iotdb.confignode.persistence.partition;
import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
import org.apache.iotdb.common.rpc.thrift.TRegionLocation;
import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.common.rpc.thrift.TSeriesPartitionSlot;
import org.apache.iotdb.common.rpc.thrift.TTimePartitionSlot;
import org.apache.iotdb.commons.partition.DataPartition;
import org.apache.iotdb.commons.partition.SchemaPartition;
import org.apache.iotdb.commons.snapshot.SnapshotProcessor;
import org.apache.iotdb.confignode.conf.ConfigNodeDescriptor;
import org.apache.iotdb.confignode.consensus.request.read.GetDataPartitionReq;
import org.apache.iotdb.confignode.consensus.request.read.GetRegionLocationsReq;
import org.apache.iotdb.confignode.consensus.request.read.GetSchemaPartitionReq;
import org.apache.iotdb.confignode.consensus.request.write.CreateDataPartitionReq;
import org.apache.iotdb.confignode.consensus.request.write.CreateRegionsReq;
import org.apache.iotdb.confignode.consensus.request.write.CreateSchemaPartitionReq;
import org.apache.iotdb.confignode.consensus.request.write.DeleteStorageGroupReq;
import org.apache.iotdb.confignode.consensus.request.write.PreDeleteStorageGroupReq;
import org.apache.iotdb.confignode.consensus.request.write.SetStorageGroupReq;
import org.apache.iotdb.confignode.consensus.response.DataPartitionResp;
import org.apache.iotdb.confignode.consensus.response.RegionLocationsResp;
import org.apache.iotdb.confignode.consensus.response.SchemaNodeManagementResp;
import org.apache.iotdb.confignode.consensus.response.SchemaPartitionResp;
import org.apache.iotdb.confignode.exception.StorageGroupNotExistsException;
import org.apache.iotdb.consensus.common.DataSet;
import org.apache.iotdb.db.service.metrics.MetricsService;
import org.apache.iotdb.db.service.metrics.enums.Metric;
import org.apache.iotdb.db.service.metrics.enums.Tag;
import org.apache.iotdb.metrics.config.MetricConfigDescriptor;
import org.apache.iotdb.metrics.utils.MetricLevel;
import org.apache.iotdb.rpc.RpcUtils;
import org.apache.iotdb.rpc.TSStatusCode;
import org.apache.iotdb.tsfile.utils.Pair;
import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TIOStreamTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The PartitionInfo stores cluster PartitionTable. The PartitionTable including: 1. regionMap:
* location of Region member 2. schemaPartition: location of schema 3. dataPartition: location of
* data
*/
public class PartitionInfo implements SnapshotProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(PartitionInfo.class);
// For allocating Regions
private final AtomicInteger nextRegionGroupId;
// Map<StorageGroupName, StorageGroupPartitionInfo>
private final ConcurrentHashMap<String, StorageGroupPartitionTable> storageGroupPartitionTables;
private final Set<TRegionReplicaSet> deletedRegionSet;
private final String snapshotFileName = "partition_info.bin";
public PartitionInfo() {
this.storageGroupPartitionTables = new ConcurrentHashMap<>();
this.nextRegionGroupId = new AtomicInteger(0);
// Ensure that the PartitionTables of the StorageGroups who've been logically deleted
// are unreadable and un-writable
// For RegionCleaner
this.deletedRegionSet = Collections.synchronizedSet(new HashSet<>());
}
public void addMetrics() {
if (MetricConfigDescriptor.getInstance().getMetricConfig().getEnableMetric()) {
MetricsService.getInstance()
.getMetricManager()
.getOrCreateAutoGauge(
Metric.STORAGE_GROUP.toString(),
MetricLevel.CORE,
storageGroupPartitionTables,
o -> o.size() / 2,
Tag.NAME.toString(),
"number");
MetricsService.getInstance()
.getMetricManager()
.getOrCreateAutoGauge(
Metric.REGION.toString(),
MetricLevel.IMPORTANT,
this,
o -> o.updateRegionMetric(TConsensusGroupType.SchemaRegion),
Tag.NAME.toString(),
"total",
Tag.TYPE.toString(),
TConsensusGroupType.SchemaRegion.toString());
MetricsService.getInstance()
.getMetricManager()
.getOrCreateAutoGauge(
Metric.REGION.toString(),
MetricLevel.IMPORTANT,
this,
o -> o.updateRegionMetric(TConsensusGroupType.DataRegion),
Tag.NAME.toString(),
"total",
Tag.TYPE.toString(),
TConsensusGroupType.DataRegion.toString());
}
}
public int generateNextRegionGroupId() {
return nextRegionGroupId.getAndIncrement();
}
// ======================================================
// Consensus read/write interfaces
// ======================================================
/**
* Thread-safely create new StorageGroupPartitionInfo
*
* @param req SetStorageGroupReq
* @return SUCCESS_STATUS if the new StorageGroupPartitionInfo is created successfully.
*/
public TSStatus setStorageGroup(SetStorageGroupReq req) {
String storageGroupName = req.getSchema().getName();
storageGroupPartitionTables.put(
storageGroupName, new StorageGroupPartitionTable(storageGroupName));
LOGGER.info("Successfully set StorageGroup: {}", req.getSchema());
return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
}
/**
* Thread-safely cache allocation result of new Regions
*
* @param req CreateRegionsReq
* @return SUCCESS_STATUS
*/
public TSStatus createRegions(CreateRegionsReq req) {
TSStatus result;
AtomicInteger maxRegionId = new AtomicInteger(Integer.MIN_VALUE);
req.getRegionMap()
.forEach(
(storageGroup, regionReplicaSets) -> {
storageGroupPartitionTables.get(storageGroup).createRegions(regionReplicaSets);
regionReplicaSets.forEach(
regionReplicaSet ->
maxRegionId.set(
Math.max(maxRegionId.get(), regionReplicaSet.getRegionId().getId())));
});
// To ensure that the nextRegionGroupId is updated correctly when
// the ConfigNode-followers concurrently processes CreateRegionsReq,
// we need to add a synchronization lock here
synchronized (nextRegionGroupId) {
if (nextRegionGroupId.get() < maxRegionId.get()) {
nextRegionGroupId.set(maxRegionId.get());
}
}
result = new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
return result;
}
/**
* Thread-safely pre-delete the specific StorageGroup
*
* @param preDeleteStorageGroupReq PreDeleteStorageGroupReq
* @return SUCCESS_STATUS
*/
public TSStatus preDeleteStorageGroup(PreDeleteStorageGroupReq preDeleteStorageGroupReq) {
final PreDeleteStorageGroupReq.PreDeleteType preDeleteType =
preDeleteStorageGroupReq.getPreDeleteType();
final String storageGroup = preDeleteStorageGroupReq.getStorageGroup();
switch (preDeleteType) {
case EXECUTE:
storageGroupPartitionTables.get(storageGroup).setPredeleted(true);
break;
case ROLLBACK:
storageGroupPartitionTables.get(storageGroup).setPredeleted(false);
break;
}
return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
}
/**
* Thread-safely delete StorageGroup
*
* @param req DeleteRegionsReq
*/
public void deleteStorageGroup(DeleteStorageGroupReq req) {
// Cache RegionReplicaSets
synchronized (deletedRegionSet) {
deletedRegionSet.addAll(storageGroupPartitionTables.get(req.getName()).getAllReplicaSets());
}
// Clean the cache
storageGroupPartitionTables.remove(req.getName());
}
/** @return The Regions that should be deleted among the DataNodes */
public Set<TRegionReplicaSet> getDeletedRegionSet() {
synchronized (deletedRegionSet) {
return deletedRegionSet;
}
}
/**
* Thread-safely get SchemaPartition
*
* @param req SchemaPartitionPlan with partitionSlotsMap
* @return SchemaPartitionDataSet that contains only existing SchemaPartition
*/
public DataSet getSchemaPartition(GetSchemaPartitionReq req) {
AtomicBoolean isAllPartitionsExist = new AtomicBoolean(true);
// TODO: Replace this map whit new SchemaPartition
Map<String, Map<TSeriesPartitionSlot, TRegionReplicaSet>> schemaPartition =
new ConcurrentHashMap<>();
if (req.getPartitionSlotsMap().size() == 0) {
// Return all SchemaPartitions when the queried PartitionSlots are empty
storageGroupPartitionTables.forEach(
(storageGroup, storageGroupPartitionTable) -> {
if (!storageGroupPartitionTable.isPredeleted()) {
schemaPartition.put(storageGroup, new ConcurrentHashMap<>());
storageGroupPartitionTable.getSchemaPartition(
new ArrayList<>(), schemaPartition.get(storageGroup));
if (schemaPartition.get(storageGroup).size() == 0) {
// Remove empty Map
schemaPartition.remove(storageGroup);
}
}
});
} else {
// Return the SchemaPartition for each StorageGroup
req.getPartitionSlotsMap()
.forEach(
(storageGroup, partitionSlots) -> {
if (isStorageGroupExisted(storageGroup)) {
schemaPartition.put(storageGroup, new ConcurrentHashMap<>());
if (!storageGroupPartitionTables
.get(storageGroup)
.getSchemaPartition(partitionSlots, schemaPartition.get(storageGroup))) {
isAllPartitionsExist.set(false);
}
if (schemaPartition.get(storageGroup).size() == 0) {
// Remove empty Map
schemaPartition.remove(storageGroup);
}
}
});
}
SchemaPartitionResp schemaPartitionResp = new SchemaPartitionResp();
schemaPartitionResp.setAllPartitionsExist(isAllPartitionsExist.get());
// Notice: SchemaPartition contains two redundant structural parameters currently.
schemaPartitionResp.setSchemaPartition(
new SchemaPartition(
schemaPartition,
ConfigNodeDescriptor.getInstance().getConf().getSeriesPartitionExecutorClass(),
ConfigNodeDescriptor.getInstance().getConf().getSeriesPartitionSlotNum()));
schemaPartitionResp.setStatus(new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()));
return schemaPartitionResp;
}
/**
* Thread-safely get DataPartition
*
* @param req DataPartitionPlan with partitionSlotsMap
* @return DataPartitionDataSet that contains only existing DataPartition
*/
public DataSet getDataPartition(GetDataPartitionReq req) {
AtomicBoolean isAllPartitionsExist = new AtomicBoolean(true);
// TODO: Replace this map whit new DataPartition
Map<String, Map<TSeriesPartitionSlot, Map<TTimePartitionSlot, List<TRegionReplicaSet>>>>
dataPartition = new ConcurrentHashMap<>();
req.getPartitionSlotsMap()
.forEach(
(storageGroup, partitionSlots) -> {
if (isStorageGroupExisted(storageGroup)) {
dataPartition.put(storageGroup, new ConcurrentHashMap<>());
if (!storageGroupPartitionTables
.get(storageGroup)
.getDataPartition(partitionSlots, dataPartition.get(storageGroup))) {
isAllPartitionsExist.set(false);
}
if (dataPartition.get(storageGroup).size() == 0) {
// Remove empty Map
dataPartition.remove(storageGroup);
}
}
});
DataPartitionResp dataPartitionResp = new DataPartitionResp();
dataPartitionResp.setAllPartitionsExist(isAllPartitionsExist.get());
// Notice: DataPartition contains two redundant structural parameters currently.
dataPartitionResp.setDataPartition(
new DataPartition(
dataPartition,
ConfigNodeDescriptor.getInstance().getConf().getSeriesPartitionExecutorClass(),
ConfigNodeDescriptor.getInstance().getConf().getSeriesPartitionSlotNum()));
dataPartitionResp.setStatus(new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()));
return dataPartitionResp;
}
private boolean isStorageGroupExisted(String storageGroup) {
final StorageGroupPartitionTable storageGroupPartitionTable =
storageGroupPartitionTables.get(storageGroup);
return storageGroupPartitionTable != null && !storageGroupPartitionTable.isPredeleted();
}
/**
* Create SchemaPartition
*
* @param req CreateSchemaPartitionPlan with SchemaPartition assigned result
* @return TSStatusCode.SUCCESS_STATUS
*/
public TSStatus createSchemaPartition(CreateSchemaPartitionReq req) {
req.getAssignedSchemaPartition()
.forEach(
(storageGroup, schemaPartitionTable) -> {
if (isStorageGroupExisted(storageGroup)) {
storageGroupPartitionTables
.get(storageGroup)
.createSchemaPartition(schemaPartitionTable);
}
});
return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
}
/**
* Create DataPartition
*
* @param req CreateDataPartitionPlan with DataPartition assigned result
* @return TSStatusCode.SUCCESS_STATUS
*/
public TSStatus createDataPartition(CreateDataPartitionReq req) {
req.getAssignedDataPartition()
.forEach(
(storageGroup, dataPartitionTable) -> {
if (isStorageGroupExisted(storageGroup)) {
storageGroupPartitionTables
.get(storageGroup)
.createDataPartition(dataPartitionTable);
}
});
return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
}
/** Get SchemaNodeManagementPartition through matched storageGroup */
public DataSet getSchemaNodeManagementPartition(List<String> matchedStorageGroups) {
SchemaNodeManagementResp schemaNodeManagementResp = new SchemaNodeManagementResp();
Map<String, Map<TSeriesPartitionSlot, TRegionReplicaSet>> schemaPartitionMap =
new ConcurrentHashMap<>();
matchedStorageGroups.stream()
.filter(this::isStorageGroupExisted)
.forEach(
storageGroup -> {
schemaPartitionMap.put(storageGroup, new ConcurrentHashMap<>());
storageGroupPartitionTables
.get(storageGroup)
.getSchemaPartition(new ArrayList<>(), schemaPartitionMap.get(storageGroup));
if (schemaPartitionMap.get(storageGroup).size() == 0) {
// Remove empty Map
schemaPartitionMap.remove(storageGroup);
}
});
schemaNodeManagementResp.setSchemaPartition(
new SchemaPartition(
schemaPartitionMap,
ConfigNodeDescriptor.getInstance().getConf().getSeriesPartitionExecutorClass(),
ConfigNodeDescriptor.getInstance().getConf().getSeriesPartitionSlotNum()));
schemaNodeManagementResp.setStatus(new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()));
return schemaNodeManagementResp;
}
/** Get region information */
public DataSet getRegionLocations(GetRegionLocationsReq regionsInfoReq) {
RegionLocationsResp regionResp = new RegionLocationsResp();
List<TRegionLocation> regionLocationList = new ArrayList<>();
if (storageGroupPartitionTables.isEmpty()) {
regionResp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS));
return regionResp;
}
storageGroupPartitionTables.forEach(
(storageGroup, storageGroupPartitionTable) -> {
storageGroupPartitionTable.getRegionInfos(regionsInfoReq, regionLocationList);
});
regionLocationList.sort(
Comparator.comparingInt(regionId -> regionId.getConsensusGroupId().getId()));
regionResp.setRegionInfosList(regionLocationList);
regionResp.setStatus(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS));
return regionResp;
}
// ======================================================
// Leader scheduling interfaces
// ======================================================
/**
* Only Leader use this interface. Filter unassigned SchemaPartitionSlots
*
* @param partitionSlotsMap Map<StorageGroupName, List<TSeriesPartitionSlot>>
* @return Map<StorageGroupName, List<TSeriesPartitionSlot>>, SchemaPartitionSlots that is not
* assigned in partitionSlotsMap
*/
public Map<String, List<TSeriesPartitionSlot>> filterUnassignedSchemaPartitionSlots(
Map<String, List<TSeriesPartitionSlot>> partitionSlotsMap) {
Map<String, List<TSeriesPartitionSlot>> result = new ConcurrentHashMap<>();
partitionSlotsMap.forEach(
(storageGroup, partitionSlots) -> {
if (isStorageGroupExisted(storageGroup)) {
result.put(
storageGroup,
storageGroupPartitionTables
.get(storageGroup)
.filterUnassignedSchemaPartitionSlots(partitionSlots));
}
});
return result;
}
/**
* Only Leader use this interface. Filter unassigned SchemaPartitionSlots
*
* @param partitionSlotsMap Map<StorageGroupName, Map<TSeriesPartitionSlot,
* List<TTimePartitionSlot>>>
* @return Map<StorageGroupName, Map<TSeriesPartitionSlot, List<TTimePartitionSlot>>>,
* DataPartitionSlots that is not assigned in partitionSlotsMap
*/
public Map<String, Map<TSeriesPartitionSlot, List<TTimePartitionSlot>>>
filterUnassignedDataPartitionSlots(
Map<String, Map<TSeriesPartitionSlot, List<TTimePartitionSlot>>> partitionSlotsMap) {
Map<String, Map<TSeriesPartitionSlot, List<TTimePartitionSlot>>> result =
new ConcurrentHashMap<>();
partitionSlotsMap.forEach(
(storageGroup, partitionSlots) -> {
if (isStorageGroupExisted(storageGroup)) {
result.put(
storageGroup,
storageGroupPartitionTables
.get(storageGroup)
.filterUnassignedDataPartitionSlots(partitionSlots));
}
});
return result;
}
/**
* Only leader use this interface.
*
* @return All Regions' RegionReplicaSet
*/
public List<TRegionReplicaSet> getAllReplicaSets() {
List<TRegionReplicaSet> result = new Vector<>();
storageGroupPartitionTables
.values()
.forEach(
storageGroupPartitionTable ->
result.addAll(storageGroupPartitionTable.getAllReplicaSets()));
return result;
}
/**
* Only leader use this interface. Get the number of Regions currently owned by the specific
* StorageGroup
*
* @param storageGroup StorageGroupName
* @param type SchemaRegion or DataRegion
* @return Number of Regions currently owned by the specific StorageGroup
* @throws StorageGroupNotExistsException When the specific StorageGroup doesn't exist
*/
public int getRegionCount(String storageGroup, TConsensusGroupType type)
throws StorageGroupNotExistsException {
if (!isStorageGroupExisted(storageGroup)) {
throw new StorageGroupNotExistsException(storageGroup);
}
return storageGroupPartitionTables.get(storageGroup).getRegionCount(type);
}
/**
* Only leader use this interface. Contending the Region allocation particle
*
* @param storageGroup StorageGroupName
* @param type SchemaRegion or DataRegion
* @return True when successfully get the allocation particle, false otherwise
*/
public boolean getRegionAllocationParticle(String storageGroup, TConsensusGroupType type) {
return storageGroupPartitionTables.get(storageGroup).getRegionAllocationParticle(type);
}
/**
* Only leader use this interface.
*
* @param storageGroup StorageGroupName
* @param type SchemaRegion or DataRegion
* @return The specific StorageGroup's Regions that sorted by the number of allocated slots
*/
public List<Pair<Long, TConsensusGroupId>> getSortedRegionSlotsCounter(
String storageGroup, TConsensusGroupType type) {
return storageGroupPartitionTables.get(storageGroup).getSortedRegionSlotsCounter(type);
}
/**
* Get total region number
*
* @param type SchemaRegion or DataRegion
* @return the number of SchemaRegion or DataRegion
*/
public int getTotalRegionCount(TConsensusGroupType type) {
Set<RegionGroup> regionGroups = new HashSet<>();
for (Map.Entry<String, StorageGroupPartitionTable> entry :
storageGroupPartitionTables.entrySet()) {
regionGroups.addAll(entry.getValue().getRegion(type));
}
return regionGroups.size();
}
/**
* update region-related metric
*
* @param type SchemaRegion or DataRegion
* @return the number of SchemaRegion or DataRegion
*/
private int updateRegionMetric(TConsensusGroupType type) {
Set<RegionGroup> regionGroups = new HashSet<>();
for (Map.Entry<String, StorageGroupPartitionTable> entry :
storageGroupPartitionTables.entrySet()) {
regionGroups.addAll(entry.getValue().getRegion(type));
}
int result = regionGroups.size();
// datanode location -> region number
Map<TDataNodeLocation, Integer> dataNodeLocationIntegerMap = new HashMap<>();
for (RegionGroup regionGroup : regionGroups) {
TRegionReplicaSet regionReplicaSet = regionGroup.getReplicaSet();
List<TDataNodeLocation> dataNodeLocations = regionReplicaSet.getDataNodeLocations();
for (TDataNodeLocation dataNodeLocation : dataNodeLocations) {
if (!dataNodeLocationIntegerMap.containsKey(dataNodeLocation)) {
dataNodeLocationIntegerMap.put(dataNodeLocation, 0);
}
dataNodeLocationIntegerMap.put(
dataNodeLocation, dataNodeLocationIntegerMap.get(dataNodeLocation) + 1);
}
}
for (Map.Entry<TDataNodeLocation, Integer> entry : dataNodeLocationIntegerMap.entrySet()) {
TDataNodeLocation dataNodeLocation = entry.getKey();
String name =
"EndPoint("
+ dataNodeLocation.getExternalEndPoint().ip
+ ":"
+ dataNodeLocation.getExternalEndPoint().port
+ ")";
MetricsService.getInstance()
.getMetricManager()
.getOrCreateGauge(
Metric.REGION.toString(),
MetricLevel.IMPORTANT,
Tag.NAME.toString(),
name,
Tag.TYPE.toString(),
type.toString())
.set(dataNodeLocationIntegerMap.get(dataNodeLocation));
}
return result;
}
@Override
public boolean processTakeSnapshot(File snapshotDir) throws TException, IOException {
File snapshotFile = new File(snapshotDir, snapshotFileName);
if (snapshotFile.exists() && snapshotFile.isFile()) {
LOGGER.error(
"Failed to take snapshot, because snapshot file [{}] is already exist.",
snapshotFile.getAbsolutePath());
return false;
}
// prevents temporary files from being damaged and cannot be deleted, which affects the next
// snapshot operation.
File tmpFile = new File(snapshotFile.getAbsolutePath() + "-" + UUID.randomUUID());
// TODO: Lock PartitionInfo
try (FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
TIOStreamTransport tioStreamTransport = new TIOStreamTransport(fileOutputStream)) {
TProtocol protocol = new TBinaryProtocol(tioStreamTransport);
// serialize nextRegionGroupId
ReadWriteIOUtils.write(nextRegionGroupId.get(), fileOutputStream);
// serialize StorageGroupPartitionTable
ReadWriteIOUtils.write(storageGroupPartitionTables.size(), fileOutputStream);
for (Map.Entry<String, StorageGroupPartitionTable> storageGroupPartitionTableEntry :
storageGroupPartitionTables.entrySet()) {
ReadWriteIOUtils.write(storageGroupPartitionTableEntry.getKey(), fileOutputStream);
storageGroupPartitionTableEntry.getValue().serialize(fileOutputStream, protocol);
}
// serialize deletedRegionSet
ReadWriteIOUtils.write(deletedRegionSet.size(), fileOutputStream);
for (TRegionReplicaSet regionReplicaSet : deletedRegionSet) {
regionReplicaSet.write(protocol);
}
// write to file
fileOutputStream.flush();
fileOutputStream.close();
// rename file
return tmpFile.renameTo(snapshotFile);
} finally {
// with or without success, delete temporary files anyway
for (int retry = 0; retry < 5; retry++) {
if (!tmpFile.exists() || tmpFile.delete()) {
break;
} else {
LOGGER.warn(
"Can't delete temporary snapshot file: {}, retrying...", tmpFile.getAbsolutePath());
}
}
}
}
public void processLoadSnapshot(File snapshotDir) throws TException, IOException {
File snapshotFile = new File(snapshotDir, snapshotFileName);
if (!snapshotFile.exists() || !snapshotFile.isFile()) {
LOGGER.error(
"Failed to load snapshot,snapshot file [{}] is not exist.",
snapshotFile.getAbsolutePath());
return;
}
// TODO: Lock PartitionInfo
try (FileInputStream fileInputStream = new FileInputStream(snapshotFile);
TIOStreamTransport tioStreamTransport = new TIOStreamTransport(fileInputStream)) {
TProtocol protocol = new TBinaryProtocol(tioStreamTransport);
// before restoring a snapshot, clear all old data
clear();
// start to restore
nextRegionGroupId.set(ReadWriteIOUtils.readInt(fileInputStream));
// restore StorageGroupPartitionTable
int length = ReadWriteIOUtils.readInt(fileInputStream);
for (int i = 0; i < length; i++) {
String storageGroup = ReadWriteIOUtils.readString(fileInputStream);
StorageGroupPartitionTable storageGroupPartitionTable =
new StorageGroupPartitionTable(storageGroup);
storageGroupPartitionTable.deserialize(fileInputStream, protocol);
storageGroupPartitionTables.put(storageGroup, storageGroupPartitionTable);
}
// restore deletedRegionSet
length = ReadWriteIOUtils.readInt(fileInputStream);
for (int i = 0; i < length; i++) {
TRegionReplicaSet regionReplicaSet = new TRegionReplicaSet();
regionReplicaSet.read(protocol);
deletedRegionSet.add(regionReplicaSet);
}
}
}
public void clear() {
nextRegionGroupId.set(0);
storageGroupPartitionTables.clear();
deletedRegionSet.clear();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PartitionInfo that = (PartitionInfo) o;
return storageGroupPartitionTables.equals(that.storageGroupPartitionTables)
&& deletedRegionSet.equals(that.deletedRegionSet);
}
@Override
public int hashCode() {
return Objects.hash(storageGroupPartitionTables, deletedRegionSet);
}
}