2013-12-21 17:27:00 -05:00
|
|
|
package iso
|
2013-06-12 02:44:40 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/mitchellh/multistep"
|
|
|
|
"github.com/mitchellh/packer/packer"
|
|
|
|
"log"
|
|
|
|
"math/rand"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2014-05-06 11:03:51 -04:00
|
|
|
// This step creates and runs the HTTP server that is serving files from the
|
|
|
|
// directory specified by the 'http_directory` configuration parameter in the
|
|
|
|
// template.
|
2013-06-12 02:44:40 -04:00
|
|
|
//
|
|
|
|
// Uses:
|
|
|
|
// config *config
|
|
|
|
// ui packer.Ui
|
|
|
|
//
|
|
|
|
// Produces:
|
|
|
|
// http_port int - The port the HTTP server started on.
|
|
|
|
type stepHTTPServer struct {
|
|
|
|
l net.Listener
|
|
|
|
}
|
|
|
|
|
2013-08-31 15:44:58 -04:00
|
|
|
func (s *stepHTTPServer) Run(state multistep.StateBag) multistep.StepAction {
|
2015-05-27 17:01:08 -04:00
|
|
|
config := state.Get("config").(*Config)
|
2013-08-31 15:44:58 -04:00
|
|
|
ui := state.Get("ui").(packer.Ui)
|
2013-06-12 02:44:40 -04:00
|
|
|
|
|
|
|
var httpPort uint = 0
|
|
|
|
if config.HTTPDir == "" {
|
2013-08-31 15:44:58 -04:00
|
|
|
state.Put("http_port", httpPort)
|
2013-06-12 02:44:40 -04:00
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find an available TCP port for our HTTP server
|
|
|
|
var httpAddr string
|
|
|
|
portRange := int(config.HTTPPortMax - config.HTTPPortMin)
|
|
|
|
for {
|
|
|
|
var err error
|
2013-06-28 21:59:29 -04:00
|
|
|
var offset uint = 0
|
|
|
|
|
|
|
|
if portRange > 0 {
|
|
|
|
// Intn will panic if portRange == 0, so we do a check.
|
|
|
|
offset = uint(rand.Intn(portRange))
|
|
|
|
}
|
|
|
|
|
|
|
|
httpPort = offset + config.HTTPPortMin
|
2013-06-12 02:44:40 -04:00
|
|
|
httpAddr = fmt.Sprintf(":%d", httpPort)
|
|
|
|
log.Printf("Trying port: %d", httpPort)
|
|
|
|
s.l, err = net.Listen("tcp", httpAddr)
|
|
|
|
if err == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ui.Say(fmt.Sprintf("Starting HTTP server on port %d", httpPort))
|
|
|
|
|
|
|
|
// Start the HTTP server and run it in the background
|
|
|
|
fileServer := http.FileServer(http.Dir(config.HTTPDir))
|
|
|
|
server := &http.Server{Addr: httpAddr, Handler: fileServer}
|
|
|
|
go server.Serve(s.l)
|
|
|
|
|
|
|
|
// Save the address into the state so it can be accessed in the future
|
2013-08-31 15:44:58 -04:00
|
|
|
state.Put("http_port", httpPort)
|
2013-06-12 02:44:40 -04:00
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
2013-08-31 15:44:58 -04:00
|
|
|
func (s *stepHTTPServer) Cleanup(multistep.StateBag) {
|
2013-06-12 02:44:40 -04:00
|
|
|
if s.l != nil {
|
|
|
|
// Close the listener so that the HTTP server stops
|
|
|
|
s.l.Close()
|
|
|
|
}
|
|
|
|
}
|