-
Notifications
You must be signed in to change notification settings - Fork 43
/
client.go
77 lines (69 loc) 路 1.53 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package plugin
import (
"bufio"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"sync"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-plugin"
)
var (
runningClientsMx sync.Mutex
runningClients = make([]*plugin.Client, 0)
)
func KillAllPlugins() {
runningClientsMx.Lock()
defer runningClientsMx.Unlock()
for _, c := range runningClients {
c.Kill()
}
}
func StartPlugin(pluginInfo *Info) (interface{}, error) {
runningClientsMx.Lock()
defer runningClientsMx.Unlock()
logR, logW := io.Pipe()
pluginLogger := log.New(os.Stderr, fmt.Sprintf("[%s]: ", pluginInfo.ShortNormalizedName), 0)
go func() {
logLineScanner := bufio.NewScanner(logR)
for logLineScanner.Scan() {
line := logLineScanner.Text()
// skip JSON logging
if strings.HasPrefix(line, "{") {
continue
}
pluginLogger.Println(line)
}
}()
cmd := exec.Command(pluginInfo.BinPath)
cmd.SysProcAttr = GetSysProcAttr()
client := plugin.NewClient(&plugin.ClientConfig{
HandshakeConfig: Handshake,
VersionedPlugins: map[int]plugin.PluginSet{
1: {
pluginInfo.Type: &GRPCWrapper{
Type: pluginInfo.Type,
},
},
},
Cmd: cmd,
AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},
Logger: hclog.NewNullLogger(),
Stderr: logW,
})
rpcClient, err := client.Client()
if err != nil {
client.Kill()
return nil, err
}
raw, err := rpcClient.Dispense(pluginInfo.Type)
if err != nil {
client.Kill()
return nil, err
}
runningClients = append(runningClients, client)
return raw, nil
}