This repository has been archived by the owner on Nov 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
105 lines (91 loc) · 2.21 KB
/
exec.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package plugin
import (
"fmt"
"github.com/iyear/go-plugin-grpc/internal/codec"
"github.com/iyear/go-plugin-grpc/internal/pb"
"google.golang.org/protobuf/proto"
)
func (p *Plugin) exec(data []byte) {
req := pb.CommunicateExecRequest{}
if err := proto.Unmarshal(data, &req); err != nil {
p.Log.Errorf("communicate exec req unmarshal error: %v", err)
return
}
defer p.recoverExec(&req)
resp, err := p.execFunc(&req)
if err != nil {
t := err.Error()
s := &t
resp = &pb.CommunicateExecResponse{
ID: req.ID,
Type: req.Type,
Result: nil,
Err: s,
}
}
msg, err := proto.Marshal(resp)
if err != nil {
p.Log.Errorf("communicate marshal exec response error: %v", err)
return
}
if err = p.clients.comm.Send(&pb.CommunicateMsg{
Type: pb.CommunicateType_ExecResponse,
Data: msg,
}); err != nil {
p.Log.Errorf("communicate send exec response error: %v", err)
return
}
}
func (p *Plugin) recoverExec(req *pb.CommunicateExecRequest) {
if r := recover(); r != nil {
p.Log.Errorf("exec func %s(%d) panic: %v", req.FuncName, req.ID, r)
p.opts.OnPanic(p, req.ID, req.FuncName, fmt.Errorf("%v", r))
// TODO refactor
t := fmt.Errorf("panic: %v", r).Error()
msg, err := proto.Marshal(&pb.CommunicateExecResponse{
ID: req.ID,
Type: req.Type,
Result: nil,
Err: &t,
})
if err != nil {
p.Log.Errorf("communicate marshal exec response error: %v", err)
return
}
if err = p.clients.comm.Send(&pb.CommunicateMsg{
Type: pb.CommunicateType_ExecResponse,
Data: msg,
}); err != nil {
p.Log.Errorf("communicate send exec response error: %v", err)
return
}
}
}
//exec 执行函数
func (p *Plugin) execFunc(req *pb.CommunicateExecRequest) (*pb.CommunicateExecResponse, error) {
f, ok := p.handlers[req.FuncName]
if !ok {
return nil, fmt.Errorf("func %s not found", req.FuncName)
}
union, err := codec.Decode(req.Payload, req.Type)
if err != nil {
return nil, err
}
result, err := f(&nativeCtx{
plugin: p,
Union: union,
})
if err != nil {
return nil, err
}
bytes, t, err := codec.Encode(result)
if err != nil {
return nil, err
}
return &pb.CommunicateExecResponse{
ID: req.ID,
Type: t,
Result: bytes,
Err: nil,
}, nil
}