-
Notifications
You must be signed in to change notification settings - Fork 269
/
storage_orm.go
209 lines (186 loc) · 5.67 KB
/
storage_orm.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
// Copyright 2022 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 election
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"github.com/pingcap/log"
ormUtil "github.com/pingcap/tiflow/engine/pkg/orm"
"github.com/pingcap/tiflow/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const (
recordRowID = 1
// leaderRowID is not used for node probing, it is only used to lock the leader row.
leaderRowID = 2
)
// Value implements the driver.Valuer interface
func (r Record) Value() (driver.Value, error) {
return json.Marshal(r)
}
// Scan implements the sql.Scanner interface
func (r *Record) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
return json.Unmarshal(b, r)
}
// TableNameElection is the table name of election.
var TableNameElection = "election"
// DO mapped from table <election>
type DO struct {
ID uint32 `gorm:"column:id;type:int(10) unsigned;primaryKey" json:"id"`
LeaderID string `gorm:"column:leader_id;type:text;not null" json:"leader_id"`
Record *Record `gorm:"column:record;type:text" json:"record"`
Version uint64 `gorm:"column:version;type:bigint(20) unsigned;not null" json:"version"`
}
// TableName Election's table name
func (*DO) TableName() string {
return TableNameElection
}
// ORMStorage is a storage implementation based on SQL database.
type ORMStorage struct {
db *gorm.DB
tableName string
}
// NewORMStorageFromSQLDB creates a new ORMStorage from sql.DB.
func NewORMStorageFromSQLDB(backendDB *sql.DB, tableName string) (*ORMStorage, error) {
db, err := ormUtil.NewGormDB(backendDB, "mysql")
if err != nil {
return nil, err
}
return NewORMStorage(db, tableName)
}
// NewORMStorage creates a new ORMStorage.
func NewORMStorage(db *gorm.DB, tableName string) (*ORMStorage, error) {
TableNameElection = tableName
if err := db.AutoMigrate(&DO{}); err != nil {
return nil, errors.Trace(err)
}
return &ORMStorage{
db: db,
tableName: tableName,
}, nil
}
// Get implements Storage.Get.
func (s *ORMStorage) Get(ctx context.Context) (*Record, error) {
var do DO
ret := s.db.WithContext(ctx).Where("id = ?", recordRowID).Limit(1).Find(&do)
if ret.Error != nil {
if ret.Error == gorm.ErrRecordNotFound {
return &Record{}, nil
}
return nil, errors.Trace(ret.Error)
}
if ret.RowsAffected == 0 {
return &Record{}, nil
}
do.Record.Version = int64(do.Version)
return do.Record, nil
}
// Update implements Storage.Update.
func (s *ORMStorage) Update(ctx context.Context, record *Record, isLeaderChanged bool) error {
if record.Version == 0 {
if !isLeaderChanged {
log.Panic("invalid operation")
}
return s.create(ctx, record)
}
return s.update(ctx, record, isLeaderChanged)
}
func (s *ORMStorage) update(ctx context.Context, record *Record, isLeaderChanged bool) error {
handleRet := func(ret *gorm.DB) error {
if ret.Error != nil {
return errors.Trace(ret.Error)
}
if ret.RowsAffected != 1 {
return errors.ErrElectionRecordConflict.GenWithStackByArgs()
}
return nil
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// TODO: find more efficient way
ret := tx.Where("id = ? AND version = ?", recordRowID, record.Version).
Updates(DO{
LeaderID: record.LeaderID,
Record: record,
Version: uint64(record.Version) + 1,
})
if err := handleRet(ret); err != nil {
return errors.Trace(err)
}
if isLeaderChanged {
ret := tx.Where("id = ?", leaderRowID).
Updates(DO{
LeaderID: record.LeaderID,
Record: nil,
Version: uint64(record.Version) + 1,
})
return handleRet(ret)
}
return nil
})
}
func (s *ORMStorage) create(ctx context.Context, record *Record) error {
rows := []*DO{
{
ID: recordRowID,
LeaderID: record.LeaderID,
Record: record,
Version: uint64(record.Version) + 1,
},
{
ID: leaderRowID,
LeaderID: record.LeaderID,
Record: nil, /* record is not saved in leader row */
Version: uint64(record.Version) + 1, /* equals to recordRow */
},
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
ret := tx.WithContext(ctx).Create(rows)
if ret.Error != nil {
return errors.Trace(ret.Error)
}
if ret.RowsAffected == 0 {
return errors.ErrElectionRecordConflict.GenWithStackByArgs()
} else if ret.RowsAffected != int64(len(rows)) {
log.Panic("Transaction atomicity is broken when updating election record")
}
return nil
})
}
// TxnWithLeaderLock execute a transaction with leader row locked.
func (s *ORMStorage) TxnWithLeaderLock(ctx context.Context, leaderID string, fc func(tx *gorm.DB) error) error {
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var do DO
ret := tx.Select("leader_id").Where("id = ? and leader_id = ?", leaderRowID, leaderID).
Clauses(clause.Locking{
Strength: "SHARE",
Table: clause.Table{Name: clause.CurrentTable},
}).Limit(1).Find(&do)
if ret.Error != nil {
if ret.Error == gorm.ErrRecordNotFound {
return errors.ErrElectorNotLeader.GenWithStackByArgs(leaderID)
}
return errors.Trace(ret.Error)
}
if ret.RowsAffected != 1 {
return errors.ErrElectorNotLeader.GenWithStackByArgs(leaderID)
}
return fc(tx)
})
}