github.com/ferranbt/nomad@v0.9.3-0.20190607002617-85c449b7667c/plugins/base/plugin.go (about)

     1  package base
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"reflect"
     7  
     8  	plugin "github.com/hashicorp/go-plugin"
     9  	"github.com/hashicorp/nomad/plugins/base/proto"
    10  	"github.com/ugorji/go/codec"
    11  	"google.golang.org/grpc"
    12  )
    13  
    14  const (
    15  	// PluginTypeBase implements the base plugin interface
    16  	PluginTypeBase = "base"
    17  
    18  	// PluginTypeDriver implements the driver plugin interface
    19  	PluginTypeDriver = "driver"
    20  
    21  	// PluginTypeDevice implements the device plugin interface
    22  	PluginTypeDevice = "device"
    23  )
    24  
    25  var (
    26  	// Handshake is a common handshake that is shared by all plugins and Nomad.
    27  	Handshake = plugin.HandshakeConfig{
    28  		// ProtocolVersion for the executor protocol.
    29  		// Version 1: pre 0.9 netrpc based executor
    30  		// Version 2: 0.9+ grpc based executor
    31  		ProtocolVersion:  2,
    32  		MagicCookieKey:   "NOMAD_PLUGIN_MAGIC_COOKIE",
    33  		MagicCookieValue: "e4327c2e01eabfd75a8a67adb114fb34a757d57eee7728d857a8cec6e91a7255",
    34  	}
    35  )
    36  
    37  // PluginBase is wraps a BasePlugin and implements go-plugins GRPCPlugin
    38  // interface to expose the interface over gRPC.
    39  type PluginBase struct {
    40  	plugin.NetRPCUnsupportedPlugin
    41  	Impl BasePlugin
    42  }
    43  
    44  func (p *PluginBase) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error {
    45  	proto.RegisterBasePluginServer(s, &basePluginServer{
    46  		impl:   p.Impl,
    47  		broker: broker,
    48  	})
    49  	return nil
    50  }
    51  
    52  func (p *PluginBase) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) {
    53  	return &BasePluginClient{
    54  		Client:  proto.NewBasePluginClient(c),
    55  		DoneCtx: ctx,
    56  	}, nil
    57  }
    58  
    59  // MsgpackHandle is a shared handle for encoding/decoding of structs
    60  var MsgpackHandle = func() *codec.MsgpackHandle {
    61  	h := &codec.MsgpackHandle{}
    62  	h.RawToString = true
    63  	h.MapType = reflect.TypeOf(map[string]interface{}(nil))
    64  	return h
    65  }()
    66  
    67  // MsgPackDecode is used to decode a MsgPack encoded object
    68  func MsgPackDecode(buf []byte, out interface{}) error {
    69  	return codec.NewDecoder(bytes.NewReader(buf), MsgpackHandle).Decode(out)
    70  }
    71  
    72  // MsgPackEncode is used to encode an object to MsgPack
    73  func MsgPackEncode(b *[]byte, in interface{}) error {
    74  	return codec.NewEncoderBytes(b, MsgpackHandle).Encode(in)
    75  }