models/metric: sort for metric result

This commit is contained in:
fatedier 2016-07-18 00:18:40 +08:00
parent 9a3564f29c
commit dee4cbd48c
2 changed files with 17 additions and 10 deletions

View File

@ -16,6 +16,7 @@ package metric
import ( import (
"encoding/json" "encoding/json"
"sort"
"sync" "sync"
"time" "time"
@ -52,22 +53,32 @@ type DailyServerStats struct {
TotalAcceptConns int64 `json:"total_accept_conns"` TotalAcceptConns int64 `json:"total_accept_conns"`
} }
// for sort
type ServerMetricList []*ServerMetric
func (l ServerMetricList) Len() int { return len(l) }
func (l ServerMetricList) Less(i, j int) bool { return l[i].Name < l[j].Name }
func (l ServerMetricList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func init() { func init() {
ServerMetricInfoMap = make(map[string]*ServerMetric) ServerMetricInfoMap = make(map[string]*ServerMetric)
} }
func GetAllProxyMetrics() map[string]*ServerMetric { func GetAllProxyMetrics() []*ServerMetric {
result := make(map[string]*ServerMetric) result := make(ServerMetricList, 0)
smMutex.RLock() smMutex.RLock()
defer smMutex.RUnlock() for _, metric := range ServerMetricInfoMap {
for proxyName, metric := range ServerMetricInfoMap {
metric.mutex.RLock() metric.mutex.RLock()
byteBuf, _ := json.Marshal(metric) byteBuf, _ := json.Marshal(metric)
metric.mutex.RUnlock() metric.mutex.RUnlock()
tmpMetric := &ServerMetric{} tmpMetric := &ServerMetric{}
json.Unmarshal(byteBuf, &tmpMetric) json.Unmarshal(byteBuf, &tmpMetric)
result[proxyName] = tmpMetric result = append(result, tmpMetric)
} }
smMutex.RUnlock()
// sort for result by proxy name
sort.Sort(result)
return result return result
} }

View File

@ -54,15 +54,11 @@ type ProxiesResponse struct {
func apiProxies(c *gin.Context) { func apiProxies(c *gin.Context) {
res := &ProxiesResponse{} res := &ProxiesResponse{}
res.Proxies = make([]*metric.ServerMetric, 0)
defer func() { defer func() {
log.Info("Http response [/api/proxies]: code [%d]", res.Code) log.Info("Http response [/api/proxies]: code [%d]", res.Code)
}() }()
log.Info("Http request: [/api/proxies]") log.Info("Http request: [/api/proxies]")
serverMetricMap := metric.GetAllProxyMetrics() res.Proxies = metric.GetAllProxyMetrics()
for _, metric := range serverMetricMap {
res.Proxies = append(res.Proxies, metric)
}
c.JSON(200, res) c.JSON(200, res)
} }