-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugin.go
298 lines (248 loc) · 6.08 KB
/
plugin.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package tcp
import (
"bytes"
"context"
"net"
"sync"
"github.com/google/uuid"
"github.com/roadrunner-server/errors"
"github.com/roadrunner-server/goridge/v3/pkg/frame"
"github.com/roadrunner-server/pool/payload"
"github.com/roadrunner-server/pool/pool"
staticPool "github.com/roadrunner-server/pool/pool/static_pool"
"github.com/roadrunner-server/pool/state/process"
"github.com/roadrunner-server/pool/worker"
"github.com/roadrunner-server/tcp/v5/handler"
"github.com/roadrunner-server/tcplisten"
"go.uber.org/zap"
)
const (
pluginName string = "tcp"
RrMode string = "RR_MODE"
)
type Pool interface {
// Workers return a worker list associated with the pool.
Workers() (workers []*worker.Process)
// RemoveWorker removes worker from the pool.
RemoveWorker(ctx context.Context) error
// AddWorker adds worker to the pool.
AddWorker() error
// Exec payload
Exec(ctx context.Context, p *payload.Payload, stopCh chan struct{}) (chan *staticPool.PExec, error)
// Reset kills all workers inside the watcher and replaces with new
Reset(ctx context.Context) error
// Destroy all underlying stacks (but let them complete the task).
Destroy(ctx context.Context)
}
type Logger interface {
NamedLogger(name string) *zap.Logger
}
// Server creates workers for the application.
type Server interface {
NewPool(ctx context.Context, cfg *pool.Config, env map[string]string, _ *zap.Logger) (*staticPool.Pool, error)
}
type Configurer interface {
// UnmarshalKey takes a single key and unmarshal it into a Struct.
UnmarshalKey(name string, out any) error
// Has checks if a config section exists.
Has(name string) bool
}
type Plugin struct {
mu sync.RWMutex
cfg *Config
log *zap.Logger
server Server
connections sync.Map // uuid -> conn
wPool Pool
listeners sync.Map // server -> listener
resBufPool sync.Pool
readBufPool sync.Pool
servInfoPool sync.Pool
pldPool sync.Pool
}
func (p *Plugin) Init(log Logger, cfg Configurer, server Server) error {
const op = errors.Op("tcp_plugin_init")
if !cfg.Has(pluginName) {
return errors.E(op, errors.Disabled)
}
err := cfg.UnmarshalKey(pluginName, &p.cfg)
if err != nil {
return errors.E(op, err)
}
err = p.cfg.InitDefault()
if err != nil {
return err
}
// buffer sent to the user
p.resBufPool = sync.Pool{
New: func() interface{} {
buf := new(bytes.Buffer)
buf.Grow(p.cfg.ReadBufferSize)
return buf
},
}
// cyclic buffer to read the data from the connection
p.readBufPool = sync.Pool{
New: func() interface{} {
buf := make([]byte, p.cfg.ReadBufferSize)
return &buf
},
}
p.servInfoPool = sync.Pool{
New: func() interface{} {
return new(handler.ServerInfo)
},
}
p.pldPool = sync.Pool{
New: func() interface{} {
return new(payload.Payload)
},
}
p.log = log.NamedLogger(pluginName)
p.server = server
return nil
}
func (p *Plugin) Serve() chan error {
errCh := make(chan error, 1)
var err error
p.wPool, err = p.server.NewPool(context.Background(), p.cfg.Pool, map[string]string{RrMode: pluginName}, nil)
if err != nil {
errCh <- err
return errCh
}
for k := range p.cfg.Servers {
go func(addr string, delim []byte, name string) {
// create a TCP listener
l, err := tcplisten.CreateListener(addr)
if err != nil {
errCh <- err
return
}
p.listeners.Store(uuid.NewString(), l)
for {
conn, errA := l.Accept()
if errA != nil {
p.log.Warn("failed to accept the connection", zap.Error(errA))
// just stop
return
}
go func() {
h := handler.NewHandler(conn, delim, name, p.Exec, &p.pldPool, &p.servInfoPool, &p.readBufPool, &p.resBufPool, &p.connections, p.log)
h.Start()
// release resources
h.Release()
}()
}
}(p.cfg.Servers[k].Addr, p.cfg.Servers[k].delimBytes, k)
}
return errCh
}
func (p *Plugin) Stop(ctx context.Context) error {
doneCh := make(chan struct{}, 1)
go func() {
// close all connections
p.mu.Lock()
defer p.mu.Unlock()
p.connections.Range(func(_, value interface{}) bool {
conn := value.(net.Conn)
if conn != nil {
_ = conn.Close()
}
return true
})
// then close all listeners
p.listeners.Range(func(_, value interface{}) bool {
_ = value.(net.Listener).Close()
return true
})
if p.wPool != nil {
switch pp := p.wPool.(type) {
case *staticPool.Pool:
if pp != nil {
pp.Destroy(ctx)
}
default:
// pool is nil, nothing to do
}
}
doneCh <- struct{}{}
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-doneCh:
return nil
}
}
func (p *Plugin) Reset() error {
p.mu.Lock()
defer p.mu.Unlock()
const op = errors.Op("tcp_reset")
p.log.Info("reset signal was received")
err := p.wPool.Reset(context.Background())
if err != nil {
return errors.E(op, err)
}
p.log.Info("plugin was successfully reset")
return nil
}
func (p *Plugin) Workers() []*process.State {
p.mu.RLock()
wrk := p.wPool.Workers()
p.mu.RUnlock()
ps := make([]*process.State, len(wrk))
for i := 0; i < len(wrk); i++ {
st, err := process.WorkerProcessState(wrk[i])
if err != nil {
p.log.Error("jobs workers state", zap.Error(err))
return nil
}
ps[i] = st
}
return ps
}
func (p *Plugin) Name() string {
return pluginName
}
func (p *Plugin) Close(uuid string) error {
if c, ok := p.connections.LoadAndDelete(uuid); ok {
conn := c.(net.Conn)
if conn != nil {
return conn.Close()
}
}
return nil
}
func (p *Plugin) RPC() any {
return &rpc{
p: p,
}
}
func (p *Plugin) Exec(epld *payload.Payload) (*payload.Payload, error) {
p.mu.RLock()
result, err := p.wPool.Exec(context.Background(), epld, nil)
if err != nil {
p.mu.RUnlock()
return nil, err
}
var r *payload.Payload
select {
case pld := <-result:
if pld.Error() != nil {
p.mu.RUnlock()
return nil, pld.Error()
}
// streaming is not supported
if pld.Payload().Flags&frame.STREAM != 0 {
p.mu.RUnlock()
return nil, errors.Str("streaming is not supported")
}
// assign the payload
r = pld.Payload()
default:
p.mu.RUnlock()
return nil, errors.Str("activity worker empty response")
}
p.mu.RUnlock()
return r, nil
}