github.com/pingcap/chaos@v0.0.0-20190710112158-c86faf4b3719/pkg/core/db.go (about)

     1  package core
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  )
     7  
     8  // DB allows Chaos to set up and tear down database.
     9  type DB interface {
    10  	// SetUp initializes the database.
    11  	SetUp(ctx context.Context, nodes []string, node string) error
    12  	// TearDown tears down the database.
    13  	TearDown(ctx context.Context, nodes []string, node string) error
    14  	// Start starts the database
    15  	Start(ctx context.Context, node string) error
    16  	// Stop stops the database
    17  	Stop(ctx context.Context, node string) error
    18  	// Kill kills the database
    19  	Kill(ctx context.Context, node string) error
    20  	// IsRunning checks whether the database is running or not
    21  	IsRunning(ctx context.Context, node string) bool
    22  	// Name returns the unique name for the database
    23  	Name() string
    24  }
    25  
    26  // NoopDB is a DB but does nothing
    27  type NoopDB struct {
    28  }
    29  
    30  // SetUp initializes the database.
    31  func (NoopDB) SetUp(ctx context.Context, nodes []string, node string) error {
    32  	return nil
    33  }
    34  
    35  // TearDown tears down the datase.
    36  func (NoopDB) TearDown(ctx context.Context, nodes []string, node string) error {
    37  	return nil
    38  }
    39  
    40  // Start starts the database
    41  func (NoopDB) Start(ctx context.Context, node string) error {
    42  	return nil
    43  }
    44  
    45  // Stop stops the database
    46  func (NoopDB) Stop(ctx context.Context, node string) error {
    47  	return nil
    48  }
    49  
    50  // Kill kills the database
    51  func (NoopDB) Kill(ctx context.Context, node string) error {
    52  	return nil
    53  }
    54  
    55  // IsRunning checks whether the database is running or not
    56  func (NoopDB) IsRunning(ctx context.Context, node string) bool {
    57  	return true
    58  }
    59  
    60  // Name returns the unique name for the database
    61  func (NoopDB) Name() string {
    62  	return "noop"
    63  }
    64  
    65  var dbs = map[string]DB{}
    66  
    67  // RegisterDB registers db. Not thread-safe
    68  func RegisterDB(db DB) {
    69  	name := db.Name()
    70  	_, ok := dbs[name]
    71  	if ok {
    72  		panic(fmt.Sprintf("db %s is already registered", name))
    73  	}
    74  
    75  	dbs[name] = db
    76  }
    77  
    78  // GetDB gets the registered db.
    79  func GetDB(name string) DB {
    80  	return dbs[name]
    81  }
    82  
    83  func init() {
    84  	RegisterDB(NoopDB{})
    85  }