forked from PlakarKorp/plakar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnect.go
More file actions
67 lines (57 loc) · 1.43 KB
/
connect.go
File metadata and controls
67 lines (57 loc) · 1.43 KB
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
package plugins
import (
"context"
"fmt"
"net"
"os"
"os/exec"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func connectPlugin(ctx context.Context, pluginPath string, args []string) (grpc.ClientConnInterface, error) {
conn, err := spawn(ctx, pluginPath, args)
if err != nil {
return nil, err
}
clientConn, err := grpc.NewClient("127.0.0.1:0",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) {
return conn, nil
}),
)
if err != nil {
return nil, fmt.Errorf("grpc client creation failed: %w", err)
}
return clientConn, nil
}
func spawn(ctx context.Context, pluginPath string, args []string) (net.Conn, error) {
cmd := exec.CommandContext(ctx, pluginPath, args...)
cmd.Stderr = os.Stderr
wr, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
rd, err := cmd.StdoutPipe()
if err != nil {
wr.Close()
return nil, err
}
stdin, ok := rd.(*os.File)
if !ok {
wr.Close()
rd.Close()
reason := "stdin is not a file"
return nil, fmt.Errorf("failed to spawn plugin: %s", reason)
}
stdout, ok := wr.(*os.File)
if !ok {
wr.Close()
rd.Close()
reason := "stdout is not a file"
return nil, fmt.Errorf("failed to spawn plugin: %s", reason)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start plugin: %w", err)
}
return NewStdioConn(stdin, stdout, cmd), nil
}