github.com/pingcap/tidb-lightning@v5.0.0-rc.0.20210428090220-84b649866577+incompatible/lightning/backend/allocator.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 backend
    15  
    16  import (
    17  	"sync/atomic"
    18  
    19  	"github.com/pingcap/tidb/meta/autoid"
    20  )
    21  
    22  // panickingAllocator is an ID allocator which panics on all operations except Rebase
    23  type panickingAllocator struct {
    24  	autoid.Allocator
    25  	base *int64
    26  	ty   autoid.AllocatorType
    27  }
    28  
    29  // NewPanickingAllocator creates a PanickingAllocator shared by all allocation types.
    30  func NewPanickingAllocators(base int64) autoid.Allocators {
    31  	sharedBase := &base
    32  	return autoid.NewAllocators(
    33  		&panickingAllocator{base: sharedBase, ty: autoid.RowIDAllocType},
    34  		&panickingAllocator{base: sharedBase, ty: autoid.AutoIncrementType},
    35  		&panickingAllocator{base: sharedBase, ty: autoid.AutoRandomType},
    36  	)
    37  }
    38  
    39  // Rebase implements the autoid.Allocator interface
    40  func (alloc *panickingAllocator) Rebase(tableID, newBase int64, allocIDs bool) error {
    41  	// CAS
    42  	for {
    43  		oldBase := atomic.LoadInt64(alloc.base)
    44  		if newBase <= oldBase {
    45  			break
    46  		}
    47  		if atomic.CompareAndSwapInt64(alloc.base, oldBase, newBase) {
    48  			break
    49  		}
    50  	}
    51  	return nil
    52  }
    53  
    54  // Base implements the autoid.Allocator interface
    55  func (alloc *panickingAllocator) Base() int64 {
    56  	return atomic.LoadInt64(alloc.base)
    57  }
    58  
    59  func (alloc *panickingAllocator) GetType() autoid.AllocatorType {
    60  	return alloc.ty
    61  }