Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nsqadmin/nsqd: optimize /stats #925

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/nsq_stat/nsq_stat.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func statLoop(interval time.Duration, connectTimeout time.Duration, requestTimeo
log.Fatalf("ERROR: failed to get topic producers - %s", err)
}

_, allChannelStats, err := ci.GetNSQDStats(producers, topic)
_, allChannelStats, err := ci.GetNSQDStats(producers, topic, "")
if err != nil {
log.Fatalf("ERROR: failed to get nsqd stats - %s", err)
}
Expand Down
13 changes: 10 additions & 3 deletions internal/clusterinfo/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ func (c *ClusterInfo) GetNSQDTopicProducers(topic string, nsqdHTTPAddrs []string
go func(addr string) {
defer wg.Done()

endpoint := fmt.Sprintf("http://%s/stats?format=json", addr)
endpoint := fmt.Sprintf("http://%s/stats?topic=%s&format=json", addr, topic)
c.logf("CI: querying nsqd %s", endpoint)

var statsResp statsRespType
Expand Down Expand Up @@ -530,7 +530,7 @@ func (c *ClusterInfo) GetNSQDTopicProducers(topic string, nsqdHTTPAddrs []string
//
// if selectedTopic is empty, this will return stats for *all* topic/channels
// and the ChannelStats dict will be keyed by topic + ':' + channel
func (c *ClusterInfo) GetNSQDStats(producers Producers, selectedTopic string) ([]*TopicStats, map[string]*ChannelStats, error) {
func (c *ClusterInfo) GetNSQDStats(producers Producers, selectedTopic, selectChannel string) ([]*TopicStats, map[string]*ChannelStats, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/selectChannel/selectedChannel/

var lock sync.Mutex
var wg sync.WaitGroup
var topicStatsList TopicStatsList
Expand All @@ -548,7 +548,14 @@ func (c *ClusterInfo) GetNSQDStats(producers Producers, selectedTopic string) ([
defer wg.Done()

addr := p.HTTPAddress()
endpoint := fmt.Sprintf("http://%s/stats?format=json", addr)
var endpoint string
if selectedTopic == "" {
endpoint = fmt.Sprintf("http://%s/stats?format=json", addr)
} else if selectChannel == "" {
endpoint = fmt.Sprintf("http://%s/stats?topic=%s&format=json", addr, selectedTopic)
} else {
endpoint = fmt.Sprintf("http://%s/stats?topic=%s&channel=%s&format=json", addr, selectedTopic, selectChannel)
}
c.logf("CI: querying nsqd %s", endpoint)

var resp respType
Expand Down
52 changes: 26 additions & 26 deletions nsqadmin/bindata.go

Large diffs are not rendered by default.

14 changes: 9 additions & 5 deletions nsqadmin/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ func (s *httpServer) topicHandler(w http.ResponseWriter, req *http.Request, ps h
s.ctx.nsqadmin.logf(LOG_WARN, "%s", err)
messages = append(messages, pe.Error())
}
topicStats, _, err := s.ci.GetNSQDStats(producers, topicName)
topicStats, _, err := s.ci.GetNSQDStats(producers, topicName, "")
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
Expand Down Expand Up @@ -291,7 +291,7 @@ func (s *httpServer) channelHandler(w http.ResponseWriter, req *http.Request, ps
s.ctx.nsqadmin.logf(LOG_WARN, "%s", err)
messages = append(messages, pe.Error())
}
_, allChannelStats, err := s.ci.GetNSQDStats(producers, topicName)
_, allChannelStats, err := s.ci.GetNSQDStats(producers, topicName, channelName)
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
Expand Down Expand Up @@ -349,7 +349,7 @@ func (s *httpServer) nodeHandler(w http.ResponseWriter, req *http.Request, ps ht
return nil, http_api.Err{404, "NODE_NOT_FOUND"}
}

topicStats, _, err := s.ci.GetNSQDStats(clusterinfo.Producers{producer}, "")
topicStats, _, err := s.ci.GetNSQDStats(clusterinfo.Producers{producer}, "", "")
if err != nil {
s.ctx.nsqadmin.logf(LOG_ERROR, "failed to get nsqd stats - %s", err)
return nil, http_api.Err{502, fmt.Sprintf("UPSTREAM_ERROR: %s", err)}
Expand All @@ -359,7 +359,11 @@ func (s *httpServer) nodeHandler(w http.ResponseWriter, req *http.Request, ps ht
var totalMessages int64
for _, ts := range topicStats {
for _, cs := range ts.Channels {
totalClients += int64(len(cs.Clients))
if len(cs.Clients) > 0 {
totalClients += int64(len(cs.Clients))
} else {
totalClients += int64(cs.ClientCount)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rather than baking this logic into the client each time, we should just always return client_count as an int, separately from clients (the array).

}
totalMessages += ts.MessageCount
}
Expand Down Expand Up @@ -631,7 +635,7 @@ func (s *httpServer) counterHandler(w http.ResponseWriter, req *http.Request, ps
s.ctx.nsqadmin.logf(LOG_WARN, "%s", err)
messages = append(messages, pe.Error())
}
_, channelStats, err := s.ci.GetNSQDStats(producers, "")
_, channelStats, err := s.ci.GetNSQDStats(producers, "", "")
if err != nil {
pe, ok := err.(clusterinfo.PartialErr)
if !ok {
Expand Down
19 changes: 18 additions & 1 deletion nsqd/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,24 @@ func (s *httpServer) doStats(w http.ResponseWriter, req *http.Request, ps httpro
channelName, _ := reqParams.Get("channel")
jsonFormat := formatString == "json"

stats := s.ctx.nsqd.GetStats()
var (
state TopicStats
stats []TopicStats
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the state variable is awkwardly named, how about we call these stats TopicStats and allStats []TopicStats?

)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor: we don't typically declare variables like this, we instead prefer var for each one.

if topicName == "" {
stats = s.ctx.nsqd.GetStats()
} else if channelName == "" {
state, err = s.ctx.nsqd.GetTopicStats(topicName)
} else {
state, err = s.ctx.nsqd.GetChannelStats(topicName, channelName)
}
if nil != err {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor: we typically prefer the variable in question to be on the left side of the comparison, e.g. if err != nil {

s.ctx.nsqd.logf(LOG_ERROR, "failed to get stats - %s", err)
return nil, http_api.Err{404, "topic/channel is not found"}
} else if nil == stats {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't need to be an else if, because the block above returns. Also, same minor note applies here, please move the variable to the left side of the comparison.

stats = []TopicStats{state}
}

health := s.ctx.nsqd.GetHealth()
startTime := s.ctx.nsqd.GetStartTime()
uptime := time.Since(startTime)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After these changes above, Is any of the topic/channel looping code necessary below this line?

Expand Down
2 changes: 1 addition & 1 deletion nsqd/nsqd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ func TestReconfigure(t *testing.T) {
nsqd.triggerOptsNotification()
test.Equal(t, 2, len(nsqd.getOpts().NSQLookupdTCPAddresses))

time.Sleep(200 * time.Millisecond)
time.Sleep(300 * time.Millisecond)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here may be error, I guess sleep time is too short.

2017-08-10 10 55 40

2017-08-10 10 56 42


var lookupPeers []string
for _, lp := range nsqd.lookupPeers.Load().([]*lookupPeer) {
Expand Down
72 changes: 72 additions & 0 deletions nsqd/stats.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package nsqd

import (
"errors"
"runtime"
"sort"
"sync/atomic"
Expand Down Expand Up @@ -40,6 +41,7 @@ type ChannelStats struct {
DeferredCount int `json:"deferred_count"`
MessageCount uint64 `json:"message_count"`
RequeueCount uint64 `json:"requeue_count"`
ClientCount int `json:"client_count"`
TimeoutCount uint64 `json:"timeout_count"`
Clients []ClientStats `json:"clients"`
Paused bool `json:"paused"`
Expand All @@ -56,6 +58,7 @@ func NewChannelStats(c *Channel, clients []ClientStats) ChannelStats {
DeferredCount: len(c.deferredMessages),
MessageCount: atomic.LoadUint64(&c.messageCount),
RequeueCount: atomic.LoadUint64(&c.requeueCount),
ClientCount: len(c.clients),
TimeoutCount: atomic.LoadUint64(&c.timeoutCount),
Clients: clients,
Paused: c.IsPaused(),
Expand Down Expand Up @@ -145,6 +148,75 @@ func (n *NSQD) GetStats() []TopicStats {
return topics
}

func (n *NSQD) GetTopicStats(topic string) (TopicStats, error) {
n.RLock()
var realTopic *Topic
for _, t := range n.topicMap {
if topic == t.name {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if t.name == topic {

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same applies to function below

realTopic = t
break
}
}
n.RUnlock()

if nil == realTopic {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if realTopic == nil {

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same applies to function below

return TopicStats{}, errors.New("the topic is not found.")
} else {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since the above block returns, we can drop the else and un-indent this block

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same applies to function below

realTopic.RLock()
realChannels := make([]*Channel, 0, len(realTopic.channelMap))
for _, c := range realTopic.channelMap {
realChannels = append(realChannels, c)
}
realTopic.RUnlock()
sort.Sort(ChannelsByName{realChannels})
channels := make([]ChannelStats, 0, len(realChannels))
for _, c := range realChannels {
channels = append(channels, NewChannelStats(c, nil))
}
topics := NewTopicStats(realTopic, channels)
return topics, nil
}
}

func (n *NSQD) GetChannelStats(topic, channel string) (TopicStats, error) {
n.RLock()
var realTopic *Topic
for _, t := range n.topicMap {
if topic == t.name {
realTopic = t
break
}
}
n.RUnlock()

if nil == realTopic {
return TopicStats{}, errors.New("the topic is not found.")
} else {
realTopic.RLock()
realChannels := make([]*Channel, 0, len(realTopic.channelMap))
for _, c := range realTopic.channelMap {
realChannels = append(realChannels, c)
}
realTopic.RUnlock()
sort.Sort(ChannelsByName{realChannels})
channels := make([]ChannelStats, 0, 1)
for _, c := range realChannels {
if c.name == channel {
c.RLock()
clients := make([]ClientStats, 0, len(c.clients))
for _, client := range c.clients {
clients = append(clients, client.Stats())
}
c.RUnlock()
channels = append(channels, NewChannelStats(c, clients))
break
}
}
topics := NewTopicStats(realTopic, channels)
return topics, nil
}
}

type memStats struct {
HeapObjects uint64 `json:"heap_objects"`
HeapIdleBytes uint64 `json:"heap_idle_bytes"`
Expand Down
14 changes: 14 additions & 0 deletions nsqd/stats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,20 @@ func TestStats(t *testing.T) {
test.Equal(t, 1, len(stats))
test.Equal(t, 1, len(stats[0].Channels))
test.Equal(t, 1, len(stats[0].Channels[0].Clients))

topicstat, err := nsqd.GetTopicStats(topicName)
test.Nil(t, err)
t.Logf("topic stats: %+v", topicstat)

test.Equal(t, 1, len(topicstat.Channels))
test.Equal(t, 0, len(topicstat.Channels[0].Clients))

channelstat, err := nsqd.GetChannelStats(topicName, "ch")
test.Nil(t, err)
t.Logf("channel stats: %+v", channelstat)

test.Equal(t, 1, len(channelstat.Channels))
test.Equal(t, 1, len(channelstat.Channels[0].Clients))
}

func TestClientAttributes(t *testing.T) {
Expand Down