2013-07-31 00:48:37 -04:00
|
|
|
package chroot
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/mitchellh/multistep"
|
|
|
|
"github.com/mitchellh/packer/packer"
|
|
|
|
"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 {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
}
|