github.com/rothwerx/packer@v0.9.0/builder/amazon/chroot/step_flock.go (about)

     1  package chroot
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  	"log"
     8  	"os"
     9  	"path/filepath"
    10  )
    11  
    12  // StepFlock provisions the instance within a chroot.
    13  //
    14  // Produces:
    15  //   flock_cleanup Cleanup - To perform early cleanup
    16  type StepFlock struct {
    17  	fh *os.File
    18  }
    19  
    20  func (s *StepFlock) Run(state multistep.StateBag) multistep.StepAction {
    21  	ui := state.Get("ui").(packer.Ui)
    22  
    23  	lockfile := "/var/lock/packer-chroot/lock"
    24  	if err := os.MkdirAll(filepath.Dir(lockfile), 0755); err != nil {
    25  		err := fmt.Errorf("Error creating lock: %s", err)
    26  		state.Put("error", err)
    27  		ui.Error(err.Error())
    28  		return multistep.ActionHalt
    29  	}
    30  
    31  	log.Printf("Obtaining lock: %s", lockfile)
    32  	f, err := os.Create(lockfile)
    33  	if err != nil {
    34  		err := fmt.Errorf("Error creating lock: %s", err)
    35  		state.Put("error", err)
    36  		ui.Error(err.Error())
    37  		return multistep.ActionHalt
    38  	}
    39  
    40  	// LOCK!
    41  	if err := lockFile(f); err != nil {
    42  		err := fmt.Errorf("Error obtaining lock: %s", err)
    43  		state.Put("error", err)
    44  		ui.Error(err.Error())
    45  		return multistep.ActionHalt
    46  	}
    47  
    48  	// Set the file handle, we can't close it because we need to hold
    49  	// the lock.
    50  	s.fh = f
    51  
    52  	state.Put("flock_cleanup", s)
    53  	return multistep.ActionContinue
    54  }
    55  
    56  func (s *StepFlock) Cleanup(state multistep.StateBag) {
    57  	s.CleanupFunc(state)
    58  }
    59  
    60  func (s *StepFlock) CleanupFunc(state multistep.StateBag) error {
    61  	if s.fh == nil {
    62  		return nil
    63  	}
    64  
    65  	log.Printf("Unlocking: %s", s.fh.Name())
    66  	if err := unlockFile(s.fh); err != nil {
    67  		return err
    68  	}
    69  
    70  	s.fh = nil
    71  	return nil
    72  }