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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
|
package websockets
import (
"context"
"net/http"
"sync"
"time"
"github.com/fasthttp/websocket"
"github.com/google/uuid"
json "github.com/json-iterator/go"
"github.com/spiral/errors"
"github.com/spiral/roadrunner/v2/common/pubsub"
"github.com/spiral/roadrunner/v2/pkg/payload"
phpPool "github.com/spiral/roadrunner/v2/pkg/pool"
"github.com/spiral/roadrunner/v2/pkg/state/process"
"github.com/spiral/roadrunner/v2/pkg/worker"
"github.com/spiral/roadrunner/v2/plugins/broadcast"
"github.com/spiral/roadrunner/v2/plugins/config"
"github.com/spiral/roadrunner/v2/plugins/http/attributes"
"github.com/spiral/roadrunner/v2/plugins/logger"
"github.com/spiral/roadrunner/v2/plugins/server"
"github.com/spiral/roadrunner/v2/plugins/websockets/connection"
"github.com/spiral/roadrunner/v2/plugins/websockets/executor"
"github.com/spiral/roadrunner/v2/plugins/websockets/pool"
"github.com/spiral/roadrunner/v2/plugins/websockets/validator"
)
const (
PluginName string = "websockets"
RrMode string = "RR_MODE"
RrBroadcastPath string = "RR_BROADCAST_PATH"
)
type Plugin struct {
sync.RWMutex
// subscriber+reader interfaces
subReader pubsub.SubReader
// broadcaster
broadcaster broadcast.Broadcaster
cfg *Config
log logger.Logger
// global connections map
connections sync.Map
// GO workers pool
workersPool *pool.WorkersPool
wsUpgrade *websocket.Upgrader
serveExit chan struct{}
// workers pool
phpPool phpPool.Pool
// server which produces commands to the pool
server server.Server
// stop receiving messages
cancel context.CancelFunc
ctx context.Context
// function used to validate access to the requested resource
accessValidator validator.AccessValidatorFn
}
func (p *Plugin) Init(cfg config.Configurer, log logger.Logger, server server.Server, b broadcast.Broadcaster) error {
const op = errors.Op("websockets_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 errors.E(op, err)
}
p.wsUpgrade = &websocket.Upgrader{
HandshakeTimeout: time.Second * 60,
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return isOriginAllowed(r.Header.Get("Origin"), p.cfg)
},
}
p.serveExit = make(chan struct{})
p.server = server
p.log = log
p.broadcaster = b
ctx, cancel := context.WithCancel(context.Background())
p.ctx = ctx
p.cancel = cancel
return nil
}
func (p *Plugin) Serve() chan error {
const op = errors.Op("websockets_plugin_serve")
errCh := make(chan error, 1)
// init broadcaster
var err error
p.subReader, err = p.broadcaster.GetDriver(p.cfg.Broker)
if err != nil {
errCh <- errors.E(op, err)
return errCh
}
go func() {
var err error
p.Lock()
defer p.Unlock()
p.phpPool, err = p.server.NewWorkerPool(context.Background(), &phpPool.Config{
Debug: p.cfg.Pool.Debug,
NumWorkers: p.cfg.Pool.NumWorkers,
MaxJobs: p.cfg.Pool.MaxJobs,
AllocateTimeout: p.cfg.Pool.AllocateTimeout,
DestroyTimeout: p.cfg.Pool.DestroyTimeout,
Supervisor: p.cfg.Pool.Supervisor,
}, map[string]string{RrMode: "http", RrBroadcastPath: p.cfg.Path})
if err != nil {
errCh <- errors.E(op, err)
return
}
p.accessValidator = p.defaultAccessValidator(p.phpPool)
}()
p.workersPool = pool.NewWorkersPool(p.subReader, &p.connections, p.log)
// we need here only Reader part of the interface
go func(ps pubsub.Reader) {
for {
data, err := ps.Next(p.ctx)
if err != nil {
if errors.Is(errors.TimeOut, err) {
return
}
errCh <- errors.E(op, err)
return
}
p.workersPool.Queue(data)
}
}(p.subReader)
return errCh
}
func (p *Plugin) Stop() error {
// close workers pool
p.workersPool.Stop()
// cancel context
p.cancel()
p.Lock()
if p.phpPool == nil {
p.Unlock()
return nil
}
p.phpPool.Destroy(context.Background())
p.Unlock()
return nil
}
func (p *Plugin) Available() {}
func (p *Plugin) Name() string {
return PluginName
}
func (p *Plugin) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != p.cfg.Path {
next.ServeHTTP(w, r)
return
}
// we need to lock here, because accessValidator might not be set in the Serve func at the moment
p.RLock()
// before we hijacked connection, we still can write to the response headers
val, err := p.accessValidator(r)
p.RUnlock()
if err != nil {
p.log.Error("access validation")
w.WriteHeader(400)
return
}
if val.Status != http.StatusOK {
for k, v := range val.Header {
for i := 0; i < len(v); i++ {
w.Header().Add(k, v[i])
}
}
w.WriteHeader(val.Status)
_, _ = w.Write(val.Body)
return
}
// upgrade connection to websocket connection
_conn, err := p.wsUpgrade.Upgrade(w, r, nil)
if err != nil {
// connection hijacked, do not use response.writer or request
p.log.Error("upgrade connection", "error", err)
return
}
// construct safe connection protected by mutexes
safeConn := connection.NewConnection(_conn, p.log)
// generate UUID from the connection
connectionID := uuid.NewString()
// store connection
p.connections.Store(connectionID, safeConn)
// Executor wraps a connection to have a safe abstraction
e := executor.NewExecutor(safeConn, p.log, connectionID, p.subReader, p.accessValidator, r)
p.log.Info("websocket client connected", "uuid", connectionID)
err = e.StartCommandLoop()
if err != nil {
p.log.Error("command loop error, disconnecting", "error", err.Error())
return
}
// when exiting - delete the connection
p.connections.Delete(connectionID)
// remove connection from all topics from all pub-sub drivers
e.CleanUp()
err = r.Body.Close()
if err != nil {
p.log.Error("body close", "error", err)
}
// close the connection on exit
err = safeConn.Close()
if err != nil {
p.log.Error("connection close", "error", err)
}
safeConn = nil
p.log.Info("disconnected", "connectionID", connectionID)
})
}
// Workers returns slice with the process states for the workers
func (p *Plugin) Workers() []*process.State {
p.RLock()
defer p.RUnlock()
workers := p.workers()
ps := make([]*process.State, 0, len(workers))
for i := 0; i < len(workers); i++ {
state, err := process.WorkerProcessState(workers[i])
if err != nil {
return nil
}
ps = append(ps, state)
}
return ps
}
// internal
func (p *Plugin) workers() []worker.BaseProcess {
return p.phpPool.Workers()
}
// Reset destroys the old pool and replaces it with new one, waiting for old pool to die
func (p *Plugin) Reset() error {
p.Lock()
defer p.Unlock()
const op = errors.Op("ws_plugin_reset")
p.log.Info("WS plugin got restart request. Restarting...")
p.phpPool.Destroy(context.Background())
p.phpPool = nil
var err error
p.phpPool, err = p.server.NewWorkerPool(context.Background(), &phpPool.Config{
Debug: p.cfg.Pool.Debug,
NumWorkers: p.cfg.Pool.NumWorkers,
MaxJobs: p.cfg.Pool.MaxJobs,
AllocateTimeout: p.cfg.Pool.AllocateTimeout,
DestroyTimeout: p.cfg.Pool.DestroyTimeout,
Supervisor: p.cfg.Pool.Supervisor,
}, map[string]string{RrMode: "http", RrBroadcastPath: p.cfg.Path})
if err != nil {
return errors.E(op, err)
}
// attach validators
p.accessValidator = p.defaultAccessValidator(p.phpPool)
p.log.Info("WS plugin successfully restarted")
return nil
}
func (p *Plugin) defaultAccessValidator(pool phpPool.Pool) validator.AccessValidatorFn {
return func(r *http.Request, topics ...string) (*validator.AccessValidator, error) {
const op = errors.Op("access_validator")
p.log.Debug("validation", "topics", topics)
r = attributes.Init(r)
// if channels len is eq to 0, we use serverValidator
if len(topics) == 0 {
ctx, err := validator.ServerAccessValidator(r)
if err != nil {
return nil, errors.E(op, err)
}
val, err := exec(ctx, pool)
if err != nil {
return nil, errors.E(err)
}
return val, nil
}
ctx, err := validator.TopicsAccessValidator(r, topics...)
if err != nil {
return nil, errors.E(op, err)
}
val, err := exec(ctx, pool)
if err != nil {
return nil, errors.E(op)
}
if val.Status != http.StatusOK {
return val, errors.E(op, errors.Errorf("access forbidden, code: %d", val.Status))
}
return val, nil
}
}
func exec(ctx []byte, pool phpPool.Pool) (*validator.AccessValidator, error) {
const op = errors.Op("exec")
pd := &payload.Payload{
Context: ctx,
}
resp, err := pool.Exec(pd)
if err != nil {
return nil, errors.E(op, err)
}
val := &validator.AccessValidator{
Body: resp.Body,
}
err = json.Unmarshal(resp.Context, val)
if err != nil {
return nil, errors.E(op, err)
}
return val, nil
}
|