-
Notifications
You must be signed in to change notification settings - Fork 92
/
group.go
270 lines (225 loc) · 6.28 KB
/
group.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
/*
* 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 group
import (
"context"
"io"
"strconv"
"sync"
)
import (
"github.com/pkg/errors"
)
import (
"github.com/arana-db/arana/pkg/proto"
"github.com/arana-db/arana/pkg/runtime"
rcontext "github.com/arana-db/arana/pkg/runtime/context"
"github.com/arana-db/arana/pkg/util/log"
)
func init() {
proto.RegisterSequence(SequencePluginName, func() proto.EnhancedSequence {
return &groupSequence{}
})
}
const (
SequencePluginName = "group"
_stepKey = "step"
_startSequence int64 = 1
_defaultGroupStep int64 = 100
_initGroupSequenceTableSql = `
CREATE TABLE IF NOT EXISTS __arana_group_sequence (
id int AUTO_INCREMENT COMMENT 'primary key',
seq_val bigint COMMENT 'the current group start value',
step int COMMENT 'the step of the group',
table_name varchar(255) NOT NULL COMMENT 'arana logic table name',
renew_time datetime NOT NULL COMMENT 'node renew time',
PRIMARY KEY(id),
UNIQUE KEY(table_name)
) ENGINE = InnoDB;
`
_initGroupSequence = `INSERT INTO __arana_group_sequence(seq_val, step, table_name, renew_time) VALUE (?, ?, ?, now())`
_selectNextGroupWithXLock = `SELECT seq_val FROM __arana_group_sequence WHERE table_name = ? FOR UPDATE`
_updateNextGroup = `UPDATE __arana_group_sequence set seq_val = ?, renew_time = now() WHERE table_name = ?`
)
var (
// mu Solving the competition of the initialization of Sequence related library tables
mu sync.Mutex
finishInitTable = false
)
type groupSequence struct {
mu sync.Mutex
tableName string
step int64
currentGroupMaxVal int64
currentVal int64
}
// Start sequence and do some initialization operations
func (seq *groupSequence) Start(ctx context.Context, conf proto.SequenceConfig) error {
rt := ctx.Value(proto.RuntimeCtxKey{}).(runtime.Runtime)
ctx = rcontext.WithRead(rcontext.WithDirect(ctx))
// init table
if err := seq.initTable(ctx, rt); err != nil {
return err
}
// init sequence
if err := seq.initStep(conf); err != nil {
return err
}
seq.tableName = conf.Name
return nil
}
func (seq *groupSequence) initTable(ctx context.Context, rt runtime.Runtime) error {
mu.Lock()
defer mu.Unlock()
if finishInitTable {
return nil
}
tx, err := rt.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
ret, err := tx.Exec(ctx, "", _initGroupSequenceTableSql)
if err != nil {
return err
}
_, _ = ret.RowsAffected()
if _, _, err := tx.Commit(ctx); err != nil {
return err
}
finishInitTable = true
return nil
}
func (seq *groupSequence) initStep(conf proto.SequenceConfig) error {
seq.mu.Lock()
defer seq.mu.Unlock()
var step int64
stepValue, ok := conf.Option[_stepKey]
if ok {
tempStep, err := strconv.Atoi(stepValue)
if err != nil {
return err
}
step = int64(tempStep)
} else {
step = _defaultGroupStep
}
seq.step = step
return nil
}
// Acquire Apply for an increase ID
func (seq *groupSequence) Acquire(ctx context.Context) (int64, error) {
seq.mu.Lock()
defer seq.mu.Unlock()
if seq.currentVal >= seq.currentGroupMaxVal {
tenant := rcontext.Tenant(ctx)
schema := rcontext.Schema(ctx)
rt, err := runtime.Load(tenant, schema)
if err != nil {
log.Errorf("[sequence] load runtime.Runtime from schema=%s fail, %s", schema, err.Error())
return 0, err
}
err = seq.acquireNextGroup(ctx, rt)
if err != nil {
return 0, err
}
} else {
seq.currentVal++
}
return seq.currentVal, nil
}
func (seq *groupSequence) acquireNextGroup(ctx context.Context, rt runtime.Runtime) error {
ctx = rcontext.WithDirect(ctx)
tx, err := rt.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
rs, err := tx.Query(ctx, "", _selectNextGroupWithXLock, proto.NewValueString(seq.tableName))
if err != nil {
return err
}
ds, err := rs.Dataset()
if err != nil {
return err
}
vals := make([]proto.Value, 1)
row, err := ds.Next()
if err != nil {
// first time, init the start seq val for the table
if errors.Is(err, io.EOF) {
seq.currentVal = _startSequence
seq.currentGroupMaxVal = _startSequence + seq.step - 1
rs, err := tx.Exec(ctx, "", _initGroupSequence, proto.NewValueInt64(_startSequence), proto.NewValueInt64(seq.step), proto.NewValueString(seq.tableName))
if err != nil {
return err
}
_, _ = rs.RowsAffected()
_, _, err = tx.Commit(ctx)
if err != nil {
return err
}
return nil
}
return err
}
if err = row.Scan(vals); err != nil {
return err
}
_, _ = ds.Next()
if vals[0] != nil {
lastGroupStartVal, _ := vals[0].Int64()
// padding left
currentGroupStartVal := (lastGroupStartVal/seq.step+1)*seq.step + 1
seq.currentVal = currentGroupStartVal
seq.currentGroupMaxVal = currentGroupStartVal + seq.step - 1
rs, err := tx.Exec(ctx, "", _updateNextGroup, proto.NewValueInt64(currentGroupStartVal), proto.NewValueString(seq.tableName))
if err != nil {
return err
}
_, _ = rs.RowsAffected()
_, _, err = tx.Commit(ctx)
if err != nil {
return err
}
}
return nil
}
// Reset resets sequence info
func (seq *groupSequence) Reset() error {
return nil
}
// Update updates sequence info
func (seq *groupSequence) Update() error {
return nil
}
// Stop stops sequence
func (seq *groupSequence) Stop() error {
return nil
}
// CurrentVal gets this sequence current val
func (seq *groupSequence) CurrentVal() int64 {
return seq.currentVal
}
func (seq *groupSequence) GetSequenceConfig() proto.SequenceConfig {
return proto.SequenceConfig{
Name: seq.tableName,
Option: map[string]string{
_stepKey: strconv.FormatInt(seq.step, 10),
},
}
}