github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/pkg/func-rollback/rollback.go (about)

     1  // Copyright 2019 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package rollback
    15  
    16  import (
    17  	"sync"
    18  
    19  	"github.com/pingcap/tiflow/dm/pkg/log"
    20  	"go.uber.org/zap"
    21  )
    22  
    23  // FuncRollback records function used to rolling back some operations.
    24  // It is currently used by units' Init to release resources when failing in the half-way.
    25  type FuncRollback struct {
    26  	Name string
    27  	Fn   func()
    28  }
    29  
    30  // FuncRollbackHolder holds some RollbackFuncs.
    31  type FuncRollbackHolder struct {
    32  	mu    sync.Mutex
    33  	owner string // used to make log clearer
    34  	fns   []FuncRollback
    35  }
    36  
    37  // NewRollbackHolder creates a new FuncRollbackHolder instance.
    38  func NewRollbackHolder(owner string) *FuncRollbackHolder {
    39  	return &FuncRollbackHolder{
    40  		owner: owner,
    41  		fns:   make([]FuncRollback, 0),
    42  	}
    43  }
    44  
    45  // Add adds a func to the holder.
    46  func (h *FuncRollbackHolder) Add(fn FuncRollback) {
    47  	h.mu.Lock()
    48  	defer h.mu.Unlock()
    49  	h.fns = append(h.fns, fn)
    50  }
    51  
    52  // RollbackReverseOrder executes rollback functions in reverse order.
    53  func (h *FuncRollbackHolder) RollbackReverseOrder() {
    54  	h.mu.Lock()
    55  	defer h.mu.Unlock()
    56  	for i := len(h.fns) - 1; i >= 0; i-- {
    57  		fn := h.fns[i]
    58  		log.L().Info("rolling back", zap.String("functon", fn.Name), zap.String("onwer", h.owner))
    59  		fn.Fn()
    60  	}
    61  }