1 Star 0 Fork 0

lanyulei/go-plugin

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
client_test.go 27.87 KB
一键复制 编辑 原始数据 按行查看 历史
Mitchell Hashimoto 提交于 2020-05-13 08:27 +08:00 . Add a test mode
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
package plugin
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
hclog "github.com/hashicorp/go-hclog"
)
func TestClient(t *testing.T) {
process := helperProcess("mock")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer c.Kill()
// Test that it parses the proper address
addr, err := c.Start()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
if addr.Network() != "tcp" {
t.Fatalf("bad: %#v", addr)
}
if addr.String() != ":1234" {
t.Fatalf("bad: %#v", addr)
}
// Test that it exits properly if killed
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
// this test isn't expected to get a client
if !c.killed() {
t.Fatal("Client should have failed")
}
}
// This tests a bug where Kill would start
func TestClient_killStart(t *testing.T) {
// Create a temporary dir to store the result file
td, err := ioutil.TempDir("", "plugin")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.RemoveAll(td)
// Start the client
path := filepath.Join(td, "booted")
process := helperProcess("bad-version", path)
c := NewClient(&ClientConfig{Cmd: process, HandshakeConfig: testHandshake})
defer c.Kill()
// Verify our path doesn't exist
if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
t.Fatalf("bad: %s", err)
}
// Test that it parses the proper address
if _, err := c.Start(); err == nil {
t.Fatal("expected error")
}
// Verify we started
if _, err := os.Stat(path); err != nil {
t.Fatalf("bad: %s", err)
}
if err := os.Remove(path); err != nil {
t.Fatalf("bad: %s", err)
}
// Test that Kill does nothing really
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
if !c.killed() {
t.Fatal("process should have failed")
}
// Verify our path doesn't exist
if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
t.Fatalf("bad: %s", err)
}
}
func TestClient_testCleanup(t *testing.T) {
// Create a temporary dir to store the result file
td, err := ioutil.TempDir("", "plugin")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.RemoveAll(td)
// Create a path that the helper process will write on cleanup
path := filepath.Join(td, "output")
// Test the cleanup
process := helperProcess("cleanup", path)
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
// Grab the client so the process starts
if _, err := c.Client(); err != nil {
c.Kill()
t.Fatalf("err: %s", err)
}
// Kill it gracefully
c.Kill()
// Test for the file
if _, err := os.Stat(path); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestClient_testInterface(t *testing.T) {
process := helperProcess("test-interface")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer c.Kill()
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
result := impl.Double(21)
if result != 42 {
t.Fatalf("bad: %#v", result)
}
// Kill it
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
}
func TestClient_grpc_servercrash(t *testing.T) {
process := helperProcess("test-grpc")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testGRPCPluginMap,
AllowedProtocols: []Protocol{ProtocolGRPC},
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
if v := c.Protocol(); v != ProtocolGRPC {
t.Fatalf("bad: %s", v)
}
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
_, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
c.process.Kill()
select {
case <-c.doneCtx.Done():
case <-time.After(time.Second * 2):
t.Fatal("Context was not closed")
}
}
func TestClient_grpc(t *testing.T) {
process := helperProcess("test-grpc")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testGRPCPluginMap,
AllowedProtocols: []Protocol{ProtocolGRPC},
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
if v := c.Protocol(); v != ProtocolGRPC {
t.Fatalf("bad: %s", v)
}
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
result := impl.Double(21)
if result != 42 {
t.Fatalf("bad: %#v", result)
}
// Kill it
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
}
func TestClient_grpcNotAllowed(t *testing.T) {
process := helperProcess("test-grpc")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer c.Kill()
if _, err := c.Start(); err == nil {
t.Fatal("should error")
}
}
func TestClient_grpcSyncStdio(t *testing.T) {
var syncOut, syncErr safeBuffer
process := helperProcess("test-grpc")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testGRPCPluginMap,
AllowedProtocols: []Protocol{ProtocolGRPC},
SyncStdout: &syncOut,
SyncStderr: &syncErr,
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
if v := c.Protocol(); v != ProtocolGRPC {
t.Fatalf("bad: %s", v)
}
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
// Print the data
stdout := []byte("hello\nworld!")
stderr := []byte("and some error\n messages!")
impl.PrintStdio(stdout, stderr)
// Wait for it to be copied
for syncOut.String() == "" || syncErr.String() == "" {
time.Sleep(10 * time.Millisecond)
}
// We should get the data
if syncOut.String() != string(stdout) {
t.Fatalf("stdout didn't match: %s", syncOut.String())
}
if syncErr.String() != string(stderr) {
t.Fatalf("stderr didn't match: %s", syncErr.String())
}
}
func TestClient_cmdAndReattach(t *testing.T) {
config := &ClientConfig{
Cmd: helperProcess("start-timeout"),
Reattach: &ReattachConfig{},
}
c := NewClient(config)
defer c.Kill()
_, err := c.Start()
if err == nil {
t.Fatal("err should not be nil")
}
}
func TestClient_reattach(t *testing.T) {
process := helperProcess("test-interface")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer c.Kill()
// Grab the RPC client
_, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Get the reattach configuration
reattach := c.ReattachConfig()
// Create a new client
c = NewClient(&ClientConfig{
Reattach: reattach,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
result := impl.Double(21)
if result != 42 {
t.Fatalf("bad: %#v", result)
}
// Kill it
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
}
func TestClient_reattachNoProtocol(t *testing.T) {
process := helperProcess("test-interface")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer c.Kill()
// Grab the RPC client
_, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Get the reattach configuration
reattach := c.ReattachConfig()
reattach.Protocol = ""
// Create a new client
c = NewClient(&ClientConfig{
Reattach: reattach,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
result := impl.Double(21)
if result != 42 {
t.Fatalf("bad: %#v", result)
}
// Kill it
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
}
func TestClient_reattachGRPC(t *testing.T) {
process := helperProcess("test-grpc")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testGRPCPluginMap,
AllowedProtocols: []Protocol{ProtocolGRPC},
})
defer c.Kill()
// Grab the RPC client
_, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Get the reattach configuration
reattach := c.ReattachConfig()
// Create a new client
c = NewClient(&ClientConfig{
Reattach: reattach,
HandshakeConfig: testHandshake,
Plugins: testGRPCPluginMap,
AllowedProtocols: []Protocol{ProtocolGRPC},
})
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
result := impl.Double(21)
if result != 42 {
t.Fatalf("bad: %#v", result)
}
// Kill it
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
}
func TestClient_reattachNotFound(t *testing.T) {
// Find a bad pid
var pid int = 5000
for i := pid; i < 32000; i++ {
if _, err := os.FindProcess(i); err != nil {
pid = i
break
}
}
// Addr that won't work
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("err: %s", err)
}
addr := l.Addr()
l.Close()
// Reattach
c := NewClient(&ClientConfig{
Reattach: &ReattachConfig{
Addr: addr,
Pid: pid,
},
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
// Start shouldn't error
if _, err := c.Start(); err == nil {
t.Fatal("should error")
} else if err != ErrProcessNotFound {
t.Fatalf("err: %s", err)
}
}
func TestClientStart_badVersion(t *testing.T) {
config := &ClientConfig{
Cmd: helperProcess("bad-version"),
StartTimeout: 50 * time.Millisecond,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
}
c := NewClient(config)
defer c.Kill()
_, err := c.Start()
if err == nil {
t.Fatal("err should not be nil")
}
}
func TestClientStart_badNegotiatedVersion(t *testing.T) {
config := &ClientConfig{
Cmd: helperProcess("test-versioned-plugins"),
StartTimeout: 50 * time.Millisecond,
// test-versioned-plugins only has version 2
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
}
c := NewClient(config)
defer c.Kill()
_, err := c.Start()
if err == nil {
t.Fatal("err should not be nil")
}
fmt.Println(err)
}
func TestClient_Start_Timeout(t *testing.T) {
config := &ClientConfig{
Cmd: helperProcess("start-timeout"),
StartTimeout: 50 * time.Millisecond,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
}
c := NewClient(config)
defer c.Kill()
_, err := c.Start()
if err == nil {
t.Fatal("err should not be nil")
}
}
func TestClient_Stderr(t *testing.T) {
stderr := new(bytes.Buffer)
process := helperProcess("stderr")
c := NewClient(&ClientConfig{
Cmd: process,
Stderr: stderr,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
for !c.Exited() {
time.Sleep(10 * time.Millisecond)
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
if !strings.Contains(stderr.String(), "HELLO\n") {
t.Fatalf("bad log data: '%s'", stderr.String())
}
if !strings.Contains(stderr.String(), "WORLD\n") {
t.Fatalf("bad log data: '%s'", stderr.String())
}
}
func TestClient_StderrJSON(t *testing.T) {
stderr := new(bytes.Buffer)
process := helperProcess("stderr-json")
var logBuf bytes.Buffer
mutex := new(sync.Mutex)
// Custom hclog.Logger
testLogger := hclog.New(&hclog.LoggerOptions{
Name: "test-logger",
Level: hclog.Trace,
Output: &logBuf,
Mutex: mutex,
})
c := NewClient(&ClientConfig{
Cmd: process,
Stderr: stderr,
HandshakeConfig: testHandshake,
Logger: testLogger,
Plugins: testPluginMap,
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
for !c.Exited() {
time.Sleep(10 * time.Millisecond)
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
logOut := logBuf.String()
if !strings.Contains(logOut, "[\"HELLO\"]\n") {
t.Fatalf("missing json list: '%s'", logOut)
}
if !strings.Contains(logOut, "12345\n") {
t.Fatalf("missing line with raw number: '%s'", logOut)
}
if !strings.Contains(logOut, "{\"a\":1}") {
t.Fatalf("missing json object: '%s'", logOut)
}
}
func TestClient_textLogLevel(t *testing.T) {
stderr := new(bytes.Buffer)
process := helperProcess("level-warn-text")
var logBuf bytes.Buffer
mutex := new(sync.Mutex)
// Custom hclog.Logger
testLogger := hclog.New(&hclog.LoggerOptions{
Name: "test-logger",
Level: hclog.Warn,
Output: &logBuf,
Mutex: mutex,
})
c := NewClient(&ClientConfig{
Cmd: process,
Stderr: stderr,
HandshakeConfig: testHandshake,
Logger: testLogger,
Plugins: testPluginMap,
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
for !c.Exited() {
time.Sleep(10 * time.Millisecond)
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
logOut := logBuf.String()
if !strings.Contains(logOut, "test line 98765") {
log.Fatalf("test string not found in log: %q\n", logOut)
}
}
func TestClient_Stdin(t *testing.T) {
// Overwrite stdin for this test with a temporary file
tf, err := ioutil.TempFile("", "terraform")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(tf.Name())
defer tf.Close()
if _, err = tf.WriteString("hello"); err != nil {
t.Fatalf("error: %s", err)
}
if err = tf.Sync(); err != nil {
t.Fatalf("error: %s", err)
}
if _, err = tf.Seek(0, 0); err != nil {
t.Fatalf("error: %s", err)
}
oldStdin := os.Stdin
defer func() { os.Stdin = oldStdin }()
os.Stdin = tf
process := helperProcess("stdin")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer c.Kill()
_, err = c.Start()
if err != nil {
t.Fatalf("error: %s", err)
}
for {
if c.Exited() {
break
}
time.Sleep(50 * time.Millisecond)
}
if !process.ProcessState.Success() {
t.Fatal("process didn't exit cleanly")
}
}
func TestClient_SecureConfig(t *testing.T) {
// Test failure case
secureConfig := &SecureConfig{
Checksum: []byte{'1'},
Hash: sha256.New(),
}
process := helperProcess("test-interface")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
SecureConfig: secureConfig,
})
// Grab the RPC client, should error
_, err := c.Client()
c.Kill()
if err != ErrChecksumsDoNotMatch {
t.Fatalf("err should be %s, got %s", ErrChecksumsDoNotMatch, err)
}
// Get the checksum of the executable
file, err := os.Open(os.Args[0])
if err != nil {
t.Fatal(err)
}
defer file.Close()
hash := sha256.New()
_, err = io.Copy(hash, file)
if err != nil {
t.Fatal(err)
}
sum := hash.Sum(nil)
secureConfig = &SecureConfig{
Checksum: sum,
Hash: sha256.New(),
}
process = helperProcess("test-interface")
c = NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
SecureConfig: secureConfig,
})
defer c.Kill()
// Grab the RPC client
_, err = c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
}
func TestClient_TLS(t *testing.T) {
// Test failure case
process := helperProcess("test-interface-tls")
cBad := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer cBad.Kill()
// Grab the RPC client
clientBad, err := cBad.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := clientBad.Dispense("test")
if err == nil {
t.Fatal("expected error, got nil")
}
cBad.Kill()
// Add TLS config to client
tlsConfig, err := helperTLSProvider()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
process = helperProcess("test-interface-tls")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
TLSConfig: tlsConfig,
})
defer c.Kill()
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err = client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
result := impl.Double(21)
if result != 42 {
t.Fatalf("bad: %#v", result)
}
// Kill it
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
}
func TestClient_TLS_grpc(t *testing.T) {
// Add TLS config to client
tlsConfig, err := helperTLSProvider()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
process := helperProcess("test-grpc-tls")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testGRPCPluginMap,
TLSConfig: tlsConfig,
AllowedProtocols: []Protocol{ProtocolGRPC},
})
defer c.Kill()
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
result := impl.Double(21)
if result != 42 {
t.Fatalf("bad: %#v", result)
}
// Kill it
c.Kill()
if !c.Exited() {
t.Fatal("should say client has exited")
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
}
func TestClient_secureConfigAndReattach(t *testing.T) {
config := &ClientConfig{
SecureConfig: &SecureConfig{},
Reattach: &ReattachConfig{},
}
c := NewClient(config)
defer c.Kill()
_, err := c.Start()
if err != ErrSecureConfigAndReattach {
t.Fatalf("err should not be %s, got %s", ErrSecureConfigAndReattach, err)
}
}
func TestClient_ping(t *testing.T) {
process := helperProcess("test-interface")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testPluginMap,
})
defer c.Kill()
// Get the client
client, err := c.Client()
if err != nil {
t.Fatalf("err: %s", err)
}
// Ping, should work
if err := client.Ping(); err != nil {
t.Fatalf("err: %s", err)
}
// Kill it
c.Kill()
if err := client.Ping(); err == nil {
t.Fatal("should error")
}
}
func TestClient_wrongVersion(t *testing.T) {
process := helperProcess("test-proto-upgraded-plugin")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testGRPCPluginMap,
AllowedProtocols: []Protocol{ProtocolGRPC},
})
defer c.Kill()
// Get the client
_, err := c.Client()
if err == nil {
t.Fatal("expected incorrect protocol version server")
}
}
func TestClient_legacyClient(t *testing.T) {
process := helperProcess("test-proto-upgraded-plugin")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testVersionedHandshake,
VersionedPlugins: map[int]PluginSet{
1: testPluginMap,
},
})
defer c.Kill()
// Get the client
client, err := c.Client()
if err != nil {
t.Fatalf("err: %s", err)
}
if c.NegotiatedVersion() != 1 {
t.Fatal("using incorrect version", c.NegotiatedVersion())
}
// Ping, should work
if err := client.Ping(); err == nil {
t.Fatal("expected error, should negotiate wrong plugin")
}
}
func TestClient_legacyServer(t *testing.T) {
// test using versioned plugins version when the server supports only
// supports one
process := helperProcess("test-proto-upgraded-client")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testVersionedHandshake,
VersionedPlugins: map[int]PluginSet{
2: testGRPCPluginMap,
},
AllowedProtocols: []Protocol{ProtocolGRPC},
})
defer c.Kill()
// Get the client
client, err := c.Client()
if err != nil {
t.Fatalf("err: %s", err)
}
if c.NegotiatedVersion() != 2 {
t.Fatal("using incorrect version", c.NegotiatedVersion())
}
// Ping, should work
if err := client.Ping(); err == nil {
t.Fatal("expected error, should negotiate wrong plugin")
}
}
func TestClient_versionedClient(t *testing.T) {
process := helperProcess("test-versioned-plugins")
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testVersionedHandshake,
VersionedPlugins: map[int]PluginSet{
2: testGRPCPluginMap,
},
AllowedProtocols: []Protocol{ProtocolGRPC},
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
if v := c.Protocol(); v != ProtocolGRPC {
t.Fatalf("bad: %s", v)
}
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
if c.NegotiatedVersion() != 2 {
t.Fatal("using incorrect version", c.NegotiatedVersion())
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
_, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
c.process.Kill()
select {
case <-c.doneCtx.Done():
case <-time.After(time.Second * 2):
t.Fatal("Context was not closed")
}
}
func TestClient_mtlsClient(t *testing.T) {
process := helperProcess("test-mtls")
c := NewClient(&ClientConfig{
AutoMTLS: true,
Cmd: process,
HandshakeConfig: testVersionedHandshake,
VersionedPlugins: map[int]PluginSet{
2: testGRPCPluginMap,
},
AllowedProtocols: []Protocol{ProtocolGRPC},
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
if v := c.Protocol(); v != ProtocolGRPC {
t.Fatalf("bad: %s", v)
}
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
if c.NegotiatedVersion() != 2 {
t.Fatal("using incorrect version", c.NegotiatedVersion())
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
tester, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
n := tester.Double(3)
if n != 6 {
t.Fatal("invalid response", n)
}
c.process.Kill()
select {
case <-c.doneCtx.Done():
case <-time.After(time.Second * 2):
t.Fatal("Context was not closed")
}
}
func TestClient_mtlsNetRPCClient(t *testing.T) {
process := helperProcess("test-interface-mtls")
c := NewClient(&ClientConfig{
AutoMTLS: true,
Cmd: process,
HandshakeConfig: testVersionedHandshake,
Plugins: testPluginMap,
AllowedProtocols: []Protocol{ProtocolNetRPC},
})
defer c.Kill()
if _, err := c.Start(); err != nil {
t.Fatalf("err: %s", err)
}
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
tester, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
n := tester.Double(3)
if n != 6 {
t.Fatal("invalid response", n)
}
c.process.Kill()
select {
case <-c.doneCtx.Done():
case <-time.After(time.Second * 2):
t.Fatal("Context was not closed")
}
}
func TestClient_logger(t *testing.T) {
t.Run("net/rpc", func(t *testing.T) { testClient_logger(t, "netrpc") })
t.Run("grpc", func(t *testing.T) { testClient_logger(t, "grpc") })
}
func testClient_logger(t *testing.T, proto string) {
var buffer bytes.Buffer
mutex := new(sync.Mutex)
stderr := io.MultiWriter(os.Stderr, &buffer)
// Custom hclog.Logger
clientLogger := hclog.New(&hclog.LoggerOptions{
Name: "test-logger",
Level: hclog.Trace,
Output: stderr,
Mutex: mutex,
})
process := helperProcess("test-interface-logger-" + proto)
c := NewClient(&ClientConfig{
Cmd: process,
HandshakeConfig: testHandshake,
Plugins: testGRPCPluginMap,
Logger: clientLogger,
AllowedProtocols: []Protocol{ProtocolNetRPC, ProtocolGRPC},
})
defer c.Kill()
// Grab the RPC client
client, err := c.Client()
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
// Grab the impl
raw, err := client.Dispense("test")
if err != nil {
t.Fatalf("err should be nil, got %s", err)
}
impl, ok := raw.(testInterface)
if !ok {
t.Fatalf("bad: %#v", raw)
}
{
// Discard everything else, and capture the output we care about
mutex.Lock()
buffer.Reset()
mutex.Unlock()
impl.PrintKV("foo", "bar")
time.Sleep(100 * time.Millisecond)
mutex.Lock()
line, err := buffer.ReadString('\n')
mutex.Unlock()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(line, "foo=bar") {
t.Fatalf("bad: %q", line)
}
}
{
// Try an integer type
mutex.Lock()
buffer.Reset()
mutex.Unlock()
impl.PrintKV("foo", 12)
time.Sleep(100 * time.Millisecond)
mutex.Lock()
line, err := buffer.ReadString('\n')
mutex.Unlock()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(line, "foo=12") {
t.Fatalf("bad: %q", line)
}
}
// Kill it
c.Kill()
// Test that it knows it is exited
if !c.Exited() {
t.Fatal("should say client has exited")
}
if c.killed() {
t.Fatal("process failed to exit gracefully")
}
}
// Test that we continue to consume stderr over long lines.
func TestClient_logStderr(t *testing.T) {
orig := stdErrBufferSize
stdErrBufferSize = 32
defer func() {
stdErrBufferSize = orig
}()
stderr := bytes.Buffer{}
c := NewClient(&ClientConfig{
Stderr: &stderr,
Cmd: &exec.Cmd{
Path: "test",
},
})
c.clientWaitGroup.Add(1)
msg := `
this line is more than 32 bytes long
and this line is more than 32 bytes long
{"a": "b", "@level": "debug"}
this line is short
`
reader := strings.NewReader(msg)
c.stderrWaitGroup.Add(1)
c.logStderr(reader)
read := stderr.String()
if read != msg {
t.Fatalf("\nexpected output: %q\ngot output: %q", msg, read)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yllan/go-plugin.git
git@gitee.com:yllan/go-plugin.git
yllan
go-plugin
go-plugin
master

搜索帮助