github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/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 map[string]interface{}) multistep.StepAction { 21 ui := state["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["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["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 creating lock: %s", err) 43 state["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["flock_cleanup"] = s 53 return multistep.ActionContinue 54 } 55 56 func (s *StepFlock) Cleanup(state map[string]interface{}) { 57 s.CleanupFunc(state) 58 } 59 60 func (s *StepFlock) CleanupFunc(state map[string]interface{}) 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 }