github.com/paybyphone/terraform@v0.9.5-0.20170613192930-9706042ddd51/state/remote/state.go (about) 1 package remote 2 3 import ( 4 "bytes" 5 "sync" 6 7 "github.com/hashicorp/terraform/state" 8 "github.com/hashicorp/terraform/terraform" 9 ) 10 11 // State implements the State interfaces in the state package to handle 12 // reading and writing the remote state. This State on its own does no 13 // local caching so every persist will go to the remote storage and local 14 // writes will go to memory. 15 type State struct { 16 mu sync.Mutex 17 18 Client Client 19 20 state, readState *terraform.State 21 } 22 23 // StateReader impl. 24 func (s *State) State() *terraform.State { 25 s.mu.Lock() 26 defer s.mu.Unlock() 27 28 return s.state.DeepCopy() 29 } 30 31 // StateWriter impl. 32 func (s *State) WriteState(state *terraform.State) error { 33 s.mu.Lock() 34 defer s.mu.Unlock() 35 36 s.state = state 37 return nil 38 } 39 40 // StateRefresher impl. 41 func (s *State) RefreshState() error { 42 s.mu.Lock() 43 defer s.mu.Unlock() 44 45 payload, err := s.Client.Get() 46 if err != nil { 47 return err 48 } 49 50 // no remote state is OK 51 if payload == nil { 52 return nil 53 } 54 55 state, err := terraform.ReadState(bytes.NewReader(payload.Data)) 56 if err != nil { 57 return err 58 } 59 60 s.state = state 61 s.readState = state 62 return nil 63 } 64 65 // StatePersister impl. 66 func (s *State) PersistState() error { 67 s.mu.Lock() 68 defer s.mu.Unlock() 69 70 s.state.IncrementSerialMaybe(s.readState) 71 72 var buf bytes.Buffer 73 if err := terraform.WriteState(s.state, &buf); err != nil { 74 return err 75 } 76 77 return s.Client.Put(buf.Bytes()) 78 } 79 80 // Lock calls the Client's Lock method if it's implemented. 81 func (s *State) Lock(info *state.LockInfo) (string, error) { 82 s.mu.Lock() 83 defer s.mu.Unlock() 84 85 if c, ok := s.Client.(ClientLocker); ok { 86 return c.Lock(info) 87 } 88 return "", nil 89 } 90 91 // Unlock calls the Client's Unlock method if it's implemented. 92 func (s *State) Unlock(id string) error { 93 s.mu.Lock() 94 defer s.mu.Unlock() 95 96 if c, ok := s.Client.(ClientLocker); ok { 97 return c.Unlock(id) 98 } 99 return nil 100 }