Debian Codegraph @

node.go

raw
1 package centrifuge
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "hash/fnv"
8 "os"
9 "sync"
10 "time"
11
12 "github.com/centrifugal/centrifuge/internal/controlpb"
13 "github.com/centrifugal/centrifuge/internal/controlproto"
14 "github.com/centrifugal/centrifuge/internal/dissolve"
15 "github.com/centrifugal/centrifuge/internal/nowtime"
16
17 "github.com/FZambia/eagle"
18 "github.com/centrifugal/protocol"
19 "github.com/google/uuid"
20 "github.com/prometheus/client_golang/prometheus"
21 )
22
23 // Node is a heart of Centrifuge library – it keeps and manages client connections,
24 // maintains information about other centrifuge nodes, keeps references to common
25 // things (like Broker and PresenceManager, Hub) etc.
26 // By default Node uses in-memory implementations of Broker and PresenceManager
27 // (see Node.SetBroker and Node.SetPresenceManager to set other implementations to use).
28 type Node struct {
29 mu sync.RWMutex
30 // unique id for this node.
31 uid string
32 // startedAt is unix time of node start.
33 startedAt int64
34 // config for node.
35 config Config
36 // hub to manage client connections.
37 hub *Hub
38 // broker is responsible for PUB/SUB and history streaming mechanics.
39 broker Broker
40 // presenceManager is responsible for presence information management.
41 presenceManager PresenceManager
42 // nodes contains registry of known nodes.
43 nodes *nodeRegistry
44 // shutdown is a flag which is only true when node is going to shut down.
45 shutdown bool
46 // shutdownCh is a channel which is closed when node shutdown initiated.
47 shutdownCh chan struct{}
48 // clientEvents to manage event handlers attached to node.
49 clientEvents *eventHub
50 // logger allows to log throughout library code and proxy log entries to
51 // configured log handler.
52 logger *logger
53 // cache control encoder in Node.
54 controlEncoder controlproto.Encoder
55 // cache control decoder in Node.
56 controlDecoder controlproto.Decoder
57 // subLocks synchronizes access to adding/removing subscriptions.
58 subLocks map[int]*sync.Mutex
59
60 metricsMu sync.Mutex
61 metricsExporter *eagle.Eagle
62 metricsSnapshot *eagle.Metrics
63
64 // subDissolver used to reliably clear unused subscriptions in Broker.
65 subDissolver *dissolve.Dissolver
66
67 // nowTimeGetter provides access to current time.
68 nowTimeGetter nowtime.Getter
69
70 surveyHandler SurveyHandler
71 surveyRegistry map[uint64]chan survey
72 surveyMu sync.RWMutex
73 surveyID uint64
74 }
75
76 const (
77 numSubLocks = 16384
78 numSubDissolverWorkers = 64
79 )
80
81 // New creates Node with provided Config.
82 func New(c Config) (*Node, error) {
83 uid := uuid.Must(uuid.NewRandom()).String()
84
85 subLocks := make(map[int]*sync.Mutex, numSubLocks)
86 for i := 0; i < numSubLocks; i++ {
87 subLocks[i] = &sync.Mutex{}
88 }
89
90 if c.Name == "" {
91 hostname, err := os.Hostname()
92 if err != nil {
93 return nil, err
94 }
95 c.Name = hostname
96 }
97
98 n := &Node{
99 uid: uid,
100 nodes: newNodeRegistry(uid),
101 config: c,
102 hub: newHub(),
103 startedAt: time.Now().Unix(),
104 shutdownCh: make(chan struct{}),
105 logger: nil,
106 controlEncoder: controlproto.NewProtobufEncoder(),
107 controlDecoder: controlproto.NewProtobufDecoder(),
108 clientEvents: &eventHub{},
109 subLocks: subLocks,
110 subDissolver: dissolve.New(numSubDissolverWorkers),
111 nowTimeGetter: nowtime.Get,
112 surveyRegistry: make(map[uint64]chan survey),
113 }
114
115 if c.LogHandler != nil {
116 n.logger = newLogger(c.LogLevel, c.LogHandler)
117 }
118
119 b, err := NewMemoryBroker(n, MemoryBrokerConfig{})
120 if err != nil {
121 return nil, err
122 }
123 n.SetBroker(b)
124
125 m, err := NewMemoryPresenceManager(n, MemoryPresenceManagerConfig{})
126 if err != nil {
127 return nil, err
128 }
129 n.SetPresenceManager(m)
130
131 if err := initMetricsRegistry(prometheus.DefaultRegisterer, c.MetricsNamespace); err != nil {
132 switch err.(type) {
133 case prometheus.AlreadyRegisteredError:
134 // Can happens when node initialized several times since we use DefaultRegisterer,
135 // skip for now.
136 default:
137 return nil, err
138 }
139 }
140
141 return n, nil
142 }
143
144 // index chooses bucket number in range [0, numBuckets).
145 func index(s string, numBuckets int) int {
146 if numBuckets == 1 {
147 return 0
148 }
149 hash := fnv.New64a()
150 _, _ = hash.Write([]byte(s))
151 return int(hash.Sum64() % uint64(numBuckets))
152 }
153
154 // ID returns unique Node identifier. This is a UUID v4 value.
155 func (n *Node) ID() string {
156 return n.uid
157 }
158
159 func (n *Node) subLock(ch string) *sync.Mutex {
160 return n.subLocks[index(ch, numSubLocks)]
161 }
162
163 // SetBroker allows to set Broker implementation to use.
164 func (n *Node) SetBroker(b Broker) {
165 n.broker = b
166 }
167
168 // SetPresenceManager allows to set PresenceManager to use.
169 func (n *Node) SetPresenceManager(m PresenceManager) {
170 n.presenceManager = m
171 }
172
173 // Hub returns node's Hub.
174 func (n *Node) Hub() *Hub {
175 return n.hub
176 }
177
178 // Run performs node startup actions. At moment must be called once on start
179 // after Broker set to Node.
180 func (n *Node) Run() error {
181 eventHandler := &brokerEventHandler{n}
182 if err := n.broker.Run(eventHandler); err != nil {
183 return err
184 }
185 err := n.initMetrics()
186 if err != nil {
187 n.logger.log(newLogEntry(LogLevelError, "error on init metrics", map[string]interface{}{"error": err.Error()}))
188 return err
189 }
190 err = n.pubNode("")
191 if err != nil {
192 n.logger.log(newLogEntry(LogLevelError, "error publishing node control command", map[string]interface{}{"error": err.Error()}))
193 return err
194 }
195 go n.sendNodePing()
196 go n.cleanNodeInfo()
197 go n.updateMetrics()
198 return n.subDissolver.Run()
199 }
200
201 // Log allows to log entry.
202 func (n *Node) Log(entry LogEntry) {
203 n.logger.log(entry)
204 }
205
206 // LogEnabled allows to log entry.
207 func (n *Node) LogEnabled(level LogLevel) bool {
208 return n.logger.enabled(level)
209 }
210
211 // Shutdown sets shutdown flag to Node so handlers could stop accepting
212 // new requests and disconnects clients with shutdown reason.
213 func (n *Node) Shutdown(ctx context.Context) error {
214 n.mu.Lock()
215 if n.shutdown {
216 n.mu.Unlock()
217 return nil
218 }
219 n.shutdown = true
220 close(n.shutdownCh)
221 n.mu.Unlock()
222 cmd := &controlpb.Command{
223 UID: n.uid,
224 Method: controlpb.MethodTypeShutdown,
225 }
226 _ = n.publishControl(cmd, "")
227 if closer, ok := n.broker.(Closer); ok {
228 defer func() { _ = closer.Close(ctx) }()
229 }
230 if n.presenceManager != nil {
231 if closer, ok := n.presenceManager.(Closer); ok {
232 defer func() { _ = closer.Close(ctx) }()
233 }
234 }
235 var wg sync.WaitGroup
236 wg.Add(2)
237 go func() {
238 defer wg.Done()
239 _ = n.subDissolver.Close()
240 }()
241 go func() {
242 defer wg.Done()
243 _ = n.hub.shutdown(ctx)
244 }()
245 wg.Wait()
246 return ctx.Err()
247 }
248
249 // NotifyShutdown returns a channel which will be closed on node shutdown.
250 func (n *Node) NotifyShutdown() chan struct{} {
251 return n.shutdownCh
252 }
253
254 func (n *Node) updateGauges() {
255 setNumClients(float64(n.hub.NumClients()))
256 setNumUsers(float64(n.hub.NumUsers()))
257 setNumChannels(float64(n.hub.NumChannels()))
258 setNumNodes(float64(len(n.nodes.list())))
259 version := n.config.Version
260 if version == "" {
261 version = "_"
262 }
263 setBuildInfo(version)
264 }
265
266 func (n *Node) updateMetrics() {
267 n.updateGauges()
268 for {
269 select {
270 case <-n.shutdownCh:
271 return
272 case <-time.After(10 * time.Second):
273 n.updateGauges()
274 }
275 }
276 }
277
278 // Centrifuge library uses Prometheus metrics for instrumentation. But we also try to
279 // aggregate Prometheus metrics periodically and share this information between Nodes.
280 func (n *Node) initMetrics() error {
281 if n.config.NodeInfoMetricsAggregateInterval == 0 {
282 return nil
283 }
284 metricsSink := make(chan eagle.Metrics)
285 n.metricsExporter = eagle.New(eagle.Config{
286 Gatherer: prometheus.DefaultGatherer,
287 Interval: n.config.NodeInfoMetricsAggregateInterval,
288 Sink: metricsSink,
289 })
290 metrics, err := n.metricsExporter.Export()
291 if err != nil {
292 return err
293 }
294 n.metricsMu.Lock()
295 n.metricsSnapshot = &metrics
296 n.metricsMu.Unlock()
297 go func() {
298 for {
299 select {
300 case <-n.NotifyShutdown():
301 return
302 case metrics := <-metricsSink:
303 n.metricsMu.Lock()
304 n.metricsSnapshot = &metrics
305 n.metricsMu.Unlock()
306 }
307 }
308 }()
309 return nil
310 }
311
312 func (n *Node) sendNodePing() {
313 for {
314 select {
315 case <-n.shutdownCh:
316 return
317 case <-time.After(nodeInfoPublishInterval):
318 err := n.pubNode("")
319 if err != nil {
320 n.logger.log(newLogEntry(LogLevelError, "error publishing node control command", map[string]interface{}{"error": err.Error()}))
321 }
322 }
323 }
324 }
325
326 func (n *Node) cleanNodeInfo() {
327 for {
328 select {
329 case <-n.shutdownCh:
330 return
331 case <-time.After(nodeInfoCleanInterval):
332 n.mu.RLock()
333 delay := nodeInfoMaxDelay
334 n.mu.RUnlock()
335 n.nodes.clean(delay)
336 }
337 }
338 }
339
340 func (n *Node) handleSurveyRequest(fromNodeID string, req *controlpb.SurveyRequest) error {
341 if n.surveyHandler == nil {
342 return nil
343 }
344 cb := func(reply SurveyReply) {
345 surveyResponse := &controlpb.SurveyResponse{
346 ID: req.ID,
347 Code: reply.Code,
348 Data: reply.Data,
349 }
350 params, _ := n.controlEncoder.EncodeSurveyResponse(surveyResponse)
351
352 cmd := &controlpb.Command{
353 UID: n.uid,
354 Method: controlpb.MethodTypeSurveyResponse,
355 Params: params,
356 }
357 _ = n.publishControl(cmd, fromNodeID)
358 }
359 n.surveyHandler(SurveyEvent{Op: req.Op, Data: req.Data}, cb)
360 return nil
361 }
362
363 func (n *Node) handleSurveyResponse(uid string, resp *controlpb.SurveyResponse) error {
364 n.surveyMu.RLock()
365 defer n.surveyMu.RUnlock()
366 if ch, ok := n.surveyRegistry[resp.ID]; ok {
367 select {
368 case ch <- survey{
369 UID: uid,
370 Result: SurveyResult{
371 Code: resp.Code,
372 Data: resp.Data,
373 },
374 }:
375 default:
376 // Survey channel allocated with capacity enough to receive all survey replies,
377 // default case here means that channel has no reader anymore, so it's safe to
378 // skip message. This extra survey reply can come from extra node that just
379 // joined.
380 }
381 }
382 return nil
383 }
384
385 // SurveyResult from node.
386 type SurveyResult struct {
387 Code uint32
388 Data []byte
389 }
390
391 type survey struct {
392 UID string
393 Result SurveyResult
394 }
395
396 var errSurveyHandlerNotRegistered = errors.New("no survey handler registered")
397
398 const defaultSurveyTimeout = 10 * time.Second
399
400 // Survey allows collecting data from all running Centrifuge nodes. This method publishes
401 // control messages, then waits for replies from all running nodes. The maximum time to wait
402 // can be controlled over context timeout. If provided context does not have a deadline for
403 // survey then this method uses default 10 seconds timeout. Keep in mind that Survey does not
404 // scale very well as number of Centrifuge Node grows. Though it has reasonably good performance
405 // to perform rare tasks even with relatively large number of nodes.
406 func (n *Node) Survey(ctx context.Context, op string, data []byte) (map[string]SurveyResult, error) {
407 if n.surveyHandler == nil {
408 return nil, errSurveyHandlerNotRegistered
409 }
410
411 incActionCount("survey")
412
413 if _, ok := ctx.Deadline(); !ok {
414 // If no timeout provided then fallback to defaultSurveyTimeout to avoid endless surveys.
415 var cancel context.CancelFunc
416 ctx, cancel = context.WithTimeout(ctx, defaultSurveyTimeout)
417 defer cancel()
418 }
419
420 numNodes := len(n.nodes.list())
421
422 n.surveyMu.Lock()
423 n.surveyID++
424 surveyRequest := &controlpb.SurveyRequest{
425 ID: n.surveyID,
426 Op: op,
427 Data: data,
428 }
429 params, err := n.controlEncoder.EncodeSurveyRequest(surveyRequest)
430 if err != nil {
431 n.surveyMu.Unlock()
432 return nil, err
433 }
434 surveyChan := make(chan survey, numNodes)
435 n.surveyRegistry[surveyRequest.ID] = surveyChan
436 n.surveyMu.Unlock()
437
438 defer func() {
439 n.surveyMu.Lock()
440 defer n.surveyMu.Unlock()
441 delete(n.surveyRegistry, surveyRequest.ID)
442 }()
443
444 results := map[string]SurveyResult{}
445
446 n.surveyHandler(SurveyEvent{Op: op, Data: data}, func(reply SurveyReply) {
447 surveyChan <- survey{
448 UID: n.uid,
449 Result: SurveyResult(reply),
450 }
451 })
452
453 var wg sync.WaitGroup
454 wg.Add(1)
455
456 go func() {
457 defer wg.Done()
458 for {
459 select {
460 case resp := <-surveyChan:
461 results[resp.UID] = resp.Result
462 if len(results) == numNodes {
463 return
464 }
465 case <-ctx.Done():
466 return
467 }
468 }
469 }()
470
471 cmd := &controlpb.Command{
472 UID: n.uid,
473 Method: controlpb.MethodTypeSurveyRequest,
474 Params: params,
475 }
476 err = n.publishControl(cmd, "")
477 if err != nil {
478 return nil, err
479 }
480
481 wg.Wait()
482 return results, ctx.Err()
483 }
484
485 // Info contains information about all known server nodes.
486 type Info struct {
487 Nodes []NodeInfo
488 }
489
490 // Metrics aggregation over time interval for node.
491 type Metrics struct {
492 Interval float64
493 Items map[string]float64
494 }
495
496 // NodeInfo contains information about node.
497 type NodeInfo struct {
498 UID string
499 Name string
500 Version string
501 NumClients uint32
502 NumUsers uint32
503 NumChannels uint32
504 Uptime uint32
505 Metrics *Metrics
506 }
507
508 // Info returns aggregated stats from all nodes.
509 func (n *Node) Info() (Info, error) {
510 nodes := n.nodes.list()
511 nodeResults := make([]NodeInfo, len(nodes))
512 for i, nd := range nodes {
513 info := NodeInfo{
514 UID: nd.UID,
515 Name: nd.Name,
516 Version: nd.Version,
517 NumClients: nd.NumClients,
518 NumUsers: nd.NumUsers,
519 NumChannels: nd.NumChannels,
520 Uptime: nd.Uptime,
521 }
522 if nd.Metrics != nil {
523 info.Metrics = &Metrics{
524 Interval: nd.Metrics.Interval,
525 Items: nd.Metrics.Items,
526 }
527 }
528 nodeResults[i] = info
529 }
530
531 return Info{
532 Nodes: nodeResults,
533 }, nil
534 }
535
536 // handleControl handles messages from control channel - control messages used for internal
537 // communication between nodes to share state or proto.
538 func (n *Node) handleControl(data []byte) error {
539 incMessagesReceived("control")
540
541 cmd, err := n.controlDecoder.DecodeCommand(data)
542 if err != nil {
543 n.logger.log(newLogEntry(LogLevelError, "error decoding control command", map[string]interface{}{"error": err.Error()}))
544 return err
545 }
546
547 if cmd.UID == n.uid {
548 // Sent by this node.
549 return nil
550 }
551
552 uid := cmd.UID
553 method := cmd.Method
554 params := cmd.Params
555
556 switch method {
557 case controlpb.MethodTypeNode:
558 cmd, err := n.controlDecoder.DecodeNode(params)
559 if err != nil {
560 n.logger.log(newLogEntry(LogLevelError, "error decoding node control params", map[string]interface{}{"error": err.Error()}))
561 return err
562 }
563 return n.nodeCmd(cmd)
564 case controlpb.MethodTypeShutdown:
565 return n.shutdownCmd(uid)
566 case controlpb.MethodTypeUnsubscribe:
567 cmd, err := n.controlDecoder.DecodeUnsubscribe(params)
568 if err != nil {
569 n.logger.log(newLogEntry(LogLevelError, "error decoding unsubscribe control params", map[string]interface{}{"error": err.Error()}))
570 return err
571 }
572 return n.hub.unsubscribe(cmd.User, cmd.Channel)
573 case controlpb.MethodTypeDisconnect:
574 cmd, err := n.controlDecoder.DecodeDisconnect(params)
575 if err != nil {
576 n.logger.log(newLogEntry(LogLevelError, "error decoding disconnect control params", map[string]interface{}{"error": err.Error()}))
577 return err
578 }
579 return n.hub.disconnect(cmd.User, &Disconnect{Code: cmd.Code, Reason: cmd.Reason, Reconnect: cmd.Reconnect}, cmd.Whitelist)
580 case controlpb.MethodTypeSurveyRequest:
581 cmd, err := n.controlDecoder.DecodeSurveyRequest(params)
582 if err != nil {
583 n.logger.log(newLogEntry(LogLevelError, "error decoding survey request control params", map[string]interface{}{"error": err.Error()}))
584 return err
585 }
586 return n.handleSurveyRequest(uid, cmd)
587 case controlpb.MethodTypeSurveyResponse:
588 cmd, err := n.controlDecoder.DecodeSurveyResponse(params)
589 if err != nil {
590 n.logger.log(newLogEntry(LogLevelError, "error decoding survey response control params", map[string]interface{}{"error": err.Error()}))
591 return err
592 }
593 return n.handleSurveyResponse(uid, cmd)
594 default:
595 n.logger.log(newLogEntry(LogLevelError, "unknown control message method", map[string]interface{}{"method": method}))
596 return fmt.Errorf("control method not found: %d", method)
597 }
598 }
599
600 // handlePublication handles messages published into channel and
601 // coming from Broker. The goal of method is to deliver this message
602 // to all clients on this node currently subscribed to channel.
603 func (n *Node) handlePublication(ch string, pub *protocol.Publication, sp StreamPosition) error {
604 incMessagesReceived("publication")
605 numSubscribers := n.hub.NumSubscribers(ch)
606 hasCurrentSubscribers := numSubscribers > 0
607 if !hasCurrentSubscribers {
608 return nil
609 }
610 return n.hub.broadcastPublication(ch, pub, sp)
611 }
612
613 // handleJoin handles join messages - i.e. broadcasts it to
614 // interested local clients subscribed to channel.
615 func (n *Node) handleJoin(ch string, join *protocol.Join) error {
616 incMessagesReceived("join")
617 hasCurrentSubscribers := n.hub.NumSubscribers(ch) > 0
618 if !hasCurrentSubscribers {
619 return nil
620 }
621 return n.hub.broadcastJoin(ch, join)
622 }
623
624 // handleLeave handles leave messages - i.e. broadcasts it to
625 // interested local clients subscribed to channel.
626 func (n *Node) handleLeave(ch string, leave *protocol.Leave) error {
627 incMessagesReceived("leave")
628 hasCurrentSubscribers := n.hub.NumSubscribers(ch) > 0
629 if !hasCurrentSubscribers {
630 return nil
631 }
632 return n.hub.broadcastLeave(ch, leave)
633 }
634
635 func (n *Node) publish(ch string, data []byte, opts ...PublishOption) (PublishResult, error) {
636 pubOpts := &PublishOptions{}
637 for _, opt := range opts {
638 opt(pubOpts)
639 }
640 incMessagesSent("publication")
641 streamPos, err := n.broker.Publish(ch, data, *pubOpts)
642 if err != nil {
643 return PublishResult{}, err
644 }
645 return PublishResult{StreamPosition: streamPos}, nil
646 }
647
648 // PublishResult returned from Publish operation.
649 type PublishResult struct {
650 StreamPosition
651 }
652
653 // Publish sends data to all clients subscribed on channel at this moment. All running
654 // nodes will receive Publication and send it to all local channel subscribers.
655 //
656 // Data expected to be valid marshaled JSON or any binary payload.
657 // Connections that work over JSON protocol can not handle binary payloads.
658 // Connections that work over Protobuf protocol can work both with JSON and binary payloads.
659 //
660 // So the rule here: if you have channel subscribers that work using JSON
661 // protocol then you can not publish binary data to these channel.
662 //
663 // Channels in Centrifuge are ephemeral and its settings not persisted over different
664 // publish operations. So if you want to have channel with history stream behind you
665 // need to provide WithHistory option on every publish. To simplify working with different
666 // channels you can make some type of publish wrapper in your own code.
667 //
668 // The returned PublishResult contains embedded StreamPosition that describes
669 // position inside stream Publication was added too. For channels without history
670 // enabled (i.e. when Publications only sent to PUB/SUB system) StreamPosition will
671 // be an empty struct (i.e. PublishResult.Offset will be zero).
672 func (n *Node) Publish(channel string, data []byte, opts ...PublishOption) (PublishResult, error) {
673 return n.publish(channel, data, opts...)
674 }
675
676 // publishJoin allows to publish join message into channel when someone subscribes on it
677 // or leave message when someone unsubscribes from channel.
678 func (n *Node) publishJoin(ch string, info *ClientInfo) error {
679 incMessagesSent("join")
680 return n.broker.PublishJoin(ch, info)
681 }
682
683 // publishLeave allows to publish join message into channel when someone subscribes on it
684 // or leave message when someone unsubscribes from channel.
685 func (n *Node) publishLeave(ch string, info *ClientInfo) error {
686 incMessagesSent("leave")
687 return n.broker.PublishLeave(ch, info)
688 }
689
690 // publishControl publishes message into control channel so all running
691 // nodes will receive and handle it.
692 func (n *Node) publishControl(cmd *controlpb.Command, nodeID string) error {
693 incMessagesSent("control")
694 data, err := n.controlEncoder.EncodeCommand(cmd)
695 if err != nil {
696 return err
697 }
698 return n.broker.PublishControl(data, nodeID)
699 }
700
701 func (n *Node) getMetrics(metrics eagle.Metrics) *controlpb.Metrics {
702 return &controlpb.Metrics{
703 Interval: n.config.NodeInfoMetricsAggregateInterval.Seconds(),
704 Items: metrics.Flatten("."),
705 }
706 }
707
708 // pubNode sends control message to all nodes - this message
709 // contains information about current node.
710 func (n *Node) pubNode(nodeID string) error {
711 n.mu.RLock()
712 node := &controlpb.Node{
713 UID: n.uid,
714 Name: n.config.Name,
715 Version: n.config.Version,
716 NumClients: uint32(n.hub.NumClients()),
717 NumUsers: uint32(n.hub.NumUsers()),
718 NumChannels: uint32(n.hub.NumChannels()),
719 Uptime: uint32(time.Now().Unix() - n.startedAt),
720 }
721
722 n.metricsMu.Lock()
723 if n.metricsSnapshot != nil {
724 node.Metrics = n.getMetrics(*n.metricsSnapshot)
725 }
726 // We only send metrics once when updated.
727 n.metricsSnapshot = nil
728 n.metricsMu.Unlock()
729
730 n.mu.RUnlock()
731
732 params, _ := n.controlEncoder.EncodeNode(node)
733
734 cmd := &controlpb.Command{
735 UID: n.uid,
736 Method: controlpb.MethodTypeNode,
737 Params: params,
738 }
739
740 err := n.nodeCmd(node)
741 if err != nil {
742 n.logger.log(newLogEntry(LogLevelError, "error handling node command", map[string]interface{}{"error": err.Error()}))
743 }
744
745 return n.publishControl(cmd, nodeID)
746 }
747
748 // pubUnsubscribe publishes unsubscribe control message to all nodes – so all
749 // nodes could unsubscribe user from channel.
750 func (n *Node) pubUnsubscribe(user string, ch string) error {
751 unsubscribe := &controlpb.Unsubscribe{
752 User: user,
753 Channel: ch,
754 }
755 params, _ := n.controlEncoder.EncodeUnsubscribe(unsubscribe)
756 cmd := &controlpb.Command{
757 UID: n.uid,
758 Method: controlpb.MethodTypeUnsubscribe,
759 Params: params,
760 }
761 return n.publishControl(cmd, "")
762 }
763
764 // pubDisconnect publishes disconnect control message to all nodes – so all
765 // nodes could disconnect user from server.
766 func (n *Node) pubDisconnect(user string, disconnect *Disconnect, whitelist []string) error {
767 protoDisconnect := &controlpb.Disconnect{
768 User: user,
769 Whitelist: whitelist,
770 Code: disconnect.Code,
771 Reason: disconnect.Reason,
772 Reconnect: disconnect.Reconnect,
773 }
774 params, _ := n.controlEncoder.EncodeDisconnect(protoDisconnect)
775 cmd := &controlpb.Command{
776 UID: n.uid,
777 Method: controlpb.MethodTypeDisconnect,
778 Params: params,
779 }
780 return n.publishControl(cmd, "")
781 }
782
783 // addClient registers authenticated connection in clientConnectionHub
784 // this allows to make operations with user connection on demand.
785 func (n *Node) addClient(c *Client) error {
786 incActionCount("add_client")
787 return n.hub.add(c)
788 }
789
790 // removeClient removes client connection from connection registry.
791 func (n *Node) removeClient(c *Client) error {
792 incActionCount("remove_client")
793 return n.hub.remove(c)
794 }
795
796 // addSubscription registers subscription of connection on channel in both
797 // Hub and Broker.
798 func (n *Node) addSubscription(ch string, c *Client) error {
799 incActionCount("add_subscription")
800 mu := n.subLock(ch)
801 mu.Lock()
802 defer mu.Unlock()
803 first, err := n.hub.addSub(ch, c)
804 if err != nil {
805 return err
806 }
807 if first {
808 err := n.broker.Subscribe(ch)
809 if err != nil {
810 _, _ = n.hub.removeSub(ch, c)
811 return err
812 }
813 }
814 return nil
815 }
816
817 // removeSubscription removes subscription of connection on channel
818 // from Hub and Broker.
819 func (n *Node) removeSubscription(ch string, c *Client) error {
820 incActionCount("remove_subscription")
821 mu := n.subLock(ch)
822 mu.Lock()
823 defer mu.Unlock()
824 empty, err := n.hub.removeSub(ch, c)
825 if err != nil {
826 return err
827 }
828 if empty {
829 submittedAt := time.Now()
830 _ = n.subDissolver.Submit(func() error {
831 timeSpent := time.Since(submittedAt)
832 if timeSpent < time.Second {
833 time.Sleep(time.Second - timeSpent)
834 }
835 mu := n.subLock(ch)
836 mu.Lock()
837 defer mu.Unlock()
838 empty := n.hub.NumSubscribers(ch) == 0
839 if empty {
840 return n.broker.Unsubscribe(ch)
841 }
842 return nil
843 })
844 }
845 return nil
846 }
847
848 // nodeCmd handles node control command i.e. updates information about known nodes.
849 func (n *Node) nodeCmd(node *controlpb.Node) error {
850 isNewNode := n.nodes.add(node)
851 if isNewNode && node.UID != n.uid {
852 // New Node in cluster
853 _ = n.pubNode(node.UID)
854 }
855 return nil
856 }
857
858 // shutdownCmd handles shutdown control command sent when node leaves cluster.
859 func (n *Node) shutdownCmd(nodeID string) error {
860 n.nodes.remove(nodeID)
861 return nil
862 }
863
864 // Unsubscribe unsubscribes user from channel, if channel is equal to empty
865 // string then user will be unsubscribed from all channels.
866 func (n *Node) Unsubscribe(user string, ch string, opts ...UnsubscribeOption) error {
867 unsubscribeOpts := &UnsubscribeOptions{}
868 for _, opt := range opts {
869 opt(unsubscribeOpts)
870 }
871 // First unsubscribe on this node.
872 err := n.hub.unsubscribe(user, ch, opts...)
873 if err != nil {
874 return err
875 }
876 // Second send unsubscribe control message to other nodes.
877 return n.pubUnsubscribe(user, ch)
878 }
879
880 // Disconnect allows to close all user connections through all nodes.
881 func (n *Node) Disconnect(user string, opts ...DisconnectOption) error {
882 disconnectOpts := &DisconnectOptions{}
883 for _, opt := range opts {
884 opt(disconnectOpts)
885 }
886 // first disconnect user from this node
887 customDisconnect := disconnectOpts.Disconnect
888 if customDisconnect == nil {
889 customDisconnect = DisconnectForceNoReconnect
890 }
891
892 err := n.hub.disconnect(user, customDisconnect, disconnectOpts.ClientWhitelist)
893 if err != nil {
894 return err
895 }
896 // second send disconnect control message to other nodes
897 return n.pubDisconnect(user, customDisconnect, disconnectOpts.ClientWhitelist)
898 }
899
900 // addPresence proxies presence adding to PresenceManager.
901 func (n *Node) addPresence(ch string, uid string, info *ClientInfo) error {
902 if n.presenceManager == nil {
903 return nil
904 }
905 incActionCount("add_presence")
906 return n.presenceManager.AddPresence(ch, uid, info)
907 }
908
909 // removePresence proxies presence removing to PresenceManager.
910 func (n *Node) removePresence(ch string, uid string) error {
911 if n.presenceManager == nil {
912 return nil
913 }
914 incActionCount("remove_presence")
915 return n.presenceManager.RemovePresence(ch, uid)
916 }
917
918 // PresenceResult wraps presence.
919 type PresenceResult struct {
920 Presence map[string]*ClientInfo
921 }
922
923 // Presence returns a map with information about active clients in channel.
924 func (n *Node) Presence(ch string) (PresenceResult, error) {
925 if n.presenceManager == nil {
926 return PresenceResult{}, ErrorNotAvailable
927 }
928 incActionCount("presence")
929 presence, err := n.presenceManager.Presence(ch)
930 if err != nil {
931 return PresenceResult{}, err
932 }
933 return PresenceResult{Presence: presence}, nil
934 }
935
936 func infoFromProto(v *protocol.ClientInfo) *ClientInfo {
937 if v == nil {
938 return nil
939 }
940 info := &ClientInfo{
941 ClientID: v.GetClient(),
942 UserID: v.GetUser(),
943 }
944 if len(v.ConnInfo) > 0 {
945 info.ConnInfo = v.ConnInfo
946 }
947 if len(v.ChanInfo) > 0 {
948 info.ChanInfo = v.ChanInfo
949 }
950 return info
951 }
952
953 func infoToProto(v *ClientInfo) *protocol.ClientInfo {
954 if v == nil {
955 return nil
956 }
957 info := &protocol.ClientInfo{
958 Client: v.ClientID,
959 User: v.UserID,
960 }
961 if len(v.ConnInfo) > 0 {
962 info.ConnInfo = v.ConnInfo
963 }
964 if len(v.ChanInfo) > 0 {
965 info.ChanInfo = v.ChanInfo
966 }
967 return info
968 }
969
970 func pubToProto(pub *Publication) *protocol.Publication {
971 if pub == nil {
972 return nil
973 }
974 return &protocol.Publication{
975 Offset: pub.Offset,
976 Data: pub.Data,
977 Info: infoToProto(pub.Info),
978 }
979 }
980
981 func pubFromProto(pub *protocol.Publication) *Publication {
982 if pub == nil {
983 return nil
984 }
985 return &Publication{
986 Offset: pub.GetOffset(),
987 Data: pub.Data,
988 Info: infoFromProto(pub.GetInfo()),
989 }
990 }
991
992 // PresenceStatsResult wraps presence stats.
993 type PresenceStatsResult struct {
994 PresenceStats
995 }
996
997 // PresenceStats returns presence stats from PresenceManager.
998 func (n *Node) PresenceStats(ch string) (PresenceStatsResult, error) {
999 if n.presenceManager == nil {
1000 return PresenceStatsResult{}, ErrorNotAvailable
1001 }
1002 incActionCount("presence_stats")
1003 presenceStats, err := n.presenceManager.PresenceStats(ch)
1004 if err != nil {
1005 return PresenceStatsResult{}, err
1006 }
1007 return PresenceStatsResult{PresenceStats: presenceStats}, nil
1008 }
1009
1010 // HistoryResult contains Publications and current stream top StreamPosition.
1011 type HistoryResult struct {
1012 // StreamPosition embedded here describes current stream top offset and epoch.
1013 StreamPosition
1014 // Publications extracted from history storage according to HistoryFilter.
1015 Publications []*Publication
1016 }
1017
1018 // History allows to extract Publications in channel.
1019 // The channel must belong to namespace where history is on.
1020 func (n *Node) History(ch string, opts ...HistoryOption) (HistoryResult, error) {
1021 incActionCount("history")
1022 historyOpts := &HistoryOptions{}
1023 for _, opt := range opts {
1024 opt(historyOpts)
1025 }
1026 pubs, streamTop, err := n.broker.History(ch, HistoryFilter{
1027 Limit: historyOpts.Limit,
1028 Since: historyOpts.Since,
1029 })
1030 if err != nil {
1031 return HistoryResult{}, err
1032 }
1033 return HistoryResult{
1034 StreamPosition: streamTop,
1035 Publications: pubs,
1036 }, nil
1037 }
1038
1039 // recoverHistory recovers publications since StreamPosition last seen by client.
1040 func (n *Node) recoverHistory(ch string, since StreamPosition) (HistoryResult, error) {
1041 incActionCount("history_recover")
1042 limit := NoLimit
1043 maxPublicationLimit := n.config.RecoveryMaxPublicationLimit
1044 if maxPublicationLimit > 0 {
1045 limit = maxPublicationLimit
1046 }
1047 return n.History(ch, WithLimit(limit), Since(&since))
1048 }
1049
1050 // streamTop returns current stream top StreamPosition for a channel.
1051 func (n *Node) streamTop(ch string) (StreamPosition, error) {
1052 incActionCount("history_stream_top")
1053 historyResult, err := n.History(ch)
1054 if err != nil {
1055 return StreamPosition{}, err
1056 }
1057 return historyResult.StreamPosition, nil
1058 }
1059
1060 // RemoveHistory removes channel history.
1061 func (n *Node) RemoveHistory(ch string) error {
1062 incActionCount("history_remove")
1063 return n.broker.RemoveHistory(ch)
1064 }
1065
1066 type nodeRegistry struct {
1067 // mu allows to synchronize access to node registry.
1068 mu sync.RWMutex
1069 // currentUID keeps uid of current node
1070 currentUID string
1071 // nodes is a map with information about known nodes.
1072 nodes map[string]controlpb.Node
1073 // updates track time we last received ping from node. Used to clean up nodes map.
1074 updates map[string]int64
1075 }
1076
1077 func newNodeRegistry(currentUID string) *nodeRegistry {
1078 return &nodeRegistry{
1079 currentUID: currentUID,
1080 nodes: make(map[string]controlpb.Node),
1081 updates: make(map[string]int64),
1082 }
1083 }
1084
1085 func (r *nodeRegistry) list() []controlpb.Node {
1086 r.mu.RLock()
1087 nodes := make([]controlpb.Node, len(r.nodes))
1088 i := 0
1089 for _, info := range r.nodes {
1090 nodes[i] = info
1091 i++
1092 }
1093 r.mu.RUnlock()
1094 return nodes
1095 }
1096
1097 func (r *nodeRegistry) get(uid string) controlpb.Node {
1098 r.mu.RLock()
1099 info := r.nodes[uid]
1100 r.mu.RUnlock()
1101 return info
1102 }
1103
1104 func (r *nodeRegistry) add(info *controlpb.Node) bool {
1105 var isNewNode bool
1106 r.mu.Lock()
1107 if node, ok := r.nodes[info.UID]; ok {
1108 if info.Metrics != nil {
1109 r.nodes[info.UID] = *info
1110 } else {
1111 node.Version = info.Version
1112 node.NumChannels = info.NumChannels
1113 node.NumClients = info.NumClients
1114 node.NumUsers = info.NumUsers
1115 node.Uptime = info.Uptime
1116 r.nodes[info.UID] = node
1117 }
1118 } else {
1119 r.nodes[info.UID] = *info
1120 isNewNode = true
1121 }
1122 r.updates[info.UID] = time.Now().Unix()
1123 r.mu.Unlock()
1124 return isNewNode
1125 }
1126
1127 func (r *nodeRegistry) remove(uid string) {
1128 r.mu.Lock()
1129 delete(r.nodes, uid)
1130 delete(r.updates, uid)
1131 r.mu.Unlock()
1132 }
1133
1134 func (r *nodeRegistry) clean(delay time.Duration) {
1135 r.mu.Lock()
1136 for uid := range r.nodes {
1137 if uid == r.currentUID {
1138 // No need to clean info for current node.
1139 continue
1140 }
1141 updated, ok := r.updates[uid]
1142 if !ok {
1143 // As we do all operations with nodes under lock this should never happen.
1144 delete(r.nodes, uid)
1145 continue
1146 }
1147 if time.Now().Unix()-updated > int64(delay.Seconds()) {
1148 // Too many seconds since this node have been last seen - remove it from map.
1149 delete(r.nodes, uid)
1150 delete(r.updates, uid)
1151 }
1152 }
1153 r.mu.Unlock()
1154 }
1155
1156 // OnSurvey allows to set SurveyHandler. This should be done before Node.Run called.
1157 func (n *Node) OnSurvey(handler SurveyHandler) {
1158 n.surveyHandler = handler
1159 }
1160
1161 // eventHub allows binding client event handlers.
1162 // All eventHub methods are not goroutine-safe and supposed
1163 // to be called once before Node Run called.
1164 type eventHub struct {
1165 connectingHandler ConnectingHandler
1166 connectHandler ConnectHandler
1167 }
1168
1169 // OnConnecting allows setting ConnectingHandler.
1170 // ConnectingHandler will be called when client sends Connect command to server.
1171 // In this handler server can reject connection or provide Credentials for it.
1172 func (n *Node) OnConnecting(handler ConnectingHandler) {
1173 n.clientEvents.connectingHandler = handler
1174 }
1175
1176 // OnConnect allows setting ConnectHandler.
1177 // ConnectHandler called after client connection successfully established,
1178 // authenticated and Connect Reply already sent to client. This is a place where
1179 // application can start communicating with client.
1180 func (n *Node) OnConnect(handler ConnectHandler) {
1181 n.clientEvents.connectHandler = handler
1182 }
1183
1184 type brokerEventHandler struct {
1185 node *Node
1186 }
1187
1188 // HandlePublication coming from Broker.
1189 func (h *brokerEventHandler) HandlePublication(ch string, pub *Publication, sp StreamPosition) error {
1190 if pub == nil {
1191 panic("nil Publication received, this should never happen")
1192 }
1193 return h.node.handlePublication(ch, pubToProto(pub), sp)
1194 }
1195
1196 // HandleJoin coming from Broker.
1197 func (h *brokerEventHandler) HandleJoin(ch string, info *ClientInfo) error {
1198 if info == nil {
1199 panic("nil join info received, this should never happen")
1200 }
1201 return h.node.handleJoin(ch, &protocol.Join{Info: *infoToProto(info)})
1202 }
1203
1204 // HandleLeave coming from Broker.
1205 func (h *brokerEventHandler) HandleLeave(ch string, info *ClientInfo) error {
1206 if info == nil {
1207 panic("nil leave info received, this should never happen")
1208 }
1209 return h.node.handleLeave(ch, &protocol.Leave{Info: *infoToProto(info)})
1210 }
1211
1212 // HandleControl coming from Broker.
1213 func (h *brokerEventHandler) HandleControl(data []byte) error {
1214 return h.node.handleControl(data)
1215 }