packer-cn/packer/rpc/builder.go

103 lines
2.2 KiB
Go
Raw Normal View History

2013-05-04 16:47:11 -04:00
package rpc
import (
"context"
"net/rpc"
2018-01-22 20:21:10 -05:00
"github.com/hashicorp/packer/packer"
2013-05-04 16:47:11 -04:00
)
// An implementation of packer.Builder where the builder is actually executed
// over an RPC connection.
type builder struct {
2013-05-04 16:47:11 -04:00
client *rpc.Client
2014-09-02 17:23:06 -04:00
mux *muxBroker
2013-05-04 16:47:11 -04:00
}
// BuilderServer wraps a packer.Builder implementation and makes it exportable
// as part of a Golang RPC server.
type BuilderServer struct {
builder packer.Builder
2014-09-02 17:23:06 -04:00
mux *muxBroker
2013-05-04 16:47:11 -04:00
}
type BuilderPrepareArgs struct {
Configs []interface{}
2013-05-04 16:47:11 -04:00
}
type BuilderPrepareResponse struct {
Warnings []string
2014-04-26 16:31:22 -04:00
Error *BasicError
}
func (b *builder) Prepare(config ...interface{}) ([]string, error) {
var resp BuilderPrepareResponse
cerr := b.client.Call("Builder.Prepare", &BuilderPrepareArgs{config}, &resp)
if cerr != nil {
return nil, cerr
}
2014-04-26 16:31:22 -04:00
var err error = nil
if resp.Error != nil {
err = resp.Error
}
2014-04-26 16:31:22 -04:00
return resp.Warnings, err
2013-05-04 16:47:11 -04:00
}
func (b *builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
2013-12-10 15:14:08 -05:00
nextId := b.mux.NextId()
server := newServerWithMux(b.mux, nextId)
2013-12-10 15:14:08 -05:00
server.RegisterHook(hook)
server.RegisterUi(ui)
go server.Serve()
var responseId uint32
if err := b.client.Call("Builder.Run", nextId, &responseId); err != nil {
return nil, err
}
2013-12-10 15:14:08 -05:00
if responseId == 0 {
return nil, nil
}
client, err := newClientWithMux(b.mux, responseId)
if err != nil {
return nil, err
}
2013-12-10 15:14:08 -05:00
return client.Artifact(), nil
2013-05-04 16:47:11 -04:00
}
func (b *BuilderServer) Prepare(args *BuilderPrepareArgs, reply *BuilderPrepareResponse) error {
warnings, err := b.builder.Prepare(args.Configs...)
*reply = BuilderPrepareResponse{
Warnings: warnings,
2014-04-26 16:31:22 -04:00
Error: NewBasicError(err),
}
2013-05-04 16:47:11 -04:00
return nil
}
func (b *BuilderServer) Run(ctx context.Context, streamId uint32, reply *uint32) error {
client, err := newClientWithMux(b.mux, streamId)
2013-05-04 16:47:11 -04:00
if err != nil {
2013-12-10 15:14:08 -05:00
return NewBasicError(err)
2013-05-04 16:47:11 -04:00
}
2013-12-10 15:14:08 -05:00
defer client.Close()
2013-05-04 16:47:11 -04:00
artifact, err := b.builder.Run(ctx, client.Ui(), client.Hook())
if err != nil {
2013-12-10 15:14:08 -05:00
return NewBasicError(err)
}
2013-12-10 15:14:08 -05:00
*reply = 0
if artifact != nil {
streamId = b.mux.NextId()
server := newServerWithMux(b.mux, streamId)
2013-12-10 15:14:08 -05:00
server.RegisterArtifact(artifact)
go server.Serve()
*reply = streamId
}
2013-05-04 16:47:11 -04:00
return nil
}