github.com/koding/terraform@v0.6.4-0.20170608090606-5d7e0339779d/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.IncrementSerialMaybe(s.state) 36 s.state = state 37 return nil 38 } 39 40 func (s *InmemState) PersistState() error { 41 return nil 42 } 43 44 func (s *InmemState) Lock(*LockInfo) (string, error) { 45 return "", nil 46 } 47 48 func (s *InmemState) Unlock(string) error { 49 return nil 50 } 51 52 // inmemLocker is an in-memory State implementation for testing locks. 53 type inmemLocker struct { 54 *InmemState 55 56 mu sync.Mutex 57 lockInfo *LockInfo 58 // count the calls to Lock 59 lockCounter int 60 } 61 62 func (s *inmemLocker) Lock(info *LockInfo) (string, error) { 63 s.mu.Lock() 64 defer s.mu.Unlock() 65 s.lockCounter++ 66 67 lockErr := &LockError{ 68 Info: &LockInfo{}, 69 } 70 71 if s.lockInfo != nil { 72 lockErr.Err = errors.New("state locked") 73 *lockErr.Info = *s.lockInfo 74 return "", lockErr 75 } 76 77 info.Created = time.Now().UTC() 78 s.lockInfo = info 79 return s.lockInfo.ID, nil 80 } 81 82 func (s *inmemLocker) Unlock(id string) error { 83 s.mu.Lock() 84 defer s.mu.Unlock() 85 86 lockErr := &LockError{ 87 Info: &LockInfo{}, 88 } 89 90 if id != s.lockInfo.ID { 91 lockErr.Err = errors.New("invalid lock id") 92 *lockErr.Info = *s.lockInfo 93 return lockErr 94 } 95 96 s.lockInfo = nil 97 return nil 98 }