-
Notifications
You must be signed in to change notification settings - Fork 0
/
txn_manager.go
289 lines (256 loc) · 7.3 KB
/
txn_manager.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
/*
* Tencent is pleased to support the open source community by making 蓝鲸 available.
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 manager
import (
"context"
"errors"
"sync"
"time"
"github.com/rs/xid"
"configcenter/src/common"
"configcenter/src/common/blog"
"configcenter/src/storage/dal"
"configcenter/src/storage/mongobyc"
"configcenter/src/storage/server/app/options"
"configcenter/src/storage/types"
)
type TxnManager struct {
enable bool
processor string
txnLifeLimit time.Duration // second
cache map[string]*Session
db mongobyc.Client
eventChan chan *types.Transaction
subscribers map[chan<- *types.Transaction]bool
ctx context.Context
sessionMutex sync.Mutex
pubsubMutex sync.Mutex
}
type Session struct {
Txninst *types.Transaction
mongobyc.Session
}
func New(ctx context.Context, opt options.TransactionConfig, db mongobyc.Client, listen string) *TxnManager {
tm := &TxnManager{
enable: opt.ShouldEnable(),
processor: listen,
txnLifeLimit: time.Second * time.Duration(float64(opt.GetTransactionLifetimeSecond())*1.5),
cache: map[string]*Session{},
db: db,
eventChan: make(chan *types.Transaction, 2048),
subscribers: map[chan<- *types.Transaction]bool{},
ctx: ctx,
}
return tm
}
func (tm *TxnManager) Subscribe(ch chan<- *types.Transaction) {
tm.pubsubMutex.Lock()
tm.subscribers[ch] = true
tm.pubsubMutex.Unlock()
}
func (tm *TxnManager) UnSubscribe(ch chan<- *types.Transaction) {
tm.pubsubMutex.Lock()
delete(tm.subscribers, ch)
tm.pubsubMutex.Unlock()
}
func (tm *TxnManager) Publish() {
for {
event := <-tm.eventChan
tm.pubsubMutex.Lock()
for subscriber := range tm.subscribers {
select {
case subscriber <- event:
case <-time.After(time.Second):
}
}
tm.pubsubMutex.Unlock()
}
}
func (tm *TxnManager) Run() error {
if tm.enable {
go tm.reconcileCache()
go tm.reconcilePersistence()
go tm.Publish()
}
<-tm.ctx.Done()
return nil
}
func (tm *TxnManager) reconcileCache() {
ticker := time.NewTicker(tm.txnLifeLimit)
for {
select {
case <-tm.ctx.Done():
ticker.Stop()
return
case <-ticker.C:
tm.sessionMutex.Lock()
for _, session := range tm.cache {
if time.Since(session.Txninst.LastTime) > tm.txnLifeLimit {
// ignore the abort error, cause the session will not be used again
go tm.Abort(session.Txninst.TxnID)
}
}
tm.sessionMutex.Unlock()
}
}
}
func (tm *TxnManager) reconcilePersistence() {
ticker := time.NewTicker(tm.txnLifeLimit * 2)
for {
select {
case <-tm.ctx.Done():
ticker.Stop()
return
case <-ticker.C:
txns := []types.Transaction{}
err := tm.db.Collection(common.BKTableNameTransaction).Find(tm.ctx, nil, nil, &txns)
if err != nil {
blog.Errorf("reconcile persistence faile: %v, we will retry %v later", err, tm.txnLifeLimit)
continue
}
for _, txn := range txns {
if time.Since(txn.LastTime) > tm.txnLifeLimit {
filter := dal.NewFilterBuilder().Eq(common.BKTxnIDField, txn.TxnID).Build()
update := types.Document{
"status": types.TxStatusException,
common.LastTimeField: time.Now(),
}
_, err := tm.db.Collection(common.BKTableNameTransaction).UpdateOne(tm.ctx, filter, update, nil)
if nil != err {
// the reconcile will handle this error, so we will not return this error
blog.Errorf("save transaction [%s] status to %#v faile: %s", txn.TxnID, txn.Status, err.Error())
}
ntxn := txn
tm.eventChan <- &ntxn
}
}
}
}
}
func (tm *TxnManager) GetSession(txnID string) *Session {
tm.sessionMutex.Lock()
session := tm.cache[txnID]
tm.sessionMutex.Unlock()
return session
}
func (tm *TxnManager) storeSession(txnID string, session *Session) {
tm.sessionMutex.Lock()
tm.cache[txnID] = session
tm.sessionMutex.Unlock()
}
func (tm *TxnManager) removeSession(txnID string) {
tm.sessionMutex.Lock()
delete(tm.cache, txnID)
tm.sessionMutex.Unlock()
}
func (tm *TxnManager) CreateTransaction(requestID string) (*Session, error) {
txn := types.Transaction{
RequestID: requestID,
Processor: tm.processor,
Status: types.TxStatusOnProgress,
CreateTime: time.Now(),
LastTime: time.Now(),
}
if !tm.enable {
return &Session{
Txninst: &txn,
}, nil
}
session := tm.db.Session().Create()
err := session.Open()
defer func() {
if err != nil {
session.Close()
}
}()
if nil != err {
return nil, err
}
err = session.StartTransaction()
if nil != err {
return nil, err
}
err = tm.db.Collection(common.BKTableNameTransaction).InsertOne(tm.ctx, txn, nil)
if err != nil {
// we should return this error,
// cause the transaction life cycle will not under txn manager's controll
return nil, err
}
txn.TxnID = tm.newTxnID()
inst := &Session{
Txninst: &txn,
Session: session,
}
tm.storeSession(txn.TxnID, inst)
return inst, nil
}
func (tm *TxnManager) newTxnID() string {
return tm.processor + "-" + xid.New().String()
}
func (tm *TxnManager) Commit(txnID string) error {
session := tm.GetSession(txnID)
if session == nil {
return errors.New("session not found")
}
txnerr := session.CommitTransaction()
defer func() {
if txnerr == nil {
session.Close()
tm.removeSession(txnID)
}
}()
if nil != txnerr {
session.Txninst.Status = types.TxStatusException
} else {
session.Txninst.Status = types.TxStatusCommited
}
tm.eventChan <- session.Txninst
filter := dal.NewFilterBuilder().Eq(common.BKTxnIDField, txnID).Build()
update := types.Document{
"status": session.Txninst.Status,
common.LastTimeField: time.Now(),
}
_, err := tm.db.Collection(common.BKTableNameTransaction).UpdateOne(tm.ctx, filter, update, nil)
if nil != err {
// the reconcile will handle this error, so we will not return this error
blog.Errorf("save transaction [%s] status to %#v faile: %s", txnID, session.Txninst.Status, err.Error())
}
return nil
}
func (tm *TxnManager) Abort(txnID string) error {
session := tm.GetSession(txnID)
if session == nil {
return errors.New("session not found")
}
txnerr := session.AbortTransaction()
defer func() {
session.Close()
tm.removeSession(txnID)
}()
if nil != txnerr {
session.Txninst.Status = types.TxStatusException
} else {
session.Txninst.Status = types.TxStatusAborted
}
tm.eventChan <- session.Txninst
filter := dal.NewFilterBuilder().Eq(common.BKTxnIDField, txnID).Build()
update := types.Document{
"status": session.Txninst.Status,
common.LastTimeField: time.Now(),
}
_, err := tm.db.Collection(common.BKTableNameTransaction).UpdateOne(tm.ctx, filter, update, nil)
if nil != err {
// the reconcile will handle this error, so we will not return this error
blog.Errorf("save transaction [%s] status to %#v faile: %s", txnID, session.Txninst.Status, err.Error())
}
return nil
}