github.com/bradfeehan/terraform@v0.7.0-rc3.0.20170529055808-34b45c5ad841/backend/local/hook_state.go (about)

     1  package local
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  
     7  	"github.com/hashicorp/terraform/state"
     8  	"github.com/hashicorp/terraform/terraform"
     9  )
    10  
    11  // interval between forced PersistState calls by StateHook
    12  const persistStateHookInterval = 10 * time.Second
    13  
    14  // StateHook is a hook that continuously updates the state by calling
    15  // WriteState on a state.State.
    16  type StateHook struct {
    17  	terraform.NilHook
    18  	sync.Mutex
    19  
    20  	// lastPersist is the time of the last call to PersistState, for periodic
    21  	// updates to remote state. PostStateUpdate will force a call PersistState
    22  	// if it has been more that persistStateHookInterval since the last call to
    23  	// PersistState.
    24  	lastPersist time.Time
    25  
    26  	State state.State
    27  }
    28  
    29  func (h *StateHook) PostStateUpdate(
    30  	s *terraform.State) (terraform.HookAction, error) {
    31  	h.Lock()
    32  	defer h.Unlock()
    33  
    34  	if h.State != nil {
    35  		// Write the new state
    36  		if err := h.State.WriteState(s); err != nil {
    37  			return terraform.HookActionHalt, err
    38  		}
    39  
    40  		// periodically persist the state
    41  		if time.Since(h.lastPersist) > persistStateHookInterval {
    42  			if err := h.persistState(); err != nil {
    43  				return terraform.HookActionHalt, err
    44  			}
    45  		}
    46  	}
    47  
    48  	// Continue forth
    49  	return terraform.HookActionContinue, nil
    50  }
    51  
    52  func (h *StateHook) persistState() error {
    53  	if h.State != nil {
    54  		err := h.State.PersistState()
    55  		h.lastPersist = time.Now()
    56  		return err
    57  	}
    58  	return nil
    59  }