2013-07-31 00:48:37 -04:00
|
|
|
package chroot
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2017-04-04 16:39:01 -04:00
|
|
|
"github.com/hashicorp/packer/packer"
|
2013-07-31 00:48:37 -04:00
|
|
|
"github.com/mitchellh/multistep"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
|
|
|
// StepFlock provisions the instance within a chroot.
|
2013-07-31 01:25:33 -04:00
|
|
|
//
|
|
|
|
// Produces:
|
|
|
|
// flock_cleanup Cleanup - To perform early cleanup
|
2013-07-31 00:48:37 -04:00
|
|
|
type StepFlock struct {
|
|
|
|
fh *os.File
|
|
|
|
}
|
|
|
|
|
2013-08-31 15:58:55 -04:00
|
|
|
func (s *StepFlock) Run(state multistep.StateBag) multistep.StepAction {
|
|
|
|
ui := state.Get("ui").(packer.Ui)
|
2013-07-31 00:48:37 -04:00
|
|
|
|
|
|
|
lockfile := "/var/lock/packer-chroot/lock"
|
|
|
|
if err := os.MkdirAll(filepath.Dir(lockfile), 0755); err != nil {
|
|
|
|
err := fmt.Errorf("Error creating lock: %s", err)
|
2013-08-31 15:58:55 -04:00
|
|
|
state.Put("error", err)
|
2013-07-31 00:48:37 -04:00
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Obtaining lock: %s", lockfile)
|
|
|
|
f, err := os.Create(lockfile)
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error creating lock: %s", err)
|
2013-08-31 15:58:55 -04:00
|
|
|
state.Put("error", err)
|
2013-07-31 00:48:37 -04:00
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
// LOCK!
|
|
|
|
if err := lockFile(f); err != nil {
|
2013-12-06 21:28:48 -05:00
|
|
|
err := fmt.Errorf("Error obtaining lock: %s", err)
|
2013-08-31 15:58:55 -04:00
|
|
|
state.Put("error", err)
|
2013-07-31 00:48:37 -04:00
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the file handle, we can't close it because we need to hold
|
|
|
|
// the lock.
|
|
|
|
s.fh = f
|
|
|
|
|
2013-08-31 15:58:55 -04:00
|
|
|
state.Put("flock_cleanup", s)
|
2013-07-31 00:48:37 -04:00
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
2013-08-31 15:58:55 -04:00
|
|
|
func (s *StepFlock) Cleanup(state multistep.StateBag) {
|
2013-07-31 01:25:33 -04:00
|
|
|
s.CleanupFunc(state)
|
|
|
|
}
|
|
|
|
|
2013-08-31 15:58:55 -04:00
|
|
|
func (s *StepFlock) CleanupFunc(state multistep.StateBag) error {
|
2013-07-31 00:48:37 -04:00
|
|
|
if s.fh == nil {
|
2013-07-31 01:25:33 -04:00
|
|
|
return nil
|
2013-07-31 00:48:37 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Unlocking: %s", s.fh.Name())
|
2013-07-31 01:25:33 -04:00
|
|
|
if err := unlockFile(s.fh); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
s.fh = nil
|
|
|
|
return nil
|
2013-07-31 00:48:37 -04:00
|
|
|
}
|