-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathhttp.go
More file actions
1822 lines (1633 loc) · 59.1 KB
/
http.go
File metadata and controls
1822 lines (1633 loc) · 59.1 KB
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
package nsqadmin
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"mime"
"net"
"net/http"
"net/http/httputil"
"net/url"
"path"
"strconv"
"strings"
"time"
"bytes"
"sort"
"sync"
"github.com/julienschmidt/httprouter"
"github.com/youzan/nsq/internal/clusterinfo"
"github.com/youzan/nsq/internal/http_api"
"github.com/youzan/nsq/internal/protocol"
"github.com/youzan/nsq/internal/version"
"golang.org/x/net/context"
"golang.org/x/sync/semaphore"
)
func maybeWarnMsg(msgs []string) string {
if len(msgs) > 0 {
return "WARNING: " + strings.Join(msgs, "; ")
}
return ""
}
// this is similar to httputil.NewSingleHostReverseProxy except it passes along basic auth
func NewSingleHostReverseProxy(target *url.URL, timeout time.Duration) *httputil.ReverseProxy {
director := func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
if target.User != nil {
passwd, _ := target.User.Password()
req.SetBasicAuth(target.User.Username(), passwd)
}
}
return &httputil.ReverseProxy{
Director: director,
Transport: http_api.NewDeadlineTransport(timeout),
}
}
type httpServer struct {
ctx *Context
router http.Handler
client *http_api.Client
ci *clusterinfo.ClusterInfo
}
func NewHTTPServer(ctx *Context) *httpServer {
log := http_api.Log(adminLog)
client := http_api.NewClient(ctx.nsqadmin.httpClientTLSConfig)
router := httprouter.New()
router.HandleMethodNotAllowed = true
router.PanicHandler = http_api.LogPanicHandler(adminLog)
router.NotFound = http_api.LogNotFoundHandler(adminLog)
router.MethodNotAllowed = http_api.LogMethodNotAllowedHandler(adminLog)
s := &httpServer{
ctx: ctx,
router: router,
client: client,
ci: clusterinfo.New(ctx.nsqadmin.opts.Logger, client),
}
router.Handle("GET", "/ping", http_api.Decorate(s.pingHandler, log, http_api.PlainText))
router.Handle("GET", "/", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/topics", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/topics/:topic", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/topics/:topic/:channel", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/nodes", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/nodes/:node", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/counter", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/lookup", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/statistics", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/search", http_api.Decorate(s.indexHandler, log))
router.Handle("GET", "/static/:asset", http_api.Decorate(s.staticAssetHandler, log, http_api.PlainText))
router.Handle("GET", "/fonts/:asset", http_api.Decorate(s.staticAssetHandler, log, http_api.PlainText))
if s.ctx.nsqadmin.opts.ProxyGraphite {
proxy := NewSingleHostReverseProxy(ctx.nsqadmin.graphiteURL, 20*time.Second)
router.Handler("GET", "/render", proxy)
}
// v1 endpoints
router.Handle("GET", "/api/topics", http_api.Decorate(s.topicsHandler, log, http_api.V1))
router.Handle("GET", "/api/topics/:topic", http_api.Decorate(s.topicHandler, log, http_api.V1))
router.Handle("GET", "/api/coordinators/:node/:topic/:partition", http_api.Decorate(s.coordinatorHandler, log, http_api.V1))
router.Handle("GET", "/api/lookup/nodes", http_api.Decorate(s.lookupNodesHandler, log, http_api.V1))
router.Handle("GET", "/api/topics/:topic/:channel", http_api.Decorate(s.channelHandler, log, http_api.V1))
router.Handle("GET", "/api/nodes", http_api.Decorate(s.nodesHandler, log, http_api.V1))
router.Handle("GET", "/api/nodes/:node", http_api.Decorate(s.nodeHandler, log, http_api.V1))
router.Handle("POST", "/api/search/messages", http_api.Decorate(s.searchMessageTrace, s.authCheck, log, http_api.V1))
router.Handle("POST", "/api/topics", http_api.Decorate(s.createTopicChannelHandler, s.authCheck, log, http_api.V1))
router.Handle("POST", "/api/topics/:topic", http_api.Decorate(s.topicActionHandler, s.authCheck, log, http_api.V1))
router.Handle("POST", "/api/topics/:topic/:channel", http_api.Decorate(s.channelActionHandler, s.adminCheck, log, http_api.V1))
router.Handle("POST", "/api/topics/:topic/:channel/admin", http_api.Decorate(s.channelAdminActionHandler, s.adminCheck, log, http_api.V1))
router.Handle("POST", "/api/topics/:topic/:channel/client", http_api.Decorate(s.channelClientActionHandler, s.authCheck, log, http_api.V1))
router.Handle("DELETE", "/api/nodes/:node", http_api.Decorate(s.tombstoneNodeForTopicHandler, s.adminCheck, log, http_api.V1))
router.Handle("DELETE", "/api/topics/:topic", http_api.Decorate(s.deleteTopicHandler, s.adminCheck, log, http_api.V1))
router.Handle("DELETE", "/api/topics/:topic/:channel", http_api.Decorate(s.deleteChannelHandler, s.adminCheck, log, http_api.V1))
router.Handle("GET", "/api/counter", http_api.Decorate(s.counterHandler, log, http_api.V1))
router.Handle("GET", "/api/graphite", http_api.Decorate(s.graphiteHandler, log, http_api.V1))
router.Handle("GET", "/api/statistics", http_api.Decorate(s.statisticsHandler, log, http_api.V1))
router.Handle("GET", "/api/statistics/:sortBy", http_api.Decorate(s.statisticsHandler, log, http_api.V1))
router.Handle("GET", "/api/cluster/stats", http_api.Decorate(s.clusterStatsHandler, log, http_api.V1))
router.Handle("GET", "/api/oauth/cas/callback", http_api.Decorate(s.casAuthCallbackHandler, log, http_api.V1))
router.Handle("GET", "/api/oauth/cas/callback/logout", http_api.Decorate(s.casAuthCallbackLogoutHandler, log, http_api.V1))
return s
}
func (s *httpServer) getExistingUserInfo(req *http.Request) (IUserAuth, error) {
return GetUserModel(s.ctx, req)
}
func (s *httpServer) logoutUser(w http.ResponseWriter, req *http.Request) error {
return LogoutUser(s.ctx, w, req)
}
func (s *httpServer) getUserInfo(w http.ResponseWriter, req *http.Request) (IUserAuth, error) {
u, err := s.getExistingUserInfo(req)
if err != nil {
s.ctx.nsqadmin.logf("error getting existing user, err: %v", err)
return nil, err
}
if u == nil {
u, err = NewCasUserModel(s.ctx, w, req)
}
return u, err
}
func (s *httpServer) validAccessToken(req *http.Request) (valid bool) {
token, ok := parseAccessToken(req)
if ok && s.ctx.nsqadmin.accessTokens[token] {
return true
}
return
}
func parseAccessToken(r *http.Request) (token string, ok bool) {
auth := r.Header.Get("Authorization")
if auth == "" {
return
}
const prefix = "Basic "
if !strings.HasPrefix(auth, prefix) {
return
}
return auth[len(prefix):], true
}
func (s *httpServer) adminCheck(f http_api.APIHandler) http_api.APIHandler {
return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
//check user info
if s.ctx.nsqadmin.IsAuthEnabled() {
u, err := s.getUserInfo(w, req)
if err != nil {
s.ctx.nsqadmin.logf("error in fetching user model %v", err)
return nil, http_api.Err{http.StatusInternalServerError, "fail to find associated user info"}
}
if !u.IsAdmin() && !s.validAccessToken(req) {
return nil, http_api.Err{http.StatusUnauthorized, "administrator priority needed"}
}
}
return f(w, req, ps)
}
}
func (s *httpServer) authCheck(f http_api.APIHandler) http_api.APIHandler {
return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
//check user info
if s.ctx.nsqadmin.IsAuthEnabled() {
u, err := s.getUserInfo(w, req)
if err != nil {
s.ctx.nsqadmin.logf("error in fetching user model %v", err)
return nil, http_api.Err{http.StatusInternalServerError, "fail to find associated user info"}
}
if !u.IsLogin() && !s.validAccessToken(req) {
return nil, http_api.Err{http.StatusUnauthorized, "authentication needed"}
}
}
return f(w, req, ps)
}
}
func (s *httpServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.router.ServeHTTP(w, req)
}
func (s *httpServer) pingHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
return "OK", nil
}
type DCLookupdAddrs struct {
DC string `json:"dc"`
LookupdAddrs []string `json:"lookupAddrs"`
}
func transform2DCLookupdAddrs(dcLookupdAddrs map[string][]string) []*DCLookupdAddrs {
dcLookupdAddrsList := make([]*DCLookupdAddrs, 0)
for dc, _ := range dcLookupdAddrs {
dcLookupdAddrsList = append(dcLookupdAddrsList, &DCLookupdAddrs{dc, dcLookupdAddrs[dc]})
}
return dcLookupdAddrsList
}
func (s *httpServer) indexHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
asset, _ := Asset("index.html")
t, _ := template.New("index").Funcs(template.FuncMap{"dcLookupdList": transform2DCLookupdAddrs}).Parse(string(asset))
w.Header().Set("Content-Type", "text/html")
lookupdAddresses := make([]string, 0)
//all lookupd addresses from dc
dcLookupdAddresses := make(map[string][]string)
lookupdAddresseMap := make(map[string]bool)
http2DCMap := make(map[string]string)
for _, addr := range s.ctx.nsqadmin.opts.NSQDHTTPAddresses {
lookupdAddresseMap[addr] = false
}
lookupdNodesDC, err := s.ci.ListAllLookupdNodes(s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC)
if err != nil {
s.ctx.nsqadmin.logf("WARNING: failed to list lookupd nodes : %v", err)
} else {
s.ctx.nsqadmin.logf("list lookupd found nodes : %v", lookupdNodesDC)
for _, lookupdNodes := range lookupdNodesDC {
for _, n := range lookupdNodes.AllNodes {
addr := net.JoinHostPort(n.NodeIP, n.HttpPort)
lookupdAddresseMap[addr] = false
http2DCMap[addr] = lookupdNodes.DC
}
if lookupdNodes.LeaderNode.ID != "" {
leaderAddr := net.JoinHostPort(lookupdNodes.LeaderNode.NodeIP, lookupdNodes.LeaderNode.HttpPort)
lookupdAddresseMap[leaderAddr] = true
}
}
}
for addr, isLeader := range lookupdAddresseMap {
if _, exist := dcLookupdAddresses[http2DCMap[addr]]; !exist {
dcLookupdAddresses[http2DCMap[addr]] = make([]string, 0)
}
if isLeader {
lookupdAddresses = append(lookupdAddresses, addr+" (Leader)")
dcLookupdAddresses[http2DCMap[addr]] = append(dcLookupdAddresses[http2DCMap[addr]], addr+" (Leader)")
} else {
lookupdAddresses = append(lookupdAddresses, addr)
dcLookupdAddresses[http2DCMap[addr]] = append(dcLookupdAddresses[http2DCMap[addr]], addr)
}
}
delete(dcLookupdAddresses, "")
s.ctx.nsqadmin.logf("total lookupd nodes : %v", lookupdAddresses)
u, _ := s.getUserInfo(w, req)
//add redirect query to ca auth url
authUrl, err := url.Parse(s.ctx.nsqadmin.opts.AuthUrl)
if err != nil {
s.ctx.nsqadmin.logf("ERROR: failed to parse authentication url %v : %v", s.ctx.nsqadmin.opts.AuthUrl, err)
return nil, http_api.Err{http.StatusInternalServerError, "INTERNAL ERROR"}
}
t.Execute(w, struct {
Version string
ProxyGraphite bool
GraphEnabled bool
GraphiteURL string
StatsdInterval int
UseStatsdPrefixes bool
StatsdCounterFormat string
StatsdGaugeFormat string
StatsdPrefix string
NSQLookupd []string
DCNSQLookupd map[string][]string
AllNSQLookupds []string
DCAllNSQLookupds map[string][]string
AuthUrl string
LogoutUrl string
Login bool
User string
AuthEnabled bool
HasNotificationEndpoint bool
EnableZanTestSkip bool
}{
Version: version.Binary,
ProxyGraphite: s.ctx.nsqadmin.opts.ProxyGraphite,
GraphEnabled: s.ctx.nsqadmin.opts.GraphiteURL != "",
GraphiteURL: s.ctx.nsqadmin.opts.GraphiteURL,
StatsdInterval: int(s.ctx.nsqadmin.opts.StatsdInterval / time.Second),
UseStatsdPrefixes: s.ctx.nsqadmin.opts.UseStatsdPrefixes,
StatsdCounterFormat: s.ctx.nsqadmin.opts.StatsdCounterFormat,
StatsdGaugeFormat: s.ctx.nsqadmin.opts.StatsdGaugeFormat,
StatsdPrefix: s.ctx.nsqadmin.opts.StatsdPrefix,
NSQLookupd: s.ctx.nsqadmin.opts.NSQLookupdHTTPAddresses,
DCNSQLookupd: s.ctx.nsqadmin.DC2LookupAddresses(),
AllNSQLookupds: lookupdAddresses,
DCAllNSQLookupds: dcLookupdAddresses,
AuthUrl: authUrl.String(),
LogoutUrl: s.ctx.nsqadmin.opts.LogoutUrl,
Login: (s.ctx.nsqadmin.IsAuthEnabled() && u.IsLogin()) || (!s.ctx.nsqadmin.IsAuthEnabled()),
User: u.GetUserName(),
AuthEnabled: s.ctx.nsqadmin.IsAuthEnabled(),
HasNotificationEndpoint: s.ctx.nsqadmin.opts.NotificationHTTPEndpoint != "",
EnableZanTestSkip: s.ctx.nsqadmin.opts.EnableZanTestSkip,
})
return nil, nil
}
func (s *httpServer) staticAssetHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
assetName := ps.ByName("asset")
asset, err := Asset(assetName)
if err != nil {
return nil, http_api.Err{404, "NOT_FOUND"}
}
ext := path.Ext(assetName)
ct := mime.TypeByExtension(ext)
if ct == "" {
switch ext {
case ".svg":
ct = "image/svg+xml"
case ".woff":
ct = "application/font-woff"
case ".ttf":
ct = "application/font-sfnt"
case ".eot":
ct = "application/vnd.ms-fontobject"
case ".woff2":
ct = "application/font-woff2"
}
}
if ct != "" {
w.Header().Set("Content-Type", ct)
}
return string(asset), nil
}
func (s *httpServer) topicsHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
var messages []string
reqParams, err := http_api.NewReqParams(req)
if err != nil {
return nil, http_api.Err{400, err.Error()}
}
var topics []*clusterinfo.TopicInfo
if len(s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC) > 0 {
fetchMetaStr, _ := reqParams.Get("metaInfo")
topics, err = s.ci.GetLookupdTopicsMeta(s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC, fetchMetaStr == "true")
} else {
topics, err = s.ci.GetNSQDTopics(s.ctx.nsqadmin.opts.NSQDHTTPAddresses)
}
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get topics - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
inactive, _ := reqParams.Get("inactive")
if inactive == "true" {
maxWeight := 10
if len(topics) < 10 {
maxWeight = len(topics)
}
sem := semaphore.NewWeighted(int64(maxWeight))
ctx := context.TODO()
var channelMapLock sync.RWMutex
topicChannelMap := make(map[string][]string)
if len(s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC) == 0 {
goto respond
}
for _, topic := range topics {
if err := sem.Acquire(ctx, 1); err != nil {
s.ctx.nsqadmin.logf("ERROR: failed to get semapher - %s", err)
break
}
go func() {
defer sem.Release(1)
producers, _, _ := s.ci.GetLookupdTopicProducers(
topic.TopicName, s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC)
if len(producers) == 0 {
topicChannels, _ := s.ci.GetLookupdTopicChannels(
topic.TopicName, s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC)
channelMapLock.Lock()
topicChannelMap[topic.TopicName] = topicChannels
channelMapLock.Unlock()
}
}()
}
if err := sem.Acquire(ctx, int64(maxWeight)); err != nil {
s.ctx.nsqadmin.logf("Failed to acquire semaphore: %v", err)
}
respond:
return struct {
Topics map[string][]string `json:"topics"`
Message string `json:"message"`
}{topicChannelMap, maybeWarnMsg(messages)}, nil
}
return struct {
Topics []*clusterinfo.TopicInfo `json:"topics"`
Message string `json:"message"`
}{topics, maybeWarnMsg(messages)}, nil
}
func (s *httpServer) lookupNodesHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
var messages []string
nodesDC, err := s.ci.ListAllLookupdNodes(s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get lookupd nodes - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: partial error %s", err)
messages = append(messages, pe.Error())
}
return struct {
*clusterinfo.LookupdNodes
LookupdNodesDC []*clusterinfo.LookupdNodes `json:"lookupd_nodes_dc"`
Message string `json:"message"`
}{nodesDC[0], nodesDC, maybeWarnMsg(messages)}, nil
}
func (s *httpServer) coordinatorHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
topicName := ps.ByName("topic")
partition := ps.ByName("partition")
var messages []string
node := ps.ByName("node")
producers, _, err := s.ci.GetTopicProducers(topicName,
s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC,
s.ctx.nsqadmin.opts.NSQDHTTPAddresses)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get topic producers - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
producer := producers.Search(node)
if producer == nil {
return nil, http_api.Err{404, "NODE_NOT_FOUND"}
}
topicCoordStats, err := s.ci.GetNSQDCoordStats(clusterinfo.Producers{producer}, topicName, partition)
if err != nil {
s.ctx.nsqadmin.logf("ERROR: failed to get nsqd coordinator stats - %s", err)
messages = append(messages, err.Error())
}
return struct {
*clusterinfo.CoordStats
Message string `json:"message"`
}{topicCoordStats, maybeWarnMsg(messages)}, nil
}
func (s *httpServer) topicHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
var messages []string
topicName := ps.ByName("topic")
producers, _, err := s.ci.GetTopicProducers(topicName,
s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC,
s.ctx.nsqadmin.opts.NSQDHTTPAddresses)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get topic producers - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
if producers.Len() == 0 {
return nil, http_api.Err{404, "NODE_NOT_FOUND"}
}
topicStats, _, err := s.ci.GetNSQDStatsWithClients(producers, topicName, "partition", true)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get topic metadata - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
topicCoordStats, err := s.ci.GetNSQDCoordStats(producers, topicName, "")
if err != nil {
s.ctx.nsqadmin.logf("ERROR: failed to get nsqd topic %v coordinator stats - %s", topicName, err)
messages = append(messages, err.Error())
}
statsMap := make(map[string]map[string]clusterinfo.TopicCoordStat)
if topicCoordStats != nil {
for _, stat := range topicCoordStats.TopicCoordStats {
t, ok := statsMap[stat.Name]
if !ok {
t = make(map[string]clusterinfo.TopicCoordStat)
statsMap[stat.Name] = t
}
t[strconv.Itoa(stat.Partition)] = stat
}
}
isOrdered := false
isMultiPart := false
isExt := false
isChannelAutoCreateDisabled := false
if len(topicStats) > 0 {
isOrdered = topicStats[0].IsMultiOrdered
isMultiPart = topicStats[0].IsMultiPart
isExt = topicStats[0].IsExt
isChannelAutoCreateDisabled = topicStats[0].IsChannelAutoCreateDisabled
}
allNodesTopicStats := &clusterinfo.TopicStats{
TopicName: topicName,
StatsdName: topicName,
IsMultiOrdered: isOrdered,
IsMultiPart: isMultiPart,
IsExt: isExt,
IsChannelAutoCreateDisabled: isChannelAutoCreateDisabled,
}
for _, t := range topicStats {
stat, ok := statsMap[t.TopicName]
if ok {
v, ok := stat[t.TopicPartition]
if ok {
t.ISRStats = v.ISRStats
t.CatchupStats = v.CatchupStats
}
}
t.SyncingNum = len(t.ISRStats) + len(t.CatchupStats)
historyStat, err := s.ci.GetNSQDMessageHistoryStats(t.Node, t.TopicName, t.TopicPartition)
if err != nil {
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, err.Error())
} else {
t.PartitionHourlyPubSize = historyStat
}
allNodesTopicStats.Add(t)
}
return struct {
*clusterinfo.TopicStats
Message string `json:"message"`
}{allNodesTopicStats, maybeWarnMsg(messages)}, nil
}
func (s *httpServer) channelHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
var messages []string
topicName := ps.ByName("topic")
channelName := ps.ByName("channel")
producers, _, err := s.ci.GetTopicProducers(topicName,
s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC,
s.ctx.nsqadmin.opts.NSQDHTTPAddresses)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get topic producers - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
if producers.Len() == 0 {
return nil, http_api.Err{404, "NODE_NOT_FOUND"}
}
_, allChannelStats, err := s.ci.GetNSQDStatsWithClients(producers, topicName, "partition", true)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get channel metadata - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
//if there is only one channel, disable channel deletion button
if len(allChannelStats) <= 1 {
cs, ok := allChannelStats[channelName]
if ok {
cs.OnlyChannel = true
}
}
return struct {
*clusterinfo.ChannelStats
Message string `json:"message"`
}{allChannelStats[channelName], maybeWarnMsg(messages)}, nil
}
func (s *httpServer) nodesHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
var messages []string
producers, err := s.ci.GetProducers(s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC, s.ctx.nsqadmin.opts.NSQDHTTPAddresses)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get nodes - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
return struct {
Nodes clusterinfo.Producers `json:"nodes"`
Message string `json:"message"`
}{producers, maybeWarnMsg(messages)}, nil
}
func (s *httpServer) nodeHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
var messages []string
node := ps.ByName("node")
producers, err := s.ci.GetProducers(s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC, s.ctx.nsqadmin.opts.NSQDHTTPAddresses)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to get producers - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
producer := producers.Search(node)
if producer == nil {
return nil, http_api.Err{404, "NODE_NOT_FOUND"}
}
topicStats, _, err := s.ci.GetNSQDStats(clusterinfo.Producers{producer}, "", "channel-depth", false)
if err != nil {
s.ctx.nsqadmin.logf("ERROR: failed to get nsqd stats - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
var totalClients int64
var totalMessages int64
for _, ts := range topicStats {
for _, cs := range ts.Channels {
if len(cs.Clients) != 0 {
totalClients += int64(len(cs.Clients))
} else {
totalClients += int64(cs.ClientNum)
}
}
totalMessages += ts.MessageCount
}
return struct {
Node string `json:"node"`
TopicStats []*clusterinfo.TopicStats `json:"topics"`
TotalMessages int64 `json:"total_messages"`
TotalClients int64 `json:"total_clients"`
Message string `json:"message"`
}{
Node: node,
TopicStats: topicStats,
TotalMessages: totalMessages,
TotalClients: totalClients,
Message: maybeWarnMsg(messages),
}, nil
}
func (s *httpServer) tombstoneNodeForTopicHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
var messages []string
node := ps.ByName("node")
var body struct {
Topic string `json:"topic"`
}
err := json.NewDecoder(req.Body).Decode(&body)
if err != nil {
return nil, http_api.Err{400, "INVALID_BODY"}
}
if !protocol.IsValidTopicName(body.Topic) {
return nil, http_api.Err{400, "INVALID_TOPIC"}
}
err = s.ci.TombstoneNodeForTopic(body.Topic, node,
s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
s.ctx.nsqadmin.logf("ERROR: failed to tombstone node for topic - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
}
s.ctx.nsqadmin.logf("WARNING: %s", err)
messages = append(messages, pe.Error())
}
s.notifyAdminActionWithUser("tombstone_topic_producer", body.Topic, "", node, req)
return struct {
Message string `json:"message"`
}{maybeWarnMsg(messages)}, nil
}
func hashTraceID(v string) int {
h := int32(0)
if len(v) > 0 {
for i := 0; i < len(v); i++ {
h = 31*h + int32(v[i])
}
}
if h < 0 {
h = -1 * h
}
return int(h)
}
const (
MAX_INCR_ID_BIT = 50
)
func GetPartitionFromMsgID(id int64) int {
// the max partition id will be less than 1024
return int((uint64(id) & (uint64(1024-1) << MAX_INCR_ID_BIT)) >> MAX_INCR_ID_BIT)
}
func (s *httpServer) searchMessageTrace(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
var warnMessages []string
if s.ctx.nsqadmin.opts.TraceQueryURL == "" {
return nil, http_api.Err{400, "TRACE service url is not configured"}
}
var queryParam struct {
Topic string `json:"topic"`
Partition string `json:"partition_id"`
Channel string `json:"channel"`
MsgID string `json:"msgid"`
TraceID string `json:"traceid"`
Hours string `json:"hours"`
IsHashed bool `json:"ishashed"`
DC []string `json:"dc"`
}
err := json.NewDecoder(req.Body).Decode(&queryParam)
if err != nil {
return nil, http_api.Err{400, err.Error()}
}
if !protocol.IsValidTopicName(queryParam.Topic) {
return nil, http_api.Err{400, "INVALID_TOPIC"}
}
dcChecked := make(map[string]bool)
if len(queryParam.DC) > 0 {
for _, dc := range queryParam.DC {
dcChecked[dc] = true
}
} else if len(s.ctx.nsqadmin.opts.DCNSQLookupdHTTPAddresses) > 0 {
return nil, http_api.Err{400, "AT_LEAST_ONE_DC_NEEDED"}
}
filters := make(IndexFieldsQuery, 0)
reqParams, err := http_api.NewReqParams(req)
if err != nil {
return nil, http_api.Err{400, err.Error()}
}
v := reqParams.Values["topic"]
topicName := queryParam.Topic
if topicName == "" && len(v) > 0 {
topicName = v[0]
}
filters["topic"] = topicName
isHashed := queryParam.IsHashed
var tid string
if isHashed {
tid = queryParam.TraceID
} else {
tid = strconv.Itoa(hashTraceID(queryParam.TraceID))
}
filters["traceid"] = tid
requestMsgID := int64(0)
requestMsgID, _ = strconv.ParseInt(queryParam.MsgID, 10, 64)
filters["msgid"] = queryParam.MsgID
for k, v := range reqParams.Values {
if len(v) == 0 {
continue
}
if k == "hashed" {
continue
}
filters[k] = v[0]
}
recentHour := 2
if queryParam.Hours != "" {
recentHour, err = strconv.Atoi(queryParam.Hours)
if err != nil {
recentHour = 2
}
}
queryBody := NewLogQueryInfo(
s.ctx.nsqadmin.opts.TraceAppName,
s.ctx.nsqadmin.opts.TraceLogIndexName,
time.Hour*time.Duration(recentHour),
filters, s.ctx.nsqadmin.opts.TraceLogPageCount)
d, _ := json.Marshal(queryBody)
s.ctx.nsqadmin.logf("search body: %v", string(d))
traceReq, err := http.NewRequest("POST", s.ctx.nsqadmin.opts.TraceQueryURL, bytes.NewReader(d))
if err != nil {
return nil, http_api.Err{500, err.Error()}
}
traceReq.Header.Add("Content-Type", "application/json; charset=UTF-8")
var traceResp TraceLogResp
resp, err := http.DefaultClient.Do(traceReq)
if err != nil {
s.ctx.nsqadmin.logf("search failed: %v", err)
warnMessages = append(warnMessages, err.Error())
} else {
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
s.ctx.nsqadmin.logf("search failed: %v", err)
warnMessages = append(warnMessages, err.Error())
} else {
if resp.StatusCode != http.StatusOK {
s.ctx.nsqadmin.logf("search failed: %v", fmt.Errorf("trace query service response: %v %v", resp.Status, string(body)).Error())
warnMessages = append(warnMessages, resp.Status)
} else {
err = json.Unmarshal(body, &traceResp)
if err != nil {
s.ctx.nsqadmin.logf("parse search respnse err: %v", err)
warnMessages = append(warnMessages, err.Error())
}
s.ctx.nsqadmin.logf("parse search response : %v", traceResp)
}
}
}
resultList := traceResp.Data
if topicName == "" {
if len(resultList.LogDataDtos) > 0 {
topicName = resultList.LogDataDtos[0].Topic
}
}
if topicName == "" {
return nil, http_api.Err{400, "topic should not be empty to search message"}
}
_, partitionProducers, _ := s.ci.GetTopicProducers(topicName, s.ctx.nsqadmin.opts.NSQLookupdHTTPAddressesDC,
s.ctx.nsqadmin.opts.NSQDHTTPAddresses)
if partitionProducers == nil {
return nil, http_api.Err{500, fmt.Sprintf("partition producers node for %v not found", topicName)}
}
//filter out trace messages which do not source from current nsqd
var tracelogFilteredLock sync.Mutex
tracelogFiltered := &TraceLog{
LogDataDtos: make([]TraceLogData, 0),
TotalCount: 0,
}
needGetRequestMsg := true
maxWeight := int64(10)
ctx := context.TODO()
sem := semaphore.NewWeighted(maxWeight)
for index, m := range resultList.LogDataDtos {
idx := index
//check dc from trace message host, filter out messages does not belong to query DC
dcPrefix := strings.SplitN(m.HostName, "-", 2)[0]
if len(dcChecked) > 0 {
if _, exist := dcChecked[dcPrefix]; !exist {
//set msg id to 0 to prevent adding to logDataFilterEmpty after current loop
resultList.LogDataDtos[idx].TraceLogItemInfo.MsgID = 0
continue
}
}
items := make([]TraceLogItemInfo, 0)
err = json.Unmarshal([]byte(m.Extra), &items)
// try compatible
if err != nil || len(items) == 0 {
err = json.Unmarshal([]byte(m.Extra1), &items)
if err != nil || len(items) == 0 {
s.ctx.nsqadmin.logf("msg extra invalid: %v: %v, %v", m.Extra, m.Extra1, err)
extraJsonStr, _ := strconv.Unquote(m.Extra1)
err = json.Unmarshal([]byte(extraJsonStr), &items)
if err != nil || len(items) == 0 {
s.ctx.nsqadmin.logf("msg extra1 invalid: %v, %v", m.Extra1, err)
continue
}
}
}
item := items[0]
if queryParam.Channel != "" && item.Channel != queryParam.Channel {
continue
}
resultList.LogDataDtos[idx].TraceLogItemInfo = item
pid := GetPartitionFromMsgID(int64(item.MsgID))
if len(partitionProducers[strconv.Itoa(pid)]) == 0 {
s.ctx.nsqadmin.logf("partition producer not found: %v", pid)
continue
}
//nsqd producers of pid among DC
producers := partitionProducers[strconv.Itoa(pid)]
if int64(item.MsgID) == requestMsgID {
needGetRequestMsg = false
}
if err := sem.Acquire(ctx, 1); err != nil {
s.ctx.nsqadmin.logf("ERROR: fail to acquire signal - %v", err)
warnMessages = append(warnMessages, err.Error())
break
}
for _, producer := range producers {
//skip producer ip or DC does not match
if (producer.DC != "" && dcPrefix != producer.DC) || producer.BroadcastAddress != m.HostIp {
continue
} else {
go func() {
defer sem.Release(int64(1))
//loop in nsqd node in all DC
msgBody, _, err := s.ci.GetNSQDMessageByID(*producer, item.Topic, strconv.Itoa(pid), int64(item.MsgID))
if err != nil {
s.ctx.nsqadmin.logf("get msg %v data failed : %v", item, err)
} else {
resultList.LogDataDtos[idx].RawMsgData = msgBody
tracelogFilteredLock.Lock()
//append messages to new filtered log list
tracelogFiltered.LogDataDtos = append(tracelogFiltered.LogDataDtos, resultList.LogDataDtos[idx])
tracelogFilteredLock.Unlock()
}
}()
}
}
}
if err := sem.Acquire(ctx, maxWeight); err != nil {
s.ctx.nsqadmin.logf("ERROR: fail to acquire signal - %v", err)
warnMessages = append(warnMessages, err.Error())
}
//update total count of tracelogFiltered
tracelogFiltered.TotalCount = len(tracelogFiltered.LogDataDtos)
logDataFilterEmpty := make(TLListT, 0, len(tracelogFiltered.LogDataDtos))
for _, v := range tracelogFiltered.LogDataDtos {
if v.MsgID == 0 {
continue
}
logDataFilterEmpty = append(logDataFilterEmpty, v)
}
sort.Sort(logDataFilterEmpty)
// js can not handle int64 in json, we convert int64 to string for showing.
logDataForJs := make([]TraceLogDataForJs, 0, len(logDataFilterEmpty))
for _, v := range logDataFilterEmpty {
var jsv TraceLogDataForJs
jsv.TraceLogItemInfoForJs = v.ToJsJson()
jsv.RawMsgData = v.RawMsgData
jsv.DC = v.DC
logDataForJs = append(logDataForJs, jsv)
}
if len(warnMessages) > 0 && requestMsgID > 0 {
needGetRequestMsg = true
}
//s.ctx.nsqadmin.logf("sorted msg trace data : %v", logDataFilterEmpty)
var requestMsg string
requestMsgDC := make(map[string]string)
if needGetRequestMsg && requestMsgID > 0 {
pid := GetPartitionFromMsgID(int64(requestMsgID))
if len(partitionProducers[strconv.Itoa(pid)]) == 0 {
s.ctx.nsqadmin.logf("partition producer not found: %v", pid)
} else {
//loop through partitionProducers in multi dc context
producersDC := partitionProducers[strconv.Itoa(pid)]
hasMultiDC := len(producersDC) > 1