forked from cubefs/cubefs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction.go
1569 lines (1352 loc) · 42.3 KB
/
transaction.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
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The CubeFS Authors.
//
// 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,
// 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.k
package metanode
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"golang.org/x/time/rate"
"net"
"strconv"
"strings"
"sync"
"time"
"github.com/cubefs/cubefs/proto"
"github.com/cubefs/cubefs/util"
"github.com/cubefs/cubefs/util/btree"
"github.com/cubefs/cubefs/util/log"
)
//Rollback Type
const (
TxNoOp uint8 = iota
TxUpdate
TxDelete
TxAdd
)
func (i *TxRollbackInode) ToString() string {
content := fmt.Sprintf("{inode:[ino:%v, type:%v, nlink:%v], quotaIds:%v, rbType:%v"+
"txInodeInfo:[Ino:%v, MpID:%v, CreateTime:%v, Timeout:%v, TxID:%v, MpMembers:%v]}",
i.inode.Inode, i.inode.Type, i.inode.NLink, i.quotaIds, i.rbType, i.txInodeInfo.Ino, i.txInodeInfo.MpID,
i.txInodeInfo.CreateTime, i.txInodeInfo.Timeout, i.txInodeInfo.TxID, i.txInodeInfo.MpMembers)
return content
}
type TxRollbackInode struct {
inode *Inode
txInodeInfo *proto.TxInodeInfo
rbType uint8 //Rollback Type
quotaIds []uint32
}
// Less tests whether the current TxRollbackInode item is less than the given one.
func (i *TxRollbackInode) Less(than btree.Item) bool {
ti, ok := than.(*TxRollbackInode)
if !ok {
return false
}
if i.txInodeInfo != nil && ti.txInodeInfo != nil {
return i.txInodeInfo.Ino < ti.txInodeInfo.Ino
}
return i.inode.Inode < ti.inode.Inode
}
// Copy returns a copy of the TxRollbackInode.
func (i *TxRollbackInode) Copy() btree.Item {
item := i.inode.Copy()
txInodeInfo := *i.txInodeInfo
quotaIds := make([]uint32, len(i.quotaIds))
copy(quotaIds, i.quotaIds)
return &TxRollbackInode{
inode: item.(*Inode),
quotaIds: quotaIds,
txInodeInfo: &txInodeInfo,
rbType: i.rbType,
}
}
func (i *TxRollbackInode) Marshal() (result []byte, err error) {
buff := bytes.NewBuffer(make([]byte, 0, 256))
bs, err := i.inode.Marshal()
if err != nil {
return
}
if err = binary.Write(buff, binary.BigEndian, uint32(len(bs))); err != nil {
return
}
if _, err = buff.Write(bs); err != nil {
return
}
bs, err = i.txInodeInfo.Marshal()
if err != nil {
return
}
if err = binary.Write(buff, binary.BigEndian, uint32(len(bs))); err != nil {
return nil, err
}
if _, err = buff.Write(bs); err != nil {
return
}
if err = binary.Write(buff, binary.BigEndian, &i.rbType); err != nil {
return
}
quotaBytes := bytes.NewBuffer(make([]byte, 0, 8))
for _, quotaId := range i.quotaIds {
if err = binary.Write(quotaBytes, binary.BigEndian, quotaId); err != nil {
return
}
}
_, err = buff.Write(quotaBytes.Bytes())
return buff.Bytes(), err
}
func (i *TxRollbackInode) Unmarshal(raw []byte) (err error) {
buff := bytes.NewBuffer(raw)
var dataLen uint32
if err = binary.Read(buff, binary.BigEndian, &dataLen); err != nil {
return
}
data := make([]byte, int(dataLen))
if _, err = buff.Read(data); err != nil {
return
}
ino := NewInode(0, 0)
if err = ino.Unmarshal(data); err != nil {
return
}
i.inode = ino
if err = binary.Read(buff, binary.BigEndian, &dataLen); err != nil {
return
}
data = make([]byte, int(dataLen))
if _, err = buff.Read(data); err != nil {
return
}
txInodeInfo := proto.NewTxInodeInfo("", 0, 0)
if err = txInodeInfo.Unmarshal(data); err != nil {
return
}
i.txInodeInfo = txInodeInfo
if err = binary.Read(buff, binary.BigEndian, &i.rbType); err != nil {
return
}
var quotaId uint32
for {
if buff.Len() == 0 {
break
}
if err = binary.Read(buff, binary.BigEndian, "aId); err != nil {
return
}
i.quotaIds = append(i.quotaIds, quotaId)
}
return
}
func NewTxRollbackInode(inode *Inode, quotaIds []uint32, txInodeInfo *proto.TxInodeInfo, rbType uint8) *TxRollbackInode {
return &TxRollbackInode{
inode: inode,
quotaIds: quotaIds,
txInodeInfo: txInodeInfo,
rbType: rbType,
}
}
type TxRollbackDentry struct {
dentry *Dentry
txDentryInfo *proto.TxDentryInfo
rbType uint8 //Rollback Type `
}
func (d *TxRollbackDentry) ToString() string {
content := fmt.Sprintf("{dentry:[ParentId:%v, Name:%v, Inode:%v, Type:%v], rbType:%v, "+
"txDentryInfo:[ParentId:%v, Name:%v, MpMembers:%v, TxID:%v, MpID:%v, CreateTime:%v, Timeout:%v]}",
d.dentry.ParentId, d.dentry.Name, d.dentry.Inode, d.dentry.Type, d.rbType, d.txDentryInfo.ParentId, d.txDentryInfo.Name,
d.txDentryInfo.MpMembers, d.txDentryInfo.TxID, d.txDentryInfo.MpID, d.txDentryInfo.CreateTime, d.txDentryInfo.Timeout)
return content
}
// Less tests whether the current TxRollbackDentry item is less than the given one.
func (d *TxRollbackDentry) Less(than btree.Item) bool {
td, ok := than.(*TxRollbackDentry)
return ok && d.txDentryInfo.GetKey() < td.txDentryInfo.GetKey()
}
// Copy returns a copy of the TxRollbackDentry.
func (d *TxRollbackDentry) Copy() btree.Item {
item := d.dentry.Copy()
txDentryInfo := *d.txDentryInfo
return &TxRollbackDentry{
dentry: item.(*Dentry),
txDentryInfo: &txDentryInfo,
rbType: d.rbType,
}
}
func (d *TxRollbackDentry) Marshal() (result []byte, err error) {
buff := bytes.NewBuffer(make([]byte, 0, 512))
bs, err := d.dentry.Marshal()
if err != nil {
return nil, err
}
if err = binary.Write(buff, binary.BigEndian, uint32(len(bs))); err != nil {
return nil, err
}
if _, err := buff.Write(bs); err != nil {
return nil, err
}
log.LogDebugf("TxRollbackDentry Marshal dentry %v", d.dentry)
log.LogDebugf("TxRollbackDentry Marshal txDentryInfo %v", d.ToString())
bs, err = d.txDentryInfo.Marshal()
if err != nil {
return nil, err
}
if err = binary.Write(buff, binary.BigEndian, uint32(len(bs))); err != nil {
return nil, err
}
if _, err := buff.Write(bs); err != nil {
return nil, err
}
if err = binary.Write(buff, binary.BigEndian, &d.rbType); err != nil {
return
}
return buff.Bytes(), nil
}
func (d *TxRollbackDentry) Unmarshal(raw []byte) (err error) {
buff := bytes.NewBuffer(raw)
var dataLen uint32
if err = binary.Read(buff, binary.BigEndian, &dataLen); err != nil {
return
}
log.LogDebugf("TxRollbackDentry Unmarshal len %v", dataLen)
data := make([]byte, int(dataLen))
if _, err = buff.Read(data); err != nil {
return
}
dentry := &Dentry{}
if err = dentry.Unmarshal(data); err != nil {
return
}
log.LogDebugf("TxRollbackDentry Unmarshal dentry %v", dentry)
d.dentry = dentry
if err = binary.Read(buff, binary.BigEndian, &dataLen); err != nil {
return
}
data = make([]byte, int(dataLen))
if _, err = buff.Read(data); err != nil {
return
}
txDentryInfo := proto.NewTxDentryInfo("", 0, "", 0)
if err = txDentryInfo.Unmarshal(data); err != nil {
return
}
d.txDentryInfo = txDentryInfo
if err = binary.Read(buff, binary.BigEndian, &d.rbType); err != nil {
return
}
return
}
func NewTxRollbackDentry(dentry *Dentry, txDentryInfo *proto.TxDentryInfo, rbType uint8) *TxRollbackDentry {
return &TxRollbackDentry{
dentry: dentry,
txDentryInfo: txDentryInfo,
rbType: rbType,
}
}
//TM
type TransactionManager struct {
//need persistence and sync to all the raft members of the mp
txIdAlloc *TxIDAllocator
txTree *BTree
txProcessor *TransactionProcessor
blacklist *util.Set
opLimiter *rate.Limiter
sync.RWMutex
}
//RM
type TransactionResource struct {
txRbInodeTree *BTree //key: inode id
txRbDentryTree *BTree // key: parentId_name
txProcessor *TransactionProcessor
sync.RWMutex
}
type TransactionProcessor struct {
txManager *TransactionManager //TM
txResource *TransactionResource //RM
mp *metaPartition
mask proto.TxOpMask
}
func (p *TransactionProcessor) Reset() {
p.txManager.Reset()
p.txResource.Reset()
}
func (p *TransactionProcessor) Pause() bool {
return p.mask == proto.TxPause
}
func NewTransactionManager(txProcessor *TransactionProcessor) *TransactionManager {
txMgr := &TransactionManager{
txIdAlloc: newTxIDAllocator(),
txTree: NewBtree(),
txProcessor: txProcessor,
blacklist: util.NewSet(),
opLimiter: rate.NewLimiter(rate.Inf, 128),
}
return txMgr
}
func NewTransactionResource(txProcessor *TransactionProcessor) *TransactionResource {
txRsc := &TransactionResource{
txRbInodeTree: NewBtree(),
txRbDentryTree: NewBtree(),
txProcessor: txProcessor,
}
return txRsc
}
func NewTransactionProcessor(mp *metaPartition) *TransactionProcessor {
txProcessor := &TransactionProcessor{
mp: mp,
}
txProcessor.txManager = NewTransactionManager(txProcessor)
txProcessor.txResource = NewTransactionResource(txProcessor)
if mp.config != nil {
go txProcessor.txManager.processExpiredTransactions()
}
return txProcessor
}
func (tm *TransactionManager) setLimit(val int) string {
if val > 0 {
tm.opLimiter.SetLimit(rate.Limit(val))
return fmt.Sprintf("%v", val)
}
tm.opLimiter.SetLimit(rate.Inf)
return "unlimited"
}
func (tm *TransactionManager) Reset() {
tm.blacklist.Clear()
tm.Lock()
tm.txIdAlloc.Reset()
tm.txTree.Reset()
tm.opLimiter.SetLimit(0)
tm.Unlock()
}
var test = false
func (tm *TransactionManager) processExpiredTransactions() {
mpId := tm.txProcessor.mp.config.PartitionId
log.LogInfof("processExpiredTransactions for mp[%v] started", mpId)
clearInterval := time.Second * 60
clearTimer := time.NewTimer(clearInterval)
txCheckVal := time.Second * 3
txCheckTimer := time.NewTimer(txCheckVal)
defer func() {
log.LogWarnf("processExpiredTransactions for mp[%v] exit", mpId)
txCheckTimer.Stop()
clearTimer.Stop()
return
}()
for {
select {
case <-tm.txProcessor.mp.stopC:
log.LogDebugf("[processExpiredTransactions] deleteWorker stop partition: %v", mpId)
return
default:
}
if _, ok := tm.txProcessor.mp.IsLeader(); !ok && !test {
log.LogDebugf("processExpiredTransactions: not leader sleep 1s, mp %d", mpId)
time.Sleep(time.Second * 10)
continue
}
select {
case <-tm.txProcessor.mp.stopC:
log.LogWarnf("processExpiredTransactions for mp[%v] stopped", mpId)
return
case <-clearTimer.C:
tm.blacklist.Clear()
clearTimer.Reset(clearInterval)
log.LogDebugf("processExpiredTransactions: blacklist cleared, mp %d", mpId)
case <-txCheckTimer.C:
if tm.txProcessor.Pause() {
txCheckTimer.Reset(txCheckVal)
continue
}
tm.processTx()
txCheckTimer.Reset(txCheckVal)
}
}
}
func (tm *TransactionManager) processTx() {
mpId := tm.txProcessor.mp.config.PartitionId
start := time.Now()
log.LogDebugf("processTx: mp %v mask %v", mpId, proto.GetMaskString(tm.txProcessor.mask))
defer func() {
log.LogDebugf("processTx: mp %d total cost %s", mpId, time.Since(start).String())
}()
limitCh := make(chan struct{}, 32)
var wg sync.WaitGroup
get := func() {
wg.Add(1)
limitCh <- struct{}{}
}
put := func() {
<-limitCh
wg.Done()
}
idx := 0
f := func(i BtreeItem) bool {
idx++
if idx%100 == 0 {
if _, ok := tm.txProcessor.mp.IsLeader(); !ok {
log.LogWarnf("processExpiredTransactions for mp[%v] already not leader and break tx tree traverse",
tm.txProcessor.mp.config.PartitionId)
return false
}
}
tx := i.(*proto.TransactionInfo)
rollbackFunc := func(skipSetStat bool) {
defer put()
status, err := tm.rollbackTx(tx.TxID, skipSetStat)
if err != nil || status != proto.OpOk {
log.LogWarnf("processExpiredTransactions: transaction (%v) expired, rolling back failed, status(%v), err(%v)",
tx, status, err)
return
}
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) expired, rolling back done", tx)
}
}
commitFunc := func() {
defer put()
status, err := tm.commitTx(tx.TxID, true)
if err != nil || status != proto.OpOk {
log.LogWarnf("processExpiredTransactions: transaction (%v) expired, commit failed, status(%v), err(%v)",
tx, status, err)
return
}
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) expired, commit done", tx)
}
}
delFunc := func() {
defer put()
status, err := tm.delTxFromRM(tx.TxID)
if err != nil || status != proto.OpOk {
log.LogWarnf("processExpiredTransactions: delTxFromRM (%v) expired, commit failed, status(%v), err(%v)",
tx, status, err)
return
}
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) delTxFromRM, commit done", tx)
}
}
clearOrphan := func() {
defer put()
tm.clearOrphanTx(tx)
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) clearOrphanTx", tx)
}
}
if tx.TmID != int64(mpId) {
if tx.CanDelete() {
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) can be deleted", tx)
}
get()
go delFunc()
return true
}
if tx.NeedClearOrphan() {
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: orphan transaction (%v) can be clear", tx)
}
get()
go clearOrphan()
return true
}
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: RM transaction (%v) is ongoing", tx)
}
return true
}
if tx.State == proto.TxStateCommit {
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) continue to commit...", tx)
}
get()
go commitFunc()
return true
}
if tx.State == proto.TxStateRollback {
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) continue to roll back...", tx)
}
get()
go rollbackFunc(true)
return true
}
if tx.State == proto.TxStatePreCommit {
if !tx.IsExpired() {
return true
}
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) expired, rolling back...", tx)
}
get()
go rollbackFunc(false)
return true
}
if tx.IsDone() {
if !tx.CanDelete() {
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) is ongoing", tx)
}
return true
}
if log.EnableDebug() {
log.LogDebugf("processExpiredTransactions: transaction (%v) can be deleted", tx)
}
get()
go delFunc()
return true
}
log.LogCriticalf("processExpiredTransactions: transaction (%v) is in state failed", tx)
return true
}
tm.txTree.GetTree().Ascend(f)
wg.Wait()
}
func (tm *TransactionManager) nextTxID() string {
id := tm.txIdAlloc.allocateTransactionID()
txId := fmt.Sprintf("%d_%d", tm.txProcessor.mp.config.PartitionId, id)
log.LogDebugf("nextTxID: txId:%v", txId)
return txId
}
func (tm *TransactionManager) txInRMDone(txId string) bool {
ifo := tm.getTransaction(txId)
if ifo == nil || ifo.Finish() {
log.LogWarnf("txInRMDone: tx in rm already done, txId %s, ifo %v", txId, ifo)
return true
}
return false
}
func (tm *TransactionManager) getTransaction(txID string) (txInfo *proto.TransactionInfo) {
txItem := proto.NewTxInfoBItem(txID)
item := tm.txTree.Get(txItem)
if item == nil {
return nil
}
txInfo = item.(*proto.TransactionInfo)
return
}
func (tm *TransactionManager) copyGetTx(txId string) (txInfo *proto.TransactionInfo) {
txItem := proto.NewTxInfoBItem(txId)
item := tm.txTree.CopyGet(txItem)
if item == nil {
return nil
}
txInfo = item.(*proto.TransactionInfo)
return
}
func (tm *TransactionManager) updateTxIdCursor(txId string) (err error) {
arr := strings.Split(txId, "_")
if len(arr) != 2 {
return fmt.Errorf("updateTxId: tx[%v] is invalid", txId)
}
id, err := strconv.ParseUint(arr[1], 10, 64)
if err != nil {
return fmt.Errorf("updateTxId: tx[%v] is invalid", txId)
}
if id > tm.txIdAlloc.getTransactionID() {
tm.txIdAlloc.setTransactionID(id)
}
return nil
}
func (tm *TransactionManager) addTxInfo(txInfo *proto.TransactionInfo) {
tm.txTree.ReplaceOrInsert(txInfo, true)
}
//TM register a transaction, process client transaction
func (tm *TransactionManager) registerTransaction(txInfo *proto.TransactionInfo) (err error) {
if uint64(txInfo.TmID) == tm.txProcessor.mp.config.PartitionId {
if err := tm.updateTxIdCursor(txInfo.TxID); err != nil {
log.LogErrorf("updateTxIdCursor failed, txInfo %s, err %s", txInfo.String(), err.Error())
return err
}
for _, inode := range txInfo.TxInodeInfos {
inode.SetCreateTime(txInfo.CreateTime)
inode.SetTimeout(txInfo.Timeout)
inode.SetTxId(txInfo.TxID)
}
for _, dentry := range txInfo.TxDentryInfos {
dentry.SetCreateTime(txInfo.CreateTime)
dentry.SetTimeout(txInfo.Timeout)
dentry.SetTxId(txInfo.TxID)
}
}
if info := tm.getTransaction(txInfo.TxID); info != nil {
log.LogWarnf("tx is already exist, txId %s, info %v", txInfo.TxID, info.String())
return nil
}
tm.addTxInfo(txInfo)
if log.EnableDebug() {
log.LogDebugf("registerTransaction: txInfo(%v)", txInfo)
}
return
}
func (tm *TransactionManager) deleteTxInfo(txId string) (status uint8) {
tm.Lock()
defer tm.Unlock()
status = proto.OpOk
txItem := proto.NewTxInfoBItem(txId)
item := tm.txTree.Delete(txItem)
if log.EnableDebug() {
log.LogDebugf("deleteTxInfo: tx[%v] is deleted, item %v", txId, item)
}
return
}
func (tm *TransactionManager) rollbackTxInfo(txId string) (status uint8) {
tm.Lock()
defer tm.Unlock()
status = proto.OpOk
tx := tm.getTransaction(txId)
if tx == nil {
status = proto.OpTxInfoNotExistErr
log.LogWarnf("rollbackTxInfo: rollback tx[%v] failed, not found", txId)
return
}
tx.State = proto.TxStateRollbackDone
tx.DoneTime = time.Now().Unix()
log.LogDebugf("rollbackTxInfo: tx[%v] is rolled back", tx)
return
}
func (tm *TransactionManager) commitTxInfo(txId string) (status uint8, err error) {
tm.Lock()
defer tm.Unlock()
status = proto.OpOk
tx := tm.getTransaction(txId)
if tx == nil {
status = proto.OpTxInfoNotExistErr
err = fmt.Errorf("commitTxInfo: commit tx[%v] failed, not found", txId)
return
}
tx.State = proto.TxStateCommitDone
tx.DoneTime = time.Now().Unix()
log.LogDebugf("commitTxInfo: tx[%v] is committed", tx)
return
}
func buildTxPacket(data interface{}, mp uint64, op uint8) (pkt *proto.Packet, err error) {
pkt = proto.NewPacketReqID()
pkt.Opcode = op
pkt.PartitionID = mp
err = pkt.MarshalData(data)
if err != nil {
errInfo := fmt.Sprintf("buildTxPacket: marshal txInfo [%v] failed", data)
err = errors.New(errInfo)
log.LogErrorf("%v", errInfo)
return nil, err
}
return
}
func (tm *TransactionManager) setTransactionState(txId string, state int32) (status uint8, err error) {
var val []byte
var resp interface{}
status = proto.OpOk
stateReq := &proto.TxSetStateRequest{
TxID: txId,
State: state,
}
val, _ = json.Marshal(stateReq)
resp, err = tm.txProcessor.mp.submit(opFSMTxSetState, val)
if err != nil {
log.LogWarnf("setTransactionState: set transaction[%v] state to [%v] failed, err[%v]", txId, state, err)
return proto.OpAgain, err
}
status = resp.(uint8)
if status != proto.OpOk {
errInfo := fmt.Sprintf("setTransactionState: set transaction[%v] state to [%v] failed", txId, state)
err = errors.New(errInfo)
log.LogWarnf("%v", errInfo)
}
return
}
func (tm *TransactionManager) delTxFromRM(txId string) (status uint8, err error) {
req := proto.TxApplyRequest{
TxID: txId,
}
val, err := json.Marshal(req)
if err != nil {
return
}
resp, err := tm.txProcessor.mp.submit(opFSMTxDelete, val)
if err != nil {
log.LogWarnf("delTxFromRM: delTxFromRM transaction[%v] failed, err[%v]", txId, err)
return proto.OpAgain, err
}
status = resp.(uint8)
if log.EnableDebug() {
log.LogDebugf("delTxFromRM: tx[%v] is deleted successfully, status (%s)", txId, proto.GetStatusStr(status))
}
return
}
func (tm *TransactionManager) clearOrphanTx(tx *proto.TransactionInfo) {
log.LogWarnf("clearOrphanTx: start to clearOrphanTx, tx %v", tx)
// check txInfo whether exist in tm
req := &proto.TxGetInfoRequest{
Pid: uint64(tx.TmID),
TxID: tx.TxID,
}
pkt, err := buildTxPacket(req, req.Pid, proto.OpMetaTxGet)
if err != nil {
return
}
mps := tx.GroupByMp()
tmpMp, ok := mps[req.Pid]
if !ok {
log.LogErrorf("clearOrphanTx: can't get tm Mp info from tx, tx %v", tx)
return
}
status := tm.txSendToMpWithAddrs(tmpMp.Members, pkt)
if status != proto.OpTxInfoNotExistErr {
log.LogWarnf("clearOrphanTx: tx is still exist, tx %v, status %s", tx, proto.GetStatusStr(status))
return
}
log.LogWarnf("clearOrphanTx: find tx in tm already not exist, start clear it from rm, tx %v", tx)
aReq := &proto.TxApplyRMRequest{
PartitionID: req.Pid,
TransactionInfo: tx,
}
newPkt := &Packet{}
err = tm.txProcessor.mp.TxRollbackRM(aReq, newPkt)
log.LogWarnf("clearOrphanTx: finally rollback tx in rm, tx %v, status %s, err %v",
tx, newPkt.GetResultMsg(), err)
return
}
func (tm *TransactionManager) commitTx(txId string, skipSetStat bool) (status uint8, err error) {
tx := tm.getTransaction(txId)
if tx == nil {
status = proto.OpTxInfoNotExistErr
log.LogWarnf("commitTx: tx[%v] not found, already success", txId)
return
}
if tx.State == proto.TxStateCommitDone {
status = proto.OpOk
log.LogWarnf("commitTx: tx[%v] is already commit", txId)
return
}
//1.set transaction to TxStateCommit
if !skipSetStat && tx.State != proto.TxStateCommit {
status, err = tm.setTransactionState(txId, proto.TxStateCommit)
if status != proto.OpOk {
log.LogWarnf("commitTx: set transaction[%v] state to TxStateCommit failed", tx)
return
}
}
//2. notify all related RMs that a transaction is completed
status = tm.sendToRM(tx, proto.OpTxCommitRM)
if status != proto.OpOk {
return
}
//3. TM commit the transaction
req := proto.TxApplyRequest{
TxID: txId,
}
val, err := json.Marshal(req)
if err != nil {
return
}
resp, err := tm.txProcessor.mp.submit(opFSMTxCommit, val)
if err != nil {
log.LogWarnf("commitTx: commit transaction[%v] failed, err[%v]", txId, err)
return proto.OpAgain, err
}
status = resp.(uint8)
log.LogDebugf("commitTx: tx[%v] is commited successfully", txId)
return
}
func (tm *TransactionManager) sendToRM(txInfo *proto.TransactionInfo, op uint8) (status uint8) {
status = proto.OpOk
mpIfos := txInfo.GroupByMp()
statusCh := make(chan uint8, len(mpIfos))
wg := sync.WaitGroup{}
mp := tm.txProcessor.mp
for mpId, ifo := range mpIfos {
req := &proto.TxApplyRMRequest{
VolName: mp.config.VolName,
PartitionID: mpId,
TransactionInfo: txInfo,
}
wg.Add(1)
pkt, _ := buildTxPacket(req, mpId, op)
if mp.config.PartitionId == mpId {
pt := &Packet{*pkt}
go func() {
defer wg.Done()
var err error
if op == proto.OpTxCommitRM {
err = mp.TxCommitRM(req, pt)
} else {
err = mp.TxRollbackRM(req, pt)
}
statusCh <- pt.ResultCode
if pt.ResultCode != proto.OpOk {
log.LogWarnf("sendToRM: invoke TxCommitRM failed, ifo %v, pkt %s, err %v", txInfo, pt.GetResultMsg(), err)
}
}()
continue
}
members := ifo.Members
go func() {
defer wg.Done()
status := tm.txSendToMpWithAddrs(members, pkt)
if status != proto.OpOk {
log.LogWarnf("sendToRM: send to rm failed, addr %s, pkt %s, status %s",
members, string(pkt.Data), proto.GetStatusStr(status))
}
statusCh <- status
}()
}
wg.Wait()
close(statusCh)
updateStatus := func(st uint8) uint8 {
if st == proto.OpTxConflictErr || st == proto.OpTxInfoNotExistErr {
log.LogWarnf("sendToRM: might have already been committed, tx[%v], status (%s)", txInfo, proto.GetStatusStr(st))
return proto.OpOk
} else if st == proto.OpTxRbInodeNotExistErr || st == proto.OpTxRbDentryNotExistErr {
log.LogWarnf("sendToRM: already done before or not add, tx[%v], status (%s)", txInfo, proto.GetStatusStr(st))
return proto.OpOk
} else {
return st
}
}
for st := range statusCh {
t := updateStatus(st)
if t != proto.OpOk {
return t
}
}
return status
}
func (tm *TransactionManager) rollbackTx(txId string, skipSetStat bool) (status uint8, err error) {
status = proto.OpOk
tx := tm.getTransaction(txId)
if tx == nil {
log.LogWarnf("commitTx: tx[%v] not found, already success", txId)
return
}
if tx.State == proto.TxStateRollbackDone {
status = proto.OpOk
log.LogWarnf("commitTx: tx[%v] is already rollback", txId)
return
}
//1.set transaction to TxStateRollback
if !skipSetStat && tx.State != proto.TxStateRollback {
status, err = tm.setTransactionState(txId, proto.TxStateRollback)
if status != proto.OpOk {
log.LogWarnf("commitTransaction: set transaction[%v] state to TxStateCommit failed", tx)
return
}
}
//2. notify all related RMs that a transaction is completed
status = tm.sendToRM(tx, proto.OpTxRollbackRM)
if status != proto.OpOk {
return
}
req := proto.TxApplyRequest{
TxID: txId,
}
val, err := json.Marshal(req)
if err != nil {
return
}
resp, err := tm.txProcessor.mp.submit(opFSMTxRollback, val)
if err != nil {
log.LogWarnf("commitTx: rollback transaction[%v] failed, err[%v]", txId, err)