packer-cn/common/commonsteps/step_http_server.go

76 lines
1.7 KiB
Go
Raw Normal View History

package commonsteps
import (
"context"
"fmt"
2019-03-15 11:25:45 -04:00
"net/http"
2019-03-15 11:25:45 -04:00
"github.com/hashicorp/packer/common/net"
"github.com/hashicorp/packer/helper/multistep"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/packer"
)
// 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.
//
// Uses:
// ui packer.Ui
//
// Produces:
// http_port int - The port the HTTP server started on.
type StepHTTPServer struct {
HTTPDir string
2019-03-19 09:47:21 -04:00
HTTPPortMin int
HTTPPortMax int
HTTPAddress string
2019-03-15 11:25:45 -04:00
l *net.Listener
}
2019-03-15 11:25:45 -04:00
func (s *StepHTTPServer) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
if s.HTTPDir == "" {
2019-03-19 09:47:21 -04:00
state.Put("http_port", 0)
return multistep.ActionContinue
}
// Find an available TCP port for our HTTP server
var httpAddr string
2019-03-15 11:25:45 -04:00
var err error
s.l, err = net.ListenRangeConfig{
Min: s.HTTPPortMin,
Max: s.HTTPPortMax,
Addr: s.HTTPAddress,
2019-03-15 11:25:45 -04:00
Network: "tcp",
}.Listen(ctx)
if err != nil {
err := fmt.Errorf("Error finding port: %s", err)
state.Put("error", err)
ui.Error(err.Error())
2019-03-15 11:25:45 -04:00
return multistep.ActionHalt
}
2019-03-15 11:25:45 -04:00
ui.Say(fmt.Sprintf("Starting HTTP server on port %d", s.l.Port))
// Start the HTTP server and run it in the background
fileServer := http.FileServer(http.Dir(s.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
2019-03-15 11:25:45 -04:00
state.Put("http_port", s.l.Port)
return multistep.ActionContinue
}
func (s *StepHTTPServer) Cleanup(multistep.StateBag) {
if s.l != nil {
// Close the listener so that the HTTP server stops
s.l.Close()
}
}