forked from centrifugal/centrifugo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1871 lines (1654 loc) · 61.3 KB
/
main.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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2015 Centrifugal
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
stdlog "log"
"net"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/centrifugal/centrifugo/v3/internal/admin"
"github.com/centrifugal/centrifugo/v3/internal/api"
"github.com/centrifugal/centrifugo/v3/internal/build"
"github.com/centrifugal/centrifugo/v3/internal/cli"
"github.com/centrifugal/centrifugo/v3/internal/client"
"github.com/centrifugal/centrifugo/v3/internal/health"
"github.com/centrifugal/centrifugo/v3/internal/jwtutils"
"github.com/centrifugal/centrifugo/v3/internal/jwtverify"
"github.com/centrifugal/centrifugo/v3/internal/logutils"
"github.com/centrifugal/centrifugo/v3/internal/metrics/graphite"
"github.com/centrifugal/centrifugo/v3/internal/middleware"
"github.com/centrifugal/centrifugo/v3/internal/natsbroker"
"github.com/centrifugal/centrifugo/v3/internal/origin"
"github.com/centrifugal/centrifugo/v3/internal/proxy"
"github.com/centrifugal/centrifugo/v3/internal/proxyproto"
"github.com/centrifugal/centrifugo/v3/internal/rule"
"github.com/centrifugal/centrifugo/v3/internal/survey"
"github.com/centrifugal/centrifugo/v3/internal/tntengine"
"github.com/centrifugal/centrifugo/v3/internal/tools"
"github.com/centrifugal/centrifugo/v3/internal/unigrpc"
"github.com/centrifugal/centrifugo/v3/internal/unihttpstream"
"github.com/centrifugal/centrifugo/v3/internal/unisse"
"github.com/centrifugal/centrifugo/v3/internal/uniws"
"github.com/centrifugal/centrifugo/v3/internal/webui"
"github.com/FZambia/viper-lite"
"github.com/centrifugal/centrifuge"
"github.com/mattn/go-isatty"
"github.com/mitchellh/mapstructure"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
)
func bindCentrifugoConfig() {
viper.SetEnvPrefix("centrifugo")
var defaults = map[string]interface{}{
"gomaxprocs": 0,
"name": "",
"engine": "memory",
"broker": "",
"token_hmac_secret_key": "",
"token_rsa_public_key": "",
"token_ecdsa_public_key": "",
"token_jwks_public_endpoint": "",
"protected": false,
"publish": false,
"subscribe_to_publish": false,
"anonymous": false,
"presence": false,
"presence_disable_for_client": false,
"history_size": 0,
"history_ttl": 0,
"history_disable_for_client": false,
"recover": false,
"position": false,
"proxy_subscribe": false,
"proxy_publish": false,
"node_info_metrics_aggregate_interval": 60 * time.Second,
"client_anonymous": false,
"client_expired_close_delay": 25 * time.Second,
"client_expired_sub_close_delay": 25 * time.Second,
"client_stale_close_delay": 25 * time.Second,
"client_channel_limit": 128,
"client_queue_max_size": 1048576, // 1 MB
"client_presence_update_interval": 25 * time.Second,
"client_user_connection_limit": 0,
"client_concurrency": 0,
"client_channel_position_check_delay": 40 * time.Second,
"channel_max_length": 255,
"channel_private_prefix": "$",
"channel_namespace_boundary": ":",
"channel_user_boundary": "#",
"channel_user_separator": ",",
"user_subscribe_to_personal": false,
"user_personal_channel_namespace": "",
"user_personal_single_connection": false,
"debug": false,
"prometheus": false,
"health": false,
"admin": false,
"admin_password": "",
"admin_secret": "",
"admin_insecure": false,
"admin_web_path": "",
"sockjs": false,
"sockjs_url": "https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js",
"sockjs_heartbeat_delay": 25 * time.Second,
"websocket_compression": false,
"websocket_compression_min_size": 0,
"websocket_compression_level": 1,
"websocket_read_buffer_size": 0,
"websocket_use_write_buffer_pool": false,
"websocket_write_buffer_size": 0,
"websocket_ping_interval": 25 * time.Second,
"websocket_write_timeout": time.Second,
"websocket_message_size_limit": 65536, // 64KB
"uni_websocket": false,
"uni_websocket_compression": false,
"uni_websocket_compression_min_size": 0,
"uni_websocket_compression_level": 1,
"uni_websocket_read_buffer_size": 0,
"uni_websocket_use_write_buffer_pool": false,
"uni_websocket_write_buffer_size": 0,
"uni_websocket_ping_interval": 25 * time.Second,
"uni_websocket_write_timeout": time.Second,
"uni_websocket_message_size_limit": 65536, // 64KB
"uni_http_stream_max_request_body_size": 65536, // 64KB
"uni_sse_max_request_body_size": 65536, // 64KB
"tls_autocert": false,
"tls_autocert_host_whitelist": "",
"tls_autocert_cache_dir": "",
"tls_autocert_email": "",
"tls_autocert_server_name": "",
"tls_autocert_http": false,
"tls_autocert_http_addr": ":80",
"redis_prefix": "centrifugo",
"redis_connect_timeout": time.Second,
"redis_read_timeout": 5 * time.Second,
"redis_write_timeout": time.Second,
"redis_idle_timeout": 0,
"history_meta_ttl": 0,
"presence_ttl": 60 * time.Second,
"grpc_api": false,
"grpc_api_address": "",
"grpc_api_port": 10000,
"shutdown_timeout": 30 * time.Second,
"shutdown_termination_delay": 0,
"graphite": false,
"graphite_host": "localhost",
"graphite_port": 2003,
"graphite_prefix": "centrifugo",
"graphite_interval": 10 * time.Second,
"graphite_tags": false,
"nats_prefix": "centrifugo",
"nats_url": "",
"nats_dial_timeout": time.Second,
"nats_write_timeout": time.Second,
"websocket_disable": false,
"api_disable": false,
"websocket_handler_prefix": "/connection/websocket",
"sockjs_handler_prefix": "/connection/sockjs",
"uni_websocket_handler_prefix": "/connection/uni_websocket",
"uni_sse_handler_prefix": "/connection/uni_sse",
"uni_http_stream_handler_prefix": "/connection/uni_http_stream",
"uni_grpc": false,
"uni_grpc_address": "",
"uni_grpc_port": 11000,
"uni_grpc_max_receive_message_size": 65536,
"admin_handler_prefix": "",
"api_handler_prefix": "/api",
"prometheus_handler_prefix": "/metrics",
"health_handler_prefix": "/health",
"proxy_connect_timeout": time.Second,
"proxy_rpc_timeout": time.Second,
"proxy_refresh_timeout": time.Second,
"proxy_subscribe_timeout": time.Second,
"proxy_publish_timeout": time.Second,
"client_history_max_publication_limit": 300,
"client_recovery_max_publication_limit": 300,
}
for k, v := range defaults {
viper.SetDefault(k, v)
}
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
viper.AutomaticEnv()
}
func main() {
var configFile string
var rootCmd = &cobra.Command{
Use: "",
Short: "Centrifugo",
Long: "Centrifugo – scalable real-time messaging server in language-agnostic way",
Run: func(cmd *cobra.Command, args []string) {
bindCentrifugoConfig()
bindPFlags := []string{
"engine", "log_level", "log_file", "pid_file", "debug", "name", "admin",
"admin_external", "client_insecure", "admin_insecure", "api_insecure",
"port", "address", "tls", "tls_cert", "tls_key", "tls_external", "internal_port",
"internal_address", "prometheus", "health", "redis_address", "tarantool_address",
"broker", "nats_url", "grpc_api", "grpc_api_tls", "grpc_api_tls_disable",
"grpc_api_tls_cert", "grpc_api_tls_key", "grpc_api_port", "sockjs", "uni_grpc",
"uni_grpc_port", "uni_websocket", "uni_sse", "uni_http_stream",
}
for _, flag := range bindPFlags {
_ = viper.BindPFlag(flag, cmd.Flags().Lookup(flag))
}
viper.SetConfigFile(configFile)
absConfPath, err := filepath.Abs(configFile)
if err != nil {
log.Fatal().Msgf("error retrieving config file absolute path: %v", err)
}
err = viper.ReadInConfig()
configFound := true
if err != nil {
switch err.(type) {
case viper.ConfigParseError:
log.Fatal().Msgf("error parsing configuration: %s\n", err)
default:
configFound = false
}
}
file := setupLogging()
if file != nil {
defer func() { _ = file.Close() }()
}
err = writePidFile(viper.GetString("pid_file"))
if err != nil {
log.Fatal().Msgf("error writing PID: %v", err)
}
if viper.IsSet("v3_use_offset") {
log.Fatal().Msg("v3_use_offset option is set which was removed in Centrifugo v3. " +
"Make sure to adapt your configuration file to fit Centrifugo v3 changes. Refer to the " +
"https://centrifugal.dev/docs/getting-started/migration_v3. If you had no intention to " +
"update Centrifugo to v3 then this error may be caused by using `latest` tag for " +
"Centrifugo Docker image in your deployment pipeline – pin to the specific Centrifugo " +
"image tag in this case (at least to centrifugo/centrifugo:v2).")
}
if os.Getenv("GOMAXPROCS") == "" {
if viper.IsSet("gomaxprocs") && viper.GetInt("gomaxprocs") > 0 {
runtime.GOMAXPROCS(viper.GetInt("gomaxprocs"))
} else {
runtime.GOMAXPROCS(runtime.NumCPU())
}
}
engineName := viper.GetString("engine")
log.Info().
Str("version", build.Version).
Str("runtime", runtime.Version()).
Int("pid", os.Getpid()).
Str("engine", strings.Title(engineName)).
Int("gomaxprocs", runtime.GOMAXPROCS(0)).Msg("starting Centrifugo")
log.Info().Str("path", absConfPath).Msg("using config file")
proxyConfig, _ := proxyConfig()
ruleConfig := ruleConfig()
err = ruleConfig.Validate()
if err != nil {
log.Fatal().Msgf("error validating config: %v", err)
}
ruleContainer := rule.NewContainer(ruleConfig)
nodeConfig := nodeConfig(build.Version)
node, err := centrifuge.New(nodeConfig)
if err != nil {
log.Fatal().Msgf("error creating Centrifuge Node: %v", err)
}
brokerName := viper.GetString("broker")
if brokerName != "" && brokerName != "nats" {
log.Fatal().Msgf("unknown broker: %s", brokerName)
}
var broker centrifuge.Broker
var presenceManager centrifuge.PresenceManager
if engineName == "memory" {
broker, presenceManager, err = memoryEngine(node)
} else if engineName == "redis" {
broker, presenceManager, err = redisEngine(node)
} else if engineName == "tarantool" {
broker, presenceManager, err = tarantoolEngine(node)
} else {
log.Fatal().Msgf("unknown engine: %s", engineName)
}
if err != nil {
log.Fatal().Msgf("error creating engine: %v", err)
}
tokenVerifier := jwtverify.NewTokenVerifierJWT(jwtVerifierConfig(), ruleContainer)
if viper.GetBool("use_unlimited_history_by_default") {
// See detailed comment about this by falling through to var definition.
client.UseUnlimitedHistoryByDefault = true
}
clientHandler := client.NewHandler(node, ruleContainer, tokenVerifier, proxyConfig)
err = clientHandler.Setup()
if err != nil {
log.Fatal().Msgf("error setting up client handler: %v", err)
}
surveyCaller := survey.NewCaller(node)
httpAPIExecutor := api.NewExecutor(node, ruleContainer, surveyCaller, "http")
grpcAPIExecutor := api.NewExecutor(node, ruleContainer, surveyCaller, "grpc")
node.SetBroker(broker)
node.SetPresenceManager(presenceManager)
var disableHistoryPresence bool
if engineName == "memory" && brokerName == "nats" {
// Presence and History won't work with Memory engine in distributed case.
disableHistoryPresence = true
node.SetPresenceManager(nil)
}
if disableHistoryPresence {
log.Warn().Msgf("presence, history and recovery disabled with Memory engine and Nats broker")
}
if !configFound {
log.Warn().Msg("config file not found")
}
if brokerName == "nats" {
broker, err := natsbroker.New(node, natsbroker.Config{
URL: viper.GetString("nats_url"),
Prefix: viper.GetString("nats_prefix"),
DialTimeout: GetDuration("nats_dial_timeout"),
WriteTimeout: GetDuration("nats_write_timeout"),
})
if err != nil {
log.Fatal().Msgf("Error creating broker: %v", err)
}
node.SetBroker(broker)
}
if err = node.Run(); err != nil {
log.Fatal().Msgf("error running node: %v", err)
}
if proxyConfig.ConnectEndpoint != "" {
log.Info().Str("endpoint", proxyConfig.ConnectEndpoint).Msg("connect proxy enabled")
}
if proxyConfig.RefreshEndpoint != "" {
log.Info().Str("endpoint", proxyConfig.RefreshEndpoint).Msg("refresh proxy enabled")
}
if proxyConfig.RPCEndpoint != "" {
log.Info().Str("endpoint", proxyConfig.RPCEndpoint).Msg("RPC proxy enabled")
}
if proxyConfig.SubscribeEndpoint != "" {
log.Info().Str("endpoint", proxyConfig.SubscribeEndpoint).Msg("subscribe proxy enabled")
}
if proxyConfig.PublishEndpoint != "" {
log.Info().Str("endpoint", proxyConfig.PublishEndpoint).Msg("publish proxy enabled")
}
if viper.GetBool("client_insecure") {
log.Warn().Msg("INSECURE client mode enabled, make sure you understand risks")
}
if viper.GetBool("api_insecure") {
log.Warn().Msg("INSECURE API mode enabled, make sure you understand risks")
}
if viper.GetBool("admin_insecure") {
log.Warn().Msg("INSECURE admin mode enabled, make sure you understand risks")
}
if viper.GetBool("debug") {
log.Warn().Msg("DEBUG mode enabled, see /debug/pprof")
}
var grpcAPIServer *grpc.Server
var grpcAPIAddr string
if viper.GetBool("grpc_api") {
grpcAPIAddr = net.JoinHostPort(viper.GetString("grpc_api_address"), viper.GetString("grpc_api_port"))
grpcAPIConn, err := net.Listen("tcp", grpcAPIAddr)
if err != nil {
log.Fatal().Msgf("cannot listen to address %s", grpcAPIAddr)
}
var grpcOpts []grpc.ServerOption
var tlsConfig *tls.Config
var tlsErr error
if viper.GetString("grpc_api_key") != "" {
grpcOpts = append(grpcOpts, api.GRPCKeyAuth(viper.GetString("grpc_api_key")))
}
if viper.GetBool("grpc_api_tls") {
tlsConfig, tlsErr = tlsConfigForGRPC()
} else if !viper.GetBool("grpc_api_tls_disable") {
tlsConfig, tlsErr = getTLSConfig()
}
if tlsErr != nil {
log.Fatal().Msgf("error getting TLS config: %v", tlsErr)
}
if tlsConfig != nil {
grpcOpts = append(grpcOpts, grpc.Creds(credentials.NewTLS(tlsConfig)))
}
grpcAPIServer = grpc.NewServer(grpcOpts...)
_ = api.RegisterGRPCServerAPI(node, grpcAPIExecutor, grpcAPIServer, api.GRPCAPIServiceConfig{})
go func() {
if err := grpcAPIServer.Serve(grpcAPIConn); err != nil {
log.Fatal().Msgf("serve GRPC API: %v", err)
}
}()
}
if grpcAPIServer != nil {
log.Info().Msgf("serving GRPC API service on %s", grpcAPIAddr)
}
var grpcUniServer *grpc.Server
var grpcUniAddr string
if viper.GetBool("uni_grpc") {
grpcUniAddr = net.JoinHostPort(viper.GetString("uni_grpc_address"), viper.GetString("uni_grpc_port"))
grpcUniConn, err := net.Listen("tcp", grpcUniAddr)
if err != nil {
log.Fatal().Msgf("cannot listen to address %s", grpcUniAddr)
}
var grpcOpts []grpc.ServerOption
//nolint:staticcheck
//goland:noinspection GoDeprecation
grpcOpts = append(grpcOpts, grpc.CustomCodec(&unigrpc.RawCodec{}), grpc.MaxRecvMsgSize(viper.GetInt("uni_grpc_max_receive_message_size")))
var tlsConfig *tls.Config
var tlsErr error
if viper.GetBool("uni_grpc_tls") {
tlsConfig, tlsErr = tlsConfigForUniGRPC()
} else if !viper.GetBool("uni_grpc_tls_disable") {
tlsConfig, tlsErr = getTLSConfig()
}
if tlsErr != nil {
log.Fatal().Msgf("error getting TLS config: %v", tlsErr)
}
if tlsConfig != nil {
grpcOpts = append(grpcOpts, grpc.Creds(credentials.NewTLS(tlsConfig)))
}
keepAliveEnforcementPolicy := keepalive.EnforcementPolicy{
MinTime: 5 * time.Second,
}
keepAliveServerParams := keepalive.ServerParameters{
Time: 25 * time.Second,
Timeout: 5 * time.Second,
}
grpcOpts = append(grpcOpts, grpc.KeepaliveEnforcementPolicy(keepAliveEnforcementPolicy))
grpcOpts = append(grpcOpts, grpc.KeepaliveParams(keepAliveServerParams))
grpcUniServer = grpc.NewServer(grpcOpts...)
_ = unigrpc.RegisterService(grpcUniServer, unigrpc.NewService(node, uniGRPCHandlerConfig()))
go func() {
if err := grpcUniServer.Serve(grpcUniConn); err != nil {
log.Fatal().Msgf("serve uni GRPC: %v", err)
}
}()
}
if grpcUniServer != nil {
log.Info().Msgf("serving unidirectional GRPC on %s", grpcUniAddr)
}
servers, err := runHTTPServers(node, httpAPIExecutor)
if err != nil {
log.Fatal().Msgf("error running HTTP server: %v", err)
}
var exporter *graphite.Exporter
if viper.GetBool("graphite") {
exporter = graphite.New(graphite.Config{
Address: net.JoinHostPort(viper.GetString("graphite_host"), strconv.Itoa(viper.GetInt("graphite_port"))),
Gatherer: prometheus.DefaultGatherer,
Prefix: strings.TrimSuffix(viper.GetString("graphite_prefix"), ".") + "." + graphite.PreparePathComponent(nodeConfig.Name),
Interval: GetDuration("graphite_interval"),
Tags: viper.GetBool("graphite_tags"),
})
}
handleSignals(configFile, node, ruleContainer, tokenVerifier, servers, grpcAPIServer, grpcUniServer, exporter)
},
}
rootCmd.Flags().StringVarP(&configFile, "config", "c", "config.json", "path to config file")
rootCmd.Flags().StringP("engine", "e", "memory", "engine to use: memory or redis")
rootCmd.Flags().StringP("broker", "", "", "custom broker to use: ex. nats")
rootCmd.Flags().StringP("log_level", "", "info", "set the log level: trace, debug, info, error, fatal or none")
rootCmd.Flags().StringP("log_file", "", "", "optional log file - if not specified logs go to STDOUT")
rootCmd.Flags().StringP("pid_file", "", "", "optional path to create PID file")
rootCmd.Flags().StringP("name", "n", "", "unique node name")
rootCmd.Flags().BoolP("debug", "", false, "enable debug endpoints")
rootCmd.Flags().BoolP("admin", "", false, "enable admin web interface")
rootCmd.Flags().BoolP("admin_external", "", false, "enable admin web interface on external port")
rootCmd.Flags().BoolP("prometheus", "", false, "enable Prometheus metrics endpoint")
rootCmd.Flags().BoolP("health", "", false, "enable health check endpoint")
rootCmd.Flags().BoolP("sockjs", "", false, "enable SockJS endpoint")
rootCmd.Flags().BoolP("uni_websocket", "", false, "enable unidirectional websocket endpoint")
rootCmd.Flags().BoolP("uni_sse", "", false, "enable unidirectional SSE (EventSource) endpoint")
rootCmd.Flags().BoolP("uni_http_stream", "", false, "enable unidirectional HTTP-streaming endpoint")
rootCmd.Flags().BoolP("client_insecure", "", false, "start in insecure client mode")
rootCmd.Flags().BoolP("api_insecure", "", false, "use insecure API mode")
rootCmd.Flags().BoolP("admin_insecure", "", false, "use insecure admin mode – no auth required for admin socket")
rootCmd.Flags().StringP("address", "a", "", "interface address to listen on")
rootCmd.Flags().StringP("port", "p", "8000", "port to bind HTTP server to")
rootCmd.Flags().StringP("internal_address", "", "", "custom interface address to listen on for internal endpoints")
rootCmd.Flags().StringP("internal_port", "", "", "custom port for internal endpoints")
rootCmd.Flags().BoolP("tls", "", false, "enable TLS, requires an X509 certificate and a key file")
rootCmd.Flags().StringP("tls_cert", "", "", "path to an X509 certificate file")
rootCmd.Flags().StringP("tls_key", "", "", "path to an X509 certificate key")
rootCmd.Flags().BoolP("tls_external", "", false, "enable TLS only for external endpoints")
rootCmd.Flags().BoolP("grpc_api", "", false, "enable GRPC API server")
rootCmd.Flags().IntP("grpc_api_port", "", 10000, "port to bind GRPC API server to")
rootCmd.Flags().BoolP("grpc_api_tls", "", false, "enable TLS for GRPC API server, requires an X509 certificate and a key file")
rootCmd.Flags().StringP("grpc_api_tls_cert", "", "", "path to an X509 certificate file for GRPC API server")
rootCmd.Flags().StringP("grpc_api_tls_key", "", "", "path to an X509 certificate key for GRPC API server")
rootCmd.Flags().BoolP("grpc_api_tls_disable", "", false, "disable general TLS for GRPC API server")
rootCmd.Flags().BoolP("uni_grpc", "", false, "enable unidirectional GRPC endpoint")
rootCmd.Flags().IntP("uni_grpc_port", "", 11000, "port to bind unidirectional GRPC server to")
rootCmd.Flags().StringP("redis_address", "", "redis://127.0.0.1:6379", "Redis connection address (Redis engine)")
rootCmd.Flags().StringP("tarantool_address", "", "tcp://127.0.0.1:3301", "Tarantool connection address (Tarantool engine)")
rootCmd.Flags().StringP("nats_url", "", "nats://127.0.0.1:4222", "Nats connection URL in format nats://user:pass@localhost:4222 (Nats broker)")
var versionCmd = &cobra.Command{
Use: "version",
Short: "Centrifugo version information",
Long: `Print the version information of Centrifugo`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Centrifugo v%s (Go version: %s)\n", build.Version, runtime.Version())
},
}
var checkConfigFile string
var checkConfigCmd = &cobra.Command{
Use: "checkconfig",
Short: "Check configuration file",
Long: `Check Centrifugo configuration file`,
Run: func(cmd *cobra.Command, args []string) {
bindCentrifugoConfig()
err := validateConfig(checkConfigFile)
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
},
}
checkConfigCmd.Flags().StringVarP(&checkConfigFile, "config", "c", "config.json", "path to config file to check")
var outputConfigFile string
var genConfigCmd = &cobra.Command{
Use: "genconfig",
Short: "Generate minimal configuration file to start with",
Long: `Generate minimal configuration file to start with`,
Run: func(cmd *cobra.Command, args []string) {
err := tools.GenerateConfig(outputConfigFile)
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
bindCentrifugoConfig()
err = validateConfig(outputConfigFile)
if err != nil {
_ = os.Remove(outputConfigFile)
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
},
}
genConfigCmd.Flags().StringVarP(&outputConfigFile, "config", "c", "config.json", "path to output config file")
var genTokenConfigFile string
var genTokenUser string
var genTokenTTL int64
var genTokenCmd = &cobra.Command{
Use: "gentoken",
Short: "Generate sample connection JWT for user",
Long: `Generate sample connection JWT for user`,
Run: func(cmd *cobra.Command, args []string) {
bindCentrifugoConfig()
err := readConfig(genTokenConfigFile)
if err != nil && err != errConfigFileNotFound {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
jwtVerifierConfig := jwtVerifierConfig()
token, err := cli.GenerateToken(jwtVerifierConfig, genTokenUser, genTokenTTL)
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
var user = fmt.Sprintf("user %s", genTokenUser)
if genTokenUser == "" {
user = "anonymous user"
}
fmt.Printf("HMAC SHA-256 JWT for %s with expiration TTL %s:\n%s\n", user, time.Duration(genTokenTTL)*time.Second, token)
},
}
genTokenCmd.Flags().StringVarP(&genTokenConfigFile, "config", "c", "config.json", "path to config file")
genTokenCmd.Flags().StringVarP(&genTokenUser, "user", "u", "", "user ID")
genTokenCmd.Flags().Int64VarP(&genTokenTTL, "ttl", "t", 3600*24*7, "token TTL in seconds")
var checkTokenConfigFile string
var checkTokenCmd = &cobra.Command{
Use: "checktoken [TOKEN]",
Short: "Check connection JWT",
Long: `Check connection JWT`,
Run: func(cmd *cobra.Command, args []string) {
bindCentrifugoConfig()
err := readConfig(checkTokenConfigFile)
if err != nil && err != errConfigFileNotFound {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
jwtVerifierConfig := jwtVerifierConfig()
if len(args) != 1 {
fmt.Printf("error: provide token to check [centrifugo checktoken <TOKEN>]\n")
os.Exit(1)
}
subject, claims, err := cli.CheckToken(jwtVerifierConfig, ruleConfig(), args[0])
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
var user = fmt.Sprintf("user %s", subject)
if subject == "" {
user = "anonymous user"
}
fmt.Printf("valid token for %s\npayload: %s\n", user, string(claims))
},
}
checkTokenCmd.Flags().StringVarP(&checkTokenConfigFile, "config", "c", "config.json", "path to config file")
var serveDir string
var servePort int
var serveAddr string
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Run static file server",
Long: `Run static file server`,
Run: func(cmd *cobra.Command, args []string) {
address := net.JoinHostPort(serveAddr, strconv.Itoa(servePort))
fmt.Printf("start serving %s on %s\n", serveDir, address)
if err := http.ListenAndServe(address, http.FileServer(http.Dir(serveDir))); err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
serveCmd.Flags().StringVarP(&serveDir, "dir", "d", "./", "path to directory")
serveCmd.Flags().IntVarP(&servePort, "port", "p", 3000, "port to serve on")
serveCmd.Flags().StringVarP(&serveAddr, "address", "a", "", "interface to serve on (default: all interfaces)")
rootCmd.AddCommand(serveCmd)
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(checkConfigCmd)
rootCmd.AddCommand(genConfigCmd)
rootCmd.AddCommand(genTokenCmd)
rootCmd.AddCommand(checkTokenCmd)
_ = rootCmd.Execute()
}
func writePidFile(pidFile string) error {
if pidFile == "" {
return nil
}
pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
return os.WriteFile(pidFile, pid, 0644)
}
var logLevelMatches = map[string]zerolog.Level{
"NONE": zerolog.NoLevel,
"TRACE": zerolog.TraceLevel,
"DEBUG": zerolog.DebugLevel,
"INFO": zerolog.InfoLevel,
"WARN": zerolog.WarnLevel,
"ERROR": zerolog.ErrorLevel,
"FATAL": zerolog.FatalLevel,
}
func configureConsoleWriter() {
if isTerminalAttached() {
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: "2006-01-02 15:04:05",
FormatLevel: logutils.ConsoleFormatLevel(),
FormatErrFieldName: logutils.ConsoleFormatErrFieldName(),
FormatErrFieldValue: logutils.ConsoleFormatErrFieldValue(),
})
}
}
func isTerminalAttached() bool {
return isatty.IsTerminal(os.Stdout.Fd()) && runtime.GOOS != "windows"
}
func setupLogging() *os.File {
configureConsoleWriter()
zerolog.SetGlobalLevel(zerolog.InfoLevel)
logLevel, ok := logLevelMatches[strings.ToUpper(viper.GetString("log_level"))]
if !ok {
logLevel = zerolog.InfoLevel
}
zerolog.SetGlobalLevel(logLevel)
if viper.IsSet("log_file") && viper.GetString("log_file") != "" {
f, err := os.OpenFile(viper.GetString("log_file"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal().Msgf("error opening log file: %v", err)
}
log.Logger = log.Output(f)
return f
}
return nil
}
func handleSignals(configFile string, n *centrifuge.Node, ruleContainer *rule.Container, tokenVerifier *jwtverify.VerifierJWT, httpServers []*http.Server, grpcAPIServer *grpc.Server, grpcUniServer *grpc.Server, exporter *graphite.Exporter) {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGINT, os.Interrupt, syscall.SIGTERM)
for {
sig := <-sigCh
log.Info().Msgf("signal received: %v", sig)
switch sig {
case syscall.SIGHUP:
// reload application configuration on SIGHUP.
log.Info().Msg("reloading configuration")
err := validateConfig(configFile)
if err != nil {
log.Error().Msgf("error parsing configuration: %s", err)
continue
}
ruleConfig := ruleConfig()
if err := tokenVerifier.Reload(jwtVerifierConfig()); err != nil {
log.Error().Msgf("error reloading: %v", err)
continue
}
if err := ruleContainer.Reload(ruleConfig); err != nil {
log.Error().Msgf("error reloading: %v", err)
continue
}
log.Info().Msg("configuration successfully reloaded")
case syscall.SIGINT, os.Interrupt, syscall.SIGTERM:
log.Info().Msg("shutting down ...")
pidFile := viper.GetString("pid_file")
shutdownTimeout := GetDuration("shutdown_timeout")
go time.AfterFunc(shutdownTimeout, func() {
if pidFile != "" {
_ = os.Remove(pidFile)
}
os.Exit(1)
})
if exporter != nil {
_ = exporter.Close()
}
var wg sync.WaitGroup
if grpcAPIServer != nil {
wg.Add(1)
go func() {
defer wg.Done()
grpcAPIServer.GracefulStop()
}()
}
if grpcUniServer != nil {
wg.Add(1)
go func() {
defer wg.Done()
grpcUniServer.GracefulStop()
}()
}
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
for _, srv := range httpServers {
wg.Add(1)
go func(srv *http.Server) {
defer wg.Done()
_ = srv.Shutdown(ctx)
}(srv)
}
_ = n.Shutdown(ctx)
wg.Wait()
cancel()
if pidFile != "" {
_ = os.Remove(pidFile)
}
time.Sleep(GetDuration("shutdown_termination_delay"))
os.Exit(0)
}
}
}
var startHTTPChallengeServerOnce sync.Once
func getTLSConfig() (*tls.Config, error) {
tlsEnabled := viper.GetBool("tls")
tlsCert := viper.GetString("tls_cert")
tlsKey := viper.GetString("tls_key")
tlsAutocertEnabled := viper.GetBool("tls_autocert")
autocertHostWhitelist := viper.GetString("tls_autocert_host_whitelist")
var tlsAutocertHostWhitelist []string
if autocertHostWhitelist != "" {
tlsAutocertHostWhitelist = strings.Split(autocertHostWhitelist, ",")
} else {
tlsAutocertHostWhitelist = nil
}
tlsAutocertCacheDir := viper.GetString("tls_autocert_cache_dir")
tlsAutocertEmail := viper.GetString("tls_autocert_email")
tlsAutocertServerName := viper.GetString("tls_autocert_server_name")
tlsAutocertHTTP := viper.GetBool("tls_autocert_http")
tlsAutocertHTTPAddr := viper.GetString("tls_autocert_http_addr")
if tlsAutocertEnabled {
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
Email: tlsAutocertEmail,
}
if tlsAutocertHostWhitelist != nil {
certManager.HostPolicy = autocert.HostWhitelist(tlsAutocertHostWhitelist...)
}
if tlsAutocertCacheDir != "" {
certManager.Cache = autocert.DirCache(tlsAutocertCacheDir)
}
if tlsAutocertHTTP {
startHTTPChallengeServerOnce.Do(func() {
// getTLSConfig can be called several times.
acmeHTTPServer := &http.Server{
Handler: certManager.HTTPHandler(nil),
Addr: tlsAutocertHTTPAddr,
ErrorLog: stdlog.New(&httpErrorLogWriter{log.Logger}, "", 0),
}
go func() {
log.Info().Msgf("serving ACME http_01 challenge on %s", tlsAutocertHTTPAddr)
if err := acmeHTTPServer.ListenAndServe(); err != nil {
log.Fatal().Msgf("can't create server on %s to serve acme http challenge: %v", tlsAutocertHTTPAddr, err)
}
}()
})
}
return &tls.Config{
GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
// See https://github.com/centrifugal/centrifugo/issues/144#issuecomment-279393819
if tlsAutocertServerName != "" && hello.ServerName == "" {
hello.ServerName = tlsAutocertServerName
}
return certManager.GetCertificate(hello)
},
NextProtos: []string{
"h2", "http/1.1", acme.ALPNProto,
},
}, nil
} else if tlsEnabled {
// Autocert disabled - just try to use provided SSL cert and key files.
tlsConfig := &tls.Config{}
tlsConfig = tlsConfig.Clone()
tlsConfig.Certificates = make([]tls.Certificate, 1)
var err error
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(tlsCert, tlsKey)
if err != nil {
return nil, err
}
return tlsConfig, nil
}
return nil, nil
}
func tlsConfigForGRPC() (*tls.Config, error) {
tlsCert := viper.GetString("grpc_api_tls_cert")
tlsKey := viper.GetString("grpc_api_tls_key")
tlsConfig := &tls.Config{}
tlsConfig.Certificates = make([]tls.Certificate, 1)
var err error
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(tlsCert, tlsKey)
if err != nil {
return nil, err
}
return tlsConfig, nil
}
func tlsConfigForUniGRPC() (*tls.Config, error) {
tlsCert := viper.GetString("uni_grpc_tls_cert")
tlsKey := viper.GetString("uni_grpc_tls_key")
tlsConfig := &tls.Config{}
tlsConfig.Certificates = make([]tls.Certificate, 1)
var err error
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(tlsCert, tlsKey)
if err != nil {
return nil, err
}
return tlsConfig, nil
}
type httpErrorLogWriter struct {
zerolog.Logger
}
func (w *httpErrorLogWriter) Write(data []byte) (int, error) {
w.Logger.Warn().Msg(strings.TrimSpace(string(data)))
return len(data), nil
}
func runHTTPServers(n *centrifuge.Node, apiExecutor *api.Executor) ([]*http.Server, error) {
debug := viper.GetBool("debug")
useAdmin := viper.GetBool("admin")
usePrometheus := viper.GetBool("prometheus")
useHealth := viper.GetBool("health")
adminExternal := viper.GetBool("admin_external")
httpAddress := viper.GetString("address")
httpPort := viper.GetString("port")
httpInternalAddress := viper.GetString("internal_address")
httpInternalPort := viper.GetString("internal_port")
if httpInternalAddress == "" && httpAddress != "" {
// If custom internal address not explicitly set we try to reuse main
// address for internal endpoints too.
httpInternalAddress = httpAddress