-
Notifications
You must be signed in to change notification settings - Fork 0
/
commander.go
96 lines (82 loc) · 1.9 KB
/
commander.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
package commander
//go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg commander -path App,Commander
import (
"context"
"net"
"sync"
"google.golang.org/grpc"
"v2ray.com/core"
"v2ray.com/core/common"
"v2ray.com/core/common/signal"
)
type Commander struct {
sync.Mutex
server *grpc.Server
config Config
v *core.Instance
ohm core.OutboundHandlerManager
}
func NewCommander(ctx context.Context, config *Config) (*Commander, error) {
v := core.MustFromContext(ctx)
c := &Commander{
config: *config,
ohm: v.OutboundHandlerManager(),
v: v,
}
if err := v.RegisterFeature((*Commander)(nil), c); err != nil {
return nil, err
}
return c, nil
}
func (c *Commander) Type() interface{} {
return (*Commander)(nil)
}
func (c *Commander) Start() error {
c.Lock()
c.server = grpc.NewServer()
for _, rawConfig := range c.config.Service {
config, err := rawConfig.GetInstance()
if err != nil {
return err
}
rawService, err := c.v.CreateObject(config)
if err != nil {
return err
}
service, ok := rawService.(Service)
if !ok {
return newError("not a Service.")
}
service.Register(c.server)
}
c.Unlock()
listener := &OutboundListener{
buffer: make(chan net.Conn, 4),
done: signal.NewDone(),
}
go func() {
if err := c.server.Serve(listener); err != nil {
newError("failed to start grpc server").Base(err).AtError().WriteToLog()
}
}()
c.ohm.RemoveHandler(context.Background(), c.config.Tag)
c.ohm.AddHandler(context.Background(), &CommanderOutbound{
tag: c.config.Tag,
listener: listener,
})
return nil
}
func (c *Commander) Close() error {
c.Lock()
defer c.Unlock()
if c.server != nil {
c.server.Stop()
c.server = nil
}
return nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
return NewCommander(ctx, cfg.(*Config))
}))
}