github.com/magodo/terraform@v0.11.12-beta1/state/inmem.go (about)

     1  package state
     2  
     3  import (
     4  	"errors"
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/hashicorp/terraform/terraform"
     9  )
    10  
    11  // InmemState is an in-memory state storage.
    12  type InmemState struct {
    13  	mu    sync.Mutex
    14  	state *terraform.State
    15  }
    16  
    17  func (s *InmemState) State() *terraform.State {
    18  	s.mu.Lock()
    19  	defer s.mu.Unlock()
    20  
    21  	return s.state.DeepCopy()
    22  }
    23  
    24  func (s *InmemState) RefreshState() error {
    25  	s.mu.Lock()
    26  	defer s.mu.Unlock()
    27  
    28  	return nil
    29  }
    30  
    31  func (s *InmemState) WriteState(state *terraform.State) error {
    32  	s.mu.Lock()
    33  	defer s.mu.Unlock()
    34  
    35  	state = state.DeepCopy()
    36  
    37  	if s.state != nil {
    38  		state.Serial = s.state.Serial
    39  
    40  		if !s.state.MarshalEqual(state) {
    41  			state.Serial++
    42  		}
    43  	}
    44  
    45  	s.state = state
    46  
    47  	return nil
    48  }
    49  
    50  func (s *InmemState) PersistState() error {
    51  	return nil
    52  }
    53  
    54  func (s *InmemState) Lock(*LockInfo) (string, error) {
    55  	return "", nil
    56  }
    57  
    58  func (s *InmemState) Unlock(string) error {
    59  	return nil
    60  }
    61  
    62  // inmemLocker is an in-memory State implementation for testing locks.
    63  type inmemLocker struct {
    64  	*InmemState
    65  
    66  	mu       sync.Mutex
    67  	lockInfo *LockInfo
    68  	// count the calls to Lock
    69  	lockCounter int
    70  }
    71  
    72  func (s *inmemLocker) Lock(info *LockInfo) (string, error) {
    73  	s.mu.Lock()
    74  	defer s.mu.Unlock()
    75  	s.lockCounter++
    76  
    77  	lockErr := &LockError{
    78  		Info: &LockInfo{},
    79  	}
    80  
    81  	if s.lockInfo != nil {
    82  		lockErr.Err = errors.New("state locked")
    83  		*lockErr.Info = *s.lockInfo
    84  		return "", lockErr
    85  	}
    86  
    87  	info.Created = time.Now().UTC()
    88  	s.lockInfo = info
    89  	return s.lockInfo.ID, nil
    90  }
    91  
    92  func (s *inmemLocker) Unlock(id string) error {
    93  	s.mu.Lock()
    94  	defer s.mu.Unlock()
    95  
    96  	lockErr := &LockError{
    97  		Info: &LockInfo{},
    98  	}
    99  
   100  	if id != s.lockInfo.ID {
   101  		lockErr.Err = errors.New("invalid lock id")
   102  		*lockErr.Info = *s.lockInfo
   103  		return lockErr
   104  	}
   105  
   106  	s.lockInfo = nil
   107  	return nil
   108  }