github.com/nevins-b/terraform@v0.3.8-0.20170215184714-bbae22007d5a/state/remote/state.go (about) 1 package remote 2 3 import ( 4 "bytes" 5 6 "github.com/hashicorp/terraform/terraform" 7 ) 8 9 // State implements the State interfaces in the state package to handle 10 // reading and writing the remote state. This State on its own does no 11 // local caching so every persist will go to the remote storage and local 12 // writes will go to memory. 13 type State struct { 14 Client Client 15 16 state, readState *terraform.State 17 } 18 19 // StateReader impl. 20 func (s *State) State() *terraform.State { 21 return s.state.DeepCopy() 22 } 23 24 // StateWriter impl. 25 func (s *State) WriteState(state *terraform.State) error { 26 s.state = state 27 return nil 28 } 29 30 // StateRefresher impl. 31 func (s *State) RefreshState() error { 32 payload, err := s.Client.Get() 33 if err != nil { 34 return err 35 } 36 37 // no remote state is OK 38 if payload == nil { 39 return nil 40 } 41 42 state, err := terraform.ReadState(bytes.NewReader(payload.Data)) 43 if err != nil { 44 return err 45 } 46 47 s.state = state 48 s.readState = state 49 return nil 50 } 51 52 // StatePersister impl. 53 func (s *State) PersistState() error { 54 s.state.IncrementSerialMaybe(s.readState) 55 56 var buf bytes.Buffer 57 if err := terraform.WriteState(s.state, &buf); err != nil { 58 return err 59 } 60 61 return s.Client.Put(buf.Bytes()) 62 } 63 64 // Lock calls the Client's Lock method if it's implemented. 65 func (s *State) Lock(reason string) error { 66 if c, ok := s.Client.(stateLocker); ok { 67 return c.Lock(reason) 68 } 69 return nil 70 } 71 72 // Unlock calls the Client's Unlock method if it's implemented. 73 func (s *State) Unlock() error { 74 if c, ok := s.Client.(stateLocker); ok { 75 return c.Unlock() 76 } 77 return nil 78 } 79 80 // stateLocker mirrors the state.Locker interface. This can be implemented by 81 // Clients to provide methods for locking and unlocking remote state. 82 type stateLocker interface { 83 Lock(reason string) error 84 Unlock() error 85 }