forked from tikv/pd
/
namespace_classifier.go
445 lines (376 loc) · 10.8 KB
/
namespace_classifier.go
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
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package table
import (
"encoding/json"
"fmt"
"math"
"net/http"
"path"
"regexp"
"sync"
"time"
log "github.com/pingcap/log"
"github.com/pingcap/pd/server/core"
"github.com/pingcap/pd/server/namespace"
"github.com/pkg/errors"
"go.uber.org/zap"
)
func init() {
namespace.RegisterClassifier("table", NewTableNamespaceClassifier)
}
// Namespace defines two things:
// 1. relation between a Name and several tables
// 2. relation between a Name and several stores
// It is used to bind tables with stores
type Namespace struct {
ID uint64 `json:"ID"`
Name string `json:"Name"`
TableIDs map[int64]bool `json:"table_ids,omitempty"`
StoreIDs map[uint64]bool `json:"store_ids,omitempty"`
Meta bool `json:"meta,omitempty"`
}
// NewNamespace creates a new namespace
func NewNamespace(id uint64, name string) *Namespace {
return &Namespace{
ID: id,
Name: name,
TableIDs: make(map[int64]bool),
StoreIDs: make(map[uint64]bool),
}
}
// GetName returns namespace's Name or default 'global' value
func (ns *Namespace) GetName() string {
if ns != nil {
return ns.Name
}
return namespace.DefaultNamespace
}
// GetID returns namespace's ID or 0
func (ns *Namespace) GetID() uint64 {
if ns != nil {
return ns.ID
}
return 0
}
// AddTableID adds a tableID to this namespace
func (ns *Namespace) AddTableID(tableID int64) {
if ns.TableIDs == nil {
ns.TableIDs = make(map[int64]bool)
}
ns.TableIDs[tableID] = true
}
// AddStoreID adds a storeID to this namespace
func (ns *Namespace) AddStoreID(storeID uint64) {
if ns.StoreIDs == nil {
ns.StoreIDs = make(map[uint64]bool)
}
ns.StoreIDs[storeID] = true
}
// tableNamespaceClassifier implements Classifier interface
type tableNamespaceClassifier struct {
sync.RWMutex
nsInfo *namespacesInfo
kv *core.KV
idAlloc core.IDAllocator
http.Handler
}
const kvRangeLimit = 1000
// NewTableNamespaceClassifier creates a new namespace classifier that
// classifies stores and regions by table range.
func NewTableNamespaceClassifier(kv *core.KV, idAlloc core.IDAllocator) (namespace.Classifier, error) {
nsInfo := newNamespacesInfo()
if err := nsInfo.loadNamespaces(kv, kvRangeLimit); err != nil {
return nil, err
}
c := &tableNamespaceClassifier{
nsInfo: nsInfo,
kv: kv,
idAlloc: idAlloc,
}
c.Handler = newTableClassifierHandler(c)
return c, nil
}
func (c *tableNamespaceClassifier) GetAllNamespaces() []string {
c.RLock()
defer c.RUnlock()
nsList := make([]string, 0, len(c.nsInfo.namespaces))
for name := range c.nsInfo.namespaces {
nsList = append(nsList, name)
}
nsList = append(nsList, namespace.DefaultNamespace)
return nsList
}
func (c *tableNamespaceClassifier) GetStoreNamespace(storeInfo *core.StoreInfo) string {
c.RLock()
defer c.RUnlock()
for name, ns := range c.nsInfo.namespaces {
_, ok := ns.StoreIDs[storeInfo.Id]
if ok {
return name
}
}
return namespace.DefaultNamespace
}
func (c *tableNamespaceClassifier) GetRegionNamespace(regionInfo *core.RegionInfo) string {
c.RLock()
defer c.RUnlock()
isMeta := Key(regionInfo.GetStartKey()).IsMeta()
tableID := Key(regionInfo.GetStartKey()).TableID()
if tableID == 0 && !isMeta {
return namespace.DefaultNamespace
}
for name, ns := range c.nsInfo.namespaces {
_, ok := ns.TableIDs[tableID]
if ok || (isMeta && ns.Meta) {
return name
}
}
return namespace.DefaultNamespace
}
func (c *tableNamespaceClassifier) AllowMerge(one *core.RegionInfo, other *core.RegionInfo) bool {
return Key(one.GetStartKey()).TableID() == Key(other.GetStartKey()).TableID()
}
// GetNamespaces returns all namespace details.
func (c *tableNamespaceClassifier) GetNamespaces() []*Namespace {
c.RLock()
defer c.RUnlock()
return c.nsInfo.getNamespaces()
}
// GetNamespaceByName returns whether namespace exists
func (c *tableNamespaceClassifier) IsNamespaceExist(name string) bool {
c.RLock()
defer c.RUnlock()
return c.nsInfo.getNamespaceByName(name) != nil
}
// CreateNamespace creates a new Namespace.
func (c *tableNamespaceClassifier) CreateNamespace(name string) error {
c.Lock()
defer c.Unlock()
r := regexp.MustCompile(`^\w+$`)
matched := r.MatchString(name)
if !matched {
return errors.New("Name should be 0-9, a-z or A-Z")
}
if name == namespace.DefaultNamespace {
return errors.Errorf("%s is reserved as default namespace", name)
}
if n := c.nsInfo.getNamespaceByName(name); n != nil {
return errors.New("Duplicate namespace Name")
}
id, err := c.idAlloc.Alloc()
if err != nil {
return err
}
ns := NewNamespace(id, name)
err = c.putNamespaceLocked(ns)
return err
}
// AddNamespaceTableID adds table ID to namespace.
func (c *tableNamespaceClassifier) AddNamespaceTableID(name string, tableID int64) error {
c.Lock()
defer c.Unlock()
n := c.nsInfo.getNamespaceByName(name)
if n == nil {
return errors.Errorf("invalid namespace Name %s, not found", name)
}
if c.nsInfo.IsTableIDExist(tableID) {
return errors.New("Table ID already exists in this cluster")
}
n.AddTableID(tableID)
return c.putNamespaceLocked(n)
}
// RemoveNamespaceTableID removes table ID from namespace.
func (c *tableNamespaceClassifier) RemoveNamespaceTableID(name string, tableID int64) error {
c.Lock()
defer c.Unlock()
n := c.nsInfo.getNamespaceByName(name)
if n == nil {
return errors.Errorf("invalid namespace Name %s, not found", name)
}
if _, ok := n.TableIDs[tableID]; !ok {
return errors.Errorf("Table ID %d is not belong to %s", tableID, name)
}
delete(n.TableIDs, tableID)
return c.putNamespaceLocked(n)
}
// AddMetaToNamespace adds meta to a namespace.
func (c *tableNamespaceClassifier) AddMetaToNamespace(name string) error {
c.Lock()
defer c.Unlock()
n := c.nsInfo.getNamespaceByName(name)
if n == nil {
return errors.Errorf("invalid namespace Name %s, not found", name)
}
if c.nsInfo.IsMetaExist() {
return errors.New("meta is already set")
}
n.Meta = true
return c.putNamespaceLocked(n)
}
// RemoveMeta removes meta from a namespace.
func (c *tableNamespaceClassifier) RemoveMeta(name string) error {
c.Lock()
defer c.Unlock()
n := c.nsInfo.getNamespaceByName(name)
if n == nil {
return errors.Errorf("invalid namespace Name %s, not found", name)
}
if !n.Meta {
return errors.Errorf("meta is not belong to %s", name)
}
n.Meta = false
return c.putNamespaceLocked(n)
}
// AddNamespaceStoreID adds store ID to namespace.
func (c *tableNamespaceClassifier) AddNamespaceStoreID(name string, storeID uint64) error {
c.Lock()
defer c.Unlock()
n := c.nsInfo.getNamespaceByName(name)
if n == nil {
return errors.Errorf("invalid namespace Name %s, not found", name)
}
if c.nsInfo.IsStoreIDExist(storeID) {
return errors.New("Store ID already exists in this namespace")
}
n.AddStoreID(storeID)
return c.putNamespaceLocked(n)
}
// RemoveNamespaceStoreID removes store ID from namespace.
func (c *tableNamespaceClassifier) RemoveNamespaceStoreID(name string, storeID uint64) error {
c.Lock()
defer c.Unlock()
n := c.nsInfo.getNamespaceByName(name)
if n == nil {
return errors.Errorf("invalid namespace Name %s, not found", name)
}
if _, ok := n.StoreIDs[storeID]; !ok {
return errors.Errorf("Store ID %d is not belong to %s", storeID, name)
}
delete(n.StoreIDs, storeID)
return c.putNamespaceLocked(n)
}
// ReloadNamespaces reloads ns info from kv storage
func (c *tableNamespaceClassifier) ReloadNamespaces() error {
nsInfo := newNamespacesInfo()
c.Lock()
defer c.Unlock()
if err := nsInfo.loadNamespaces(c.kv, kvRangeLimit); err != nil {
return err
}
c.nsInfo = nsInfo
return nil
}
func (c *tableNamespaceClassifier) putNamespaceLocked(ns *Namespace) error {
if c.kv != nil {
if err := c.nsInfo.saveNamespace(c.kv, ns); err != nil {
return err
}
}
c.nsInfo.setNamespace(ns)
return nil
}
type namespacesInfo struct {
namespaces map[string]*Namespace
}
func newNamespacesInfo() *namespacesInfo {
return &namespacesInfo{
namespaces: make(map[string]*Namespace),
}
}
func (namespaceInfo *namespacesInfo) getNamespaceByName(name string) *Namespace {
namespace, ok := namespaceInfo.namespaces[name]
if !ok {
return nil
}
return namespace
}
func (namespaceInfo *namespacesInfo) setNamespace(item *Namespace) {
namespaceInfo.namespaces[item.Name] = item
}
func (namespaceInfo *namespacesInfo) getNamespaceCount() int {
return len(namespaceInfo.namespaces)
}
func (namespaceInfo *namespacesInfo) getNamespaces() []*Namespace {
nsList := make([]*Namespace, 0, len(namespaceInfo.namespaces))
for _, item := range namespaceInfo.namespaces {
nsList = append(nsList, item)
}
return nsList
}
// IsTableIDExist returns true if table ID exists in namespacesInfo
func (namespaceInfo *namespacesInfo) IsTableIDExist(tableID int64) bool {
for _, ns := range namespaceInfo.namespaces {
_, ok := ns.TableIDs[tableID]
if ok {
return true
}
}
return false
}
// IsStoreIDExist returns true if store ID exists in namespacesInfo
func (namespaceInfo *namespacesInfo) IsStoreIDExist(storeID uint64) bool {
for _, ns := range namespaceInfo.namespaces {
_, ok := ns.StoreIDs[storeID]
if ok {
return true
}
}
return false
}
// IsMetaExist returns true if meta is binded to a namespace.
func (namespaceInfo *namespacesInfo) IsMetaExist() bool {
for _, ns := range namespaceInfo.namespaces {
if ns.Meta {
return true
}
}
return false
}
func (namespaceInfo *namespacesInfo) namespacePath(nsID uint64) string {
return path.Join("namespace", fmt.Sprintf("%20d", nsID))
}
func (namespaceInfo *namespacesInfo) saveNamespace(kv *core.KV, ns *Namespace) error {
value, err := json.Marshal(ns)
if err != nil {
return errors.WithStack(err)
}
err = kv.Save(namespaceInfo.namespacePath(ns.GetID()), string(value))
return err
}
func (namespaceInfo *namespacesInfo) loadNamespaces(kv *core.KV, rangeLimit int) error {
start := time.Now()
nextID := uint64(0)
endKey := namespaceInfo.namespacePath(math.MaxUint64)
for {
key := namespaceInfo.namespacePath(nextID)
res, err := kv.LoadRange(key, endKey, rangeLimit)
if err != nil {
return err
}
for _, s := range res {
ns := &Namespace{}
if err := json.Unmarshal([]byte(s), ns); err != nil {
return errors.WithStack(err)
}
nextID = ns.GetID() + 1
namespaceInfo.setNamespace(ns)
}
if len(res) < rangeLimit {
log.Info("load namespaces information",
zap.Int("namespace-count", namespaceInfo.getNamespaceCount()),
zap.Duration("cost", time.Since(start)))
return nil
}
}
}