github.com/paultyng/terraform@v0.6.11-0.20180227224804-66ff8f8bed40/command/testdata/statelocker.go (about)

     1  // statelocker use used for testing command with a locked state.
     2  // This will lock the state file at a given path, then wait for a sigal. On
     3  // SIGINT and SIGTERM the state will be Unlocked before exit.
     4  package main
     5  
     6  import (
     7  	"io"
     8  	"log"
     9  	"os"
    10  	"os/signal"
    11  	"syscall"
    12  	"time"
    13  
    14  	"github.com/hashicorp/terraform/state"
    15  )
    16  
    17  func main() {
    18  	if len(os.Args) != 2 {
    19  		log.Fatal(os.Args[0], "statefile")
    20  	}
    21  
    22  	s := &state.LocalState{
    23  		Path: os.Args[1],
    24  	}
    25  
    26  	info := state.NewLockInfo()
    27  	info.Operation = "test"
    28  	info.Info = "state locker"
    29  
    30  	lockID, err := s.Lock(info)
    31  	if err != nil {
    32  		io.WriteString(os.Stderr, err.Error())
    33  		return
    34  	}
    35  
    36  	// signal to the caller that we're locked
    37  	io.WriteString(os.Stdout, "LOCKID "+lockID)
    38  
    39  	defer func() {
    40  		if err := s.Unlock(lockID); err != nil {
    41  			io.WriteString(os.Stderr, err.Error())
    42  		}
    43  	}()
    44  
    45  	c := make(chan os.Signal, 1)
    46  	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
    47  
    48  	// timeout after 10 second in case we don't get cleaned up by the test
    49  	select {
    50  	case <-time.After(10 * time.Second):
    51  	case <-c:
    52  	}
    53  }