You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tx.go 5.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package sql
  18. import (
  19. "context"
  20. "database/sql/driver"
  21. "sync"
  22. "github.com/seata/seata-go/pkg/datasource/sql/undo"
  23. "github.com/seata/seata-go/pkg/datasource/sql/datasource"
  24. "github.com/seata/seata-go/pkg/protocol/branch"
  25. "github.com/seata/seata-go/pkg/protocol/message"
  26. "github.com/seata/seata-go/pkg/util/log"
  27. "github.com/pkg/errors"
  28. "github.com/seata/seata-go/pkg/datasource/sql/types"
  29. )
  30. const REPORT_RETRY_COUNT = 5
  31. var (
  32. hl sync.RWMutex
  33. txHooks []txHook
  34. )
  35. func RegisterTxHook(h txHook) {
  36. hl.Lock()
  37. defer hl.Unlock()
  38. txHooks = append(txHooks, h)
  39. }
  40. func CleanTxHooks() {
  41. hl.Lock()
  42. defer hl.Unlock()
  43. txHooks = make([]txHook, 0, 4)
  44. }
  45. type (
  46. txOption func(tx *Tx)
  47. txHook interface {
  48. BeforeCommit(tx *Tx)
  49. BeforeRollback(tx *Tx)
  50. }
  51. )
  52. func newTx(opts ...txOption) (driver.Tx, error) {
  53. tx := new(Tx)
  54. for i := range opts {
  55. opts[i](tx)
  56. }
  57. if err := tx.init(); err != nil {
  58. return nil, err
  59. }
  60. return tx, nil
  61. }
  62. // withDriverConn
  63. func withDriverConn(conn *Conn) txOption {
  64. return func(t *Tx) {
  65. t.conn = conn
  66. }
  67. }
  68. // withOriginTx
  69. func withOriginTx(tx driver.Tx) txOption {
  70. return func(t *Tx) {
  71. t.target = tx
  72. }
  73. }
  74. // withTxCtx
  75. func withTxCtx(ctx *types.TransactionContext) txOption {
  76. return func(t *Tx) {
  77. t.ctx = ctx
  78. }
  79. }
  80. // Tx
  81. type Tx struct {
  82. conn *Conn
  83. ctx *types.TransactionContext
  84. target driver.Tx
  85. }
  86. // Commit do commit action
  87. // case 1. no open global-transaction, just do local transaction commit
  88. // case 2. not need flush undolog, is XA mode, do local transaction commit
  89. // case 3. need run AT transaction
  90. func (tx *Tx) Commit() error {
  91. if len(txHooks) != 0 {
  92. hl.RLock()
  93. defer hl.RUnlock()
  94. for i := range txHooks {
  95. txHooks[i].BeforeCommit(tx)
  96. }
  97. }
  98. if tx.ctx.TransType == types.Local {
  99. return tx.commitOnLocal()
  100. }
  101. // flush undo log if need, is XA mode
  102. if tx.ctx.TransType == types.XAMode {
  103. return tx.commitOnXA()
  104. }
  105. return tx.commitOnAT()
  106. }
  107. func (tx *Tx) Rollback() error {
  108. if len(txHooks) != 0 {
  109. hl.RLock()
  110. defer hl.RUnlock()
  111. for i := range txHooks {
  112. txHooks[i].BeforeRollback(tx)
  113. }
  114. }
  115. err := tx.target.Rollback()
  116. if err != nil {
  117. if tx.ctx.OpenGlobalTrsnaction() && tx.ctx.IsBranchRegistered() {
  118. tx.report(false)
  119. }
  120. }
  121. return err
  122. }
  123. // init
  124. func (tx *Tx) init() error {
  125. return nil
  126. }
  127. // commitOnLocal
  128. func (tx *Tx) commitOnLocal() error {
  129. return tx.target.Commit()
  130. }
  131. // commitOnXA
  132. func (tx *Tx) commitOnXA() error {
  133. return nil
  134. }
  135. // commitOnAT
  136. func (tx *Tx) commitOnAT() error {
  137. // if TX-Mode is AT, run regis this transaction branch
  138. if err := tx.register(tx.ctx); err != nil {
  139. return err
  140. }
  141. undoLogMgr, err := undo.GetUndoLogManager(tx.ctx.DBType)
  142. if err != nil {
  143. return err
  144. }
  145. if err := undoLogMgr.FlushUndoLog(tx.ctx, tx.conn.targetConn); err != nil {
  146. if rerr := tx.report(false); rerr != nil {
  147. return errors.WithStack(rerr)
  148. }
  149. return errors.WithStack(err)
  150. }
  151. if err := tx.commitOnLocal(); err != nil {
  152. if rerr := tx.report(false); rerr != nil {
  153. return errors.WithStack(rerr)
  154. }
  155. return errors.WithStack(err)
  156. }
  157. tx.report(true)
  158. return nil
  159. }
  160. // register
  161. func (tx *Tx) register(ctx *types.TransactionContext) error {
  162. if !ctx.HasUndoLog() || !ctx.HasLockKey() {
  163. return nil
  164. }
  165. lockKey := ""
  166. for _, v := range ctx.LockKeys {
  167. lockKey += v + ";"
  168. }
  169. request := message.BranchRegisterRequest{
  170. Xid: ctx.XaID,
  171. BranchType: branch.BranchType(ctx.TransType),
  172. ResourceId: ctx.ResourceID,
  173. LockKey: lockKey,
  174. ApplicationData: nil,
  175. }
  176. dataSourceManager := datasource.GetDataSourceManager(branch.BranchType(ctx.TransType))
  177. branchId, err := dataSourceManager.BranchRegister(context.Background(), "", request)
  178. if err != nil {
  179. log.Infof("Failed to report branch status: %s", err.Error())
  180. return err
  181. }
  182. ctx.BranchID = uint64(branchId)
  183. return nil
  184. }
  185. // report
  186. func (tx *Tx) report(success bool) error {
  187. if tx.ctx.BranchID == 0 {
  188. return nil
  189. }
  190. status := getStatus(success)
  191. request := message.BranchReportRequest{
  192. Xid: tx.ctx.XaID,
  193. BranchId: int64(tx.ctx.BranchID),
  194. ResourceId: tx.ctx.ResourceID,
  195. Status: status,
  196. }
  197. dataSourceManager := datasource.GetDataSourceManager(branch.BranchType(tx.ctx.TransType))
  198. retry := REPORT_RETRY_COUNT
  199. for retry > 0 {
  200. err := dataSourceManager.BranchReport(context.Background(), request)
  201. if err != nil {
  202. retry--
  203. log.Infof("Failed to report [%s / %s] commit done [%s] Retry Countdown: %s", tx.ctx.BranchID, tx.ctx.XaID, success, retry)
  204. if retry == 0 {
  205. log.Infof("Failed to report branch status: %s", err.Error())
  206. return err
  207. }
  208. } else {
  209. return nil
  210. }
  211. }
  212. return nil
  213. }
  214. func getStatus(success bool) branch.BranchStatus {
  215. if success {
  216. return branch.BranchStatusPhaseoneDone
  217. } else {
  218. return branch.BranchStatusPhaseoneFailed
  219. }
  220. }