增加服务流量统计

This commit is contained in:
GoEdgeLab
2021-06-08 11:22:44 +08:00
parent b3d3f251b3
commit 59b11ea07f
16 changed files with 955 additions and 641 deletions

View File

@@ -131,6 +131,10 @@ func (this *RPCClient) ServerHTTPFirewallDailyStatRPC() pb.ServerHTTPFirewallDai
return pb.NewServerHTTPFirewallDailyStatServiceClient(this.pickConn()) return pb.NewServerHTTPFirewallDailyStatServiceClient(this.pickConn())
} }
func (this *RPCClient) ServerDailyStatRPC() pb.ServerDailyStatServiceClient {
return pb.NewServerDailyStatServiceClient(this.pickConn())
}
func (this *RPCClient) ServerGroupRPC() pb.ServerGroupServiceClient { func (this *RPCClient) ServerGroupRPC() pb.ServerGroupServiceClient {
return pb.NewServerGroupServiceClient(this.pickConn()) return pb.NewServerGroupServiceClient(this.pickConn())
} }

View File

@@ -1,12 +1,12 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package stat package stat
import ( import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/iwind/TeaGo/maps" "github.com/iwind/TeaGo/maps"
timeutil "github.com/iwind/TeaGo/utils/time" "sort"
) )
type IndexAction struct { type IndexAction struct {
@@ -20,140 +20,34 @@ func (this *IndexAction) Init() {
func (this *IndexAction) RunGet(params struct { func (this *IndexAction) RunGet(params struct {
ServerId int64 ServerId int64
Month string
}) { }) {
month := params.Month {
if len(month) != 6 { resp, err := this.RPC().ServerDailyStatRPC().FindServerHourlyStats(this.AdminContext(), &pb.FindServerHourlyStatsRequest{
month = timeutil.Format("Ym") ServerId: params.ServerId,
} Hours: 24,
this.Data["month"] = month })
serverTypeResp, err := this.RPC().ServerRPC().FindEnabledServerType(this.AdminContext(), &pb.FindEnabledServerTypeRequest{ServerId: params.ServerId})
if err != nil {
this.ErrorPage(err)
return
}
serverType := serverTypeResp.Type
statIsOn := false
// 是否已开启
if serverconfigs.IsHTTPServerType(serverType) {
webConfig, err := dao.SharedHTTPWebDAO.FindWebConfigWithServerId(this.AdminContext(), params.ServerId)
if err != nil { if err != nil {
this.ErrorPage(err) this.ErrorPage(err)
return return
} }
if webConfig != nil && webConfig.StatRef != nil {
statIsOn = webConfig.StatRef.IsOn
}
} else {
this.WriteString("此类型服务暂不支持统计")
return
}
this.Data["statIsOn"] = statIsOn sort.Slice(resp.Stats, func(i, j int) bool {
stat1 := resp.Stats[i]
// 统计数据 stat2 := resp.Stats[j]
countryStatMaps := []maps.Map{} return stat1.Hour < stat2.Hour
provinceStatMaps := []maps.Map{} })
cityStatMaps := []maps.Map{} statMaps := []maps.Map{}
for _, stat := range resp.Stats {
if statIsOn { statMaps = append(statMaps, maps.Map{
// 地区 "day": stat.Hour[:4] + "-" + stat.Hour[4:6] + "-" + stat.Hour[6:8],
{ "hour": stat.Hour[8:],
resp, err := this.RPC().ServerRegionCountryMonthlyStatRPC().FindTopServerRegionCountryMonthlyStats(this.AdminContext(), &pb.FindTopServerRegionCountryMonthlyStatsRequest{ "bytes": stat.Bytes,
Month: month, "cachedBytes": stat.CachedBytes,
ServerId: params.ServerId, "countRequests": stat.CountRequests,
Offset: 0, "countCachedRequests": stat.CountCachedRequests,
Size: 10,
}) })
if err != nil {
this.ErrorPage(err)
return
}
for _, stat := range resp.Stats {
countryStatMaps = append(countryStatMaps, maps.Map{
"count": stat.Count,
"country": maps.Map{
"id": stat.RegionCountry.Id,
"name": stat.RegionCountry.Name,
},
})
}
} }
this.Data["hourlyStats"] = statMaps
// 省份
{
resp, err := this.RPC().ServerRegionProvinceMonthlyStatRPC().FindTopServerRegionProvinceMonthlyStats(this.AdminContext(), &pb.FindTopServerRegionProvinceMonthlyStatsRequest{
Month: month,
ServerId: params.ServerId,
Offset: 0,
Size: 10,
})
if err != nil {
this.ErrorPage(err)
return
}
for _, stat := range resp.Stats {
provinceStatMaps = append(provinceStatMaps, maps.Map{
"count": stat.Count,
"country": maps.Map{
"id": stat.RegionCountry.Id,
"name": stat.RegionCountry.Name,
},
"province": maps.Map{
"id": stat.RegionProvince.Id,
"name": stat.RegionProvince.Name,
},
})
}
}
// 城市
{
resp, err := this.RPC().ServerRegionCityMonthlyStatRPC().FindTopServerRegionCityMonthlyStats(this.AdminContext(), &pb.FindTopServerRegionCityMonthlyStatsRequest{
Month: month,
ServerId: params.ServerId,
Offset: 0,
Size: 10,
})
if err != nil {
this.ErrorPage(err)
return
}
for _, stat := range resp.Stats {
cityStatMaps = append(cityStatMaps, maps.Map{
"count": stat.Count,
"country": maps.Map{
"id": stat.RegionCountry.Id,
"name": stat.RegionCountry.Name,
},
"province": maps.Map{
"id": stat.RegionProvince.Id,
"name": stat.RegionProvince.Name,
},
"city": maps.Map{
"id": stat.RegionCity.Id,
"name": stat.RegionCity.Name,
},
})
}
}
}
this.Data["countryStats"] = countryStatMaps
this.Data["provinceStats"] = provinceStatMaps
this.Data["cityStats"] = cityStatMaps
// 记录最近使用
_, err = this.RPC().LatestItemRPC().IncreaseLatestItem(this.AdminContext(), &pb.IncreaseLatestItemRequest{
ItemType: "server",
ItemId: params.ServerId,
})
if err != nil {
this.ErrorPage(err)
return
} }
this.Show() this.Show()

View File

@@ -14,6 +14,7 @@ func init() {
Helper(serverutils.NewServerHelper()). Helper(serverutils.NewServerHelper()).
Prefix("/servers/server/stat"). Prefix("/servers/server/stat").
Get("", new(IndexAction)). Get("", new(IndexAction)).
Get("/regions", new(RegionsAction)).
Get("/providers", new(ProvidersAction)). Get("/providers", new(ProvidersAction)).
Get("/clients", new(ClientsAction)). Get("/clients", new(ClientsAction)).
Get("/waf", new(WafAction)). Get("/waf", new(WafAction)).

View File

@@ -0,0 +1,160 @@
package stat
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/dao"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/iwind/TeaGo/maps"
timeutil "github.com/iwind/TeaGo/utils/time"
)
type RegionsAction struct {
actionutils.ParentAction
}
func (this *RegionsAction) Init() {
this.Nav("", "stat", "")
this.SecondMenu("region")
}
func (this *RegionsAction) RunGet(params struct {
ServerId int64
Month string
}) {
month := params.Month
if len(month) != 6 {
month = timeutil.Format("Ym")
}
this.Data["month"] = month
serverTypeResp, err := this.RPC().ServerRPC().FindEnabledServerType(this.AdminContext(), &pb.FindEnabledServerTypeRequest{ServerId: params.ServerId})
if err != nil {
this.ErrorPage(err)
return
}
serverType := serverTypeResp.Type
statIsOn := false
// 是否已开启
if serverconfigs.IsHTTPServerType(serverType) {
webConfig, err := dao.SharedHTTPWebDAO.FindWebConfigWithServerId(this.AdminContext(), params.ServerId)
if err != nil {
this.ErrorPage(err)
return
}
if webConfig != nil && webConfig.StatRef != nil {
statIsOn = webConfig.StatRef.IsOn
}
} else {
this.WriteString("此类型服务暂不支持统计")
return
}
this.Data["statIsOn"] = statIsOn
// 统计数据
countryStatMaps := []maps.Map{}
provinceStatMaps := []maps.Map{}
cityStatMaps := []maps.Map{}
if statIsOn {
// 地区
{
resp, err := this.RPC().ServerRegionCountryMonthlyStatRPC().FindTopServerRegionCountryMonthlyStats(this.AdminContext(), &pb.FindTopServerRegionCountryMonthlyStatsRequest{
Month: month,
ServerId: params.ServerId,
Offset: 0,
Size: 10,
})
if err != nil {
this.ErrorPage(err)
return
}
for _, stat := range resp.Stats {
countryStatMaps = append(countryStatMaps, maps.Map{
"count": stat.Count,
"country": maps.Map{
"id": stat.RegionCountry.Id,
"name": stat.RegionCountry.Name,
},
})
}
}
// 省份
{
resp, err := this.RPC().ServerRegionProvinceMonthlyStatRPC().FindTopServerRegionProvinceMonthlyStats(this.AdminContext(), &pb.FindTopServerRegionProvinceMonthlyStatsRequest{
Month: month,
ServerId: params.ServerId,
Offset: 0,
Size: 10,
})
if err != nil {
this.ErrorPage(err)
return
}
for _, stat := range resp.Stats {
provinceStatMaps = append(provinceStatMaps, maps.Map{
"count": stat.Count,
"country": maps.Map{
"id": stat.RegionCountry.Id,
"name": stat.RegionCountry.Name,
},
"province": maps.Map{
"id": stat.RegionProvince.Id,
"name": stat.RegionProvince.Name,
},
})
}
}
// 城市
{
resp, err := this.RPC().ServerRegionCityMonthlyStatRPC().FindTopServerRegionCityMonthlyStats(this.AdminContext(), &pb.FindTopServerRegionCityMonthlyStatsRequest{
Month: month,
ServerId: params.ServerId,
Offset: 0,
Size: 10,
})
if err != nil {
this.ErrorPage(err)
return
}
for _, stat := range resp.Stats {
cityStatMaps = append(cityStatMaps, maps.Map{
"count": stat.Count,
"country": maps.Map{
"id": stat.RegionCountry.Id,
"name": stat.RegionCountry.Name,
},
"province": maps.Map{
"id": stat.RegionProvince.Id,
"name": stat.RegionProvince.Name,
},
"city": maps.Map{
"id": stat.RegionCity.Id,
"name": stat.RegionCity.Name,
},
})
}
}
}
this.Data["countryStats"] = countryStatMaps
this.Data["provinceStats"] = provinceStatMaps
this.Data["cityStats"] = cityStatMaps
// 记录最近使用
_, err = this.RPC().LatestItemRPC().IncreaseLatestItem(this.AdminContext(), &pb.IncreaseLatestItemRequest{
ItemType: "server",
ItemId: params.ServerId,
})
if err != nil {
this.ErrorPage(err)
return
}
this.Show()
}

View File

@@ -159,10 +159,15 @@ func (this *ServerHelper) createLogMenu(secondMenuItem string, serverIdString st
func (this *ServerHelper) createStatMenu(secondMenuItem string, serverIdString string, serverConfig *serverconfigs.ServerConfig) []maps.Map { func (this *ServerHelper) createStatMenu(secondMenuItem string, serverIdString string, serverConfig *serverconfigs.ServerConfig) []maps.Map {
menuItems := []maps.Map{} menuItems := []maps.Map{}
menuItems = append(menuItems, maps.Map{ menuItems = append(menuItems, maps.Map{
"name": "地域分布", "name": "流量统计",
"url": "/servers/server/stat?serverId=" + serverIdString, "url": "/servers/server/stat?serverId=" + serverIdString,
"isActive": secondMenuItem == "index", "isActive": secondMenuItem == "index",
}) })
menuItems = append(menuItems, maps.Map{
"name": "地域分布",
"url": "/servers/server/stat/regions?serverId=" + serverIdString,
"isActive": secondMenuItem == "region",
})
menuItems = append(menuItems, maps.Map{ menuItems = append(menuItems, maps.Map{
"name": "运营商", "name": "运营商",
"url": "/servers/server/stat/providers?serverId=" + serverIdString, "url": "/servers/server/stat/providers?serverId=" + serverIdString,

View File

@@ -1,302 +1,352 @@
window.teaweb = { window.teaweb = {
set: function (key, value) { set: function (key, value) {
localStorage.setItem(key, JSON.stringify(value)); localStorage.setItem(key, JSON.stringify(value));
}, },
get: function (key) { get: function (key) {
var item = localStorage.getItem(key); var item = localStorage.getItem(key);
if (item == null || item.length == 0) { if (item == null || item.length == 0) {
return null; return null;
} }
return JSON.parse(item); return JSON.parse(item);
}, },
getString: function (key) { getString: function (key) {
var value = this.get(key); var value = this.get(key);
if (typeof (value) == "string") { if (typeof (value) == "string") {
return value; return value;
} }
return ""; return "";
}, },
getBool: function (key) { getBool: function (key) {
return Boolean(this.get(key)); return Boolean(this.get(key));
}, },
remove: function (key) { remove: function (key) {
localStorage.removeItem(key) localStorage.removeItem(key)
}, },
match: function (source, keyword) { match: function (source, keyword) {
if (source == null) { if (source == null) {
return false; return false;
} }
if (keyword == null) { if (keyword == null) {
return true; return true;
} }
source = source.trim(); source = source.trim();
keyword = keyword.trim(); keyword = keyword.trim();
if (keyword.length == 0) { if (keyword.length == 0) {
return true; return true;
} }
if (source.length == 0) { if (source.length == 0) {
return false; return false;
} }
var pieces = keyword.split(/\s+/); var pieces = keyword.split(/\s+/);
for (var i = 0; i < pieces.length; i++) { for (var i = 0; i < pieces.length; i++) {
var pattern = pieces[i]; var pattern = pieces[i];
pattern = pattern.replace(/(\+|\*|\?|[|]|{|}|\||\\|\(|\)|\.)/g, "\\$1"); pattern = pattern.replace(/(\+|\*|\?|[|]|{|}|\||\\|\(|\)|\.)/g, "\\$1");
var reg = new RegExp(pattern, "i"); var reg = new RegExp(pattern, "i");
if (!reg.test(source)) { if (!reg.test(source)) {
return false; return false;
} }
} }
return true; return true;
}, },
loadJS: function (file, callback) { loadJS: function (file, callback) {
let element = document.createElement("script") let element = document.createElement("script")
element.setAttribute("type", "text/javascript") element.setAttribute("type", "text/javascript")
element.setAttribute("src", file) element.setAttribute("src", file)
if (typeof callback == "function") { if (typeof callback == "function") {
element.addEventListener("load", callback) element.addEventListener("load", callback)
} }
document.head.append(element) document.head.append(element)
}, },
loadCSS: function (file, callback) { loadCSS: function (file, callback) {
let element = document.createElement("link") let element = document.createElement("link")
element.setAttribute("rel", "stylesheet") element.setAttribute("rel", "stylesheet")
element.setAttribute("type", "text/css") element.setAttribute("type", "text/css")
element.setAttribute("href", file) element.setAttribute("href", file)
if (typeof callback == "function") { if (typeof callback == "function") {
element.addEventListener("load", callback) element.addEventListener("load", callback)
} }
document.head.append(element) document.head.append(element)
}, },
datepicker: function (element, callback) { datepicker: function (element, callback) {
// 加载 // 加载
if (typeof Pikaday == "undefined") { if (typeof Pikaday == "undefined") {
let that = this let that = this
this.loadJS("/js/moment.min.js") this.loadJS("/js/moment.min.js")
this.loadJS("/js/pikaday.js", function () { this.loadJS("/js/pikaday.js", function () {
that.datepicker(element, callback) that.datepicker(element, callback)
}) })
this.loadCSS("/js/pikaday.css") this.loadCSS("/js/pikaday.css")
this.loadCSS("/js/pikaday.theme.css") this.loadCSS("/js/pikaday.theme.css")
this.loadCSS("/js/pikaday.triangle.css") this.loadCSS("/js/pikaday.triangle.css")
return return
} }
if (typeof (element) == "string") { if (typeof (element) == "string") {
element = document.getElementById(element); element = document.getElementById(element);
} }
var year = new Date().getFullYear(); var year = new Date().getFullYear();
var picker = new Pikaday({ var picker = new Pikaday({
field: element, field: element,
firstDay: 1, firstDay: 1,
minDate: new Date(year - 1, 0, 1), minDate: new Date(year - 1, 0, 1),
maxDate: new Date(year + 10, 11, 31), maxDate: new Date(year + 10, 11, 31),
yearRange: [year - 1, year + 10], yearRange: [year - 1, year + 10],
format: "YYYY-MM-DD", format: "YYYY-MM-DD",
i18n: { i18n: {
previousMonth: '上月', previousMonth: '上月',
nextMonth: '下月', nextMonth: '下月',
months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'], months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
weekdays: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'], weekdays: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
weekdaysShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] weekdaysShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
}, },
theme: 'triangle-theme', theme: 'triangle-theme',
onSelect: function () { onSelect: function () {
if (typeof (callback) == "function") { if (typeof (callback) == "function") {
callback.call(Tea.Vue, picker.toString()); callback.call(Tea.Vue, picker.toString());
} }
} }
}); });
}, },
formatBytes: function (bytes) { formatBytes: function (bytes) {
bytes = Math.ceil(bytes); bytes = Math.ceil(bytes);
if (bytes < 1024) { if (bytes < 1024) {
return bytes + " bytes"; return bytes + "B";
} }
if (bytes < 1024 * 1024) { if (bytes < 1024 * 1024) {
return (Math.ceil(bytes * 100 / 1024) / 100) + " k"; return (Math.ceil(bytes * 100 / 1024) / 100) + "K";
} }
return (Math.ceil(bytes * 100 / 1024 / 1024) / 100) + " m"; if (bytes < 1024 * 1024 * 1024) {
}, return (Math.ceil(bytes * 100 / 1024 / 1024) / 100) + "M";
formatNumber: function (x) { }
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ", "); if (bytes < 1024 * 1024 * 1024 * 1024) {
}, return (Math.ceil(bytes * 100 / 1024 / 1024 / 1024) / 100) + "G";
popup: function (url, options) { }
if (options == null) { if (bytes < 1024 * 1024 * 1024 * 1024 * 1024) {
options = {}; return (Math.ceil(bytes * 100 / 1024 / 1024 / 1024 / 1024) / 100) + "T";
} }
var width = "40em"; return (Math.ceil(bytes * 100 / 1024 / 1024 / 1024 / 1024 / 1024) / 100) + "P";
var height = "20em"; },
window.POPUP_CALLBACK = function () { formatNumber: function (x) {
Swal.close(); return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ", ");
}; },
bytesAxis: function (stats, countFunc) {
let max = Math.max.apply(this, stats.map(countFunc))
let divider = 1
let unit = ""
if (max >= 1024 * 1024 * 1024 * 1024) {
unit = "T"
divider = 1024 * 1024 * 1024 * 1024
} else if (max >= 1024 * 1024 * 1024) {
unit = "G"
divider = 1024 * 1024 * 1024
} else if (max >= 1024 * 1024) {
unit = "M"
divider = 1024 * 1024
} else if (max >= 1024) {
unit = "K"
divider = 1024
}
return {
unit: unit,
divider: divider
}
},
countAxis: function (stats, countFunc) {
let max = Math.max.apply(this, stats.map(countFunc))
let divider = 1
let unit = ""
if (max >= 1000 * 1000 * 1000) {
unit = "B"
divider = 1000 * 1000 * 1000
} else if (max >= 1000 * 1000) {
unit = "M"
divider = 1000 * 1000
} else if (max >= 1000) {
unit = "K"
divider = 1000
}
return {
unit: unit,
divider: divider
}
},
popup: function (url, options) {
if (options == null) {
options = {};
}
var width = "40em";
var height = "20em";
window.POPUP_CALLBACK = function () {
Swal.close();
};
if (options["width"] != null) { if (options["width"] != null) {
width = options["width"]; width = options["width"];
} }
if (options["height"] != null) { if (options["height"] != null) {
height = options["height"]; height = options["height"];
} }
if (typeof (options["callback"]) == "function") { if (typeof (options["callback"]) == "function") {
window.POPUP_CALLBACK = function () { window.POPUP_CALLBACK = function () {
Swal.close(); Swal.close();
options["callback"].apply(Tea.Vue, arguments); options["callback"].apply(Tea.Vue, arguments);
}; };
} }
Swal.fire({ Swal.fire({
html: '<iframe src="' + url + '#popup-' + width + '" style="border:0; width: 100%; height:' + height + '"></iframe>', html: '<iframe src="' + url + '#popup-' + width + '" style="border:0; width: 100%; height:' + height + '"></iframe>',
width: width, width: width,
padding: "0.5em", padding: "0.5em",
showConfirmButton: false, showConfirmButton: false,
showCloseButton: true, showCloseButton: true,
focusConfirm: false, focusConfirm: false,
onClose: function (popup) { onClose: function (popup) {
if (typeof (options["onClose"]) == "function") { if (typeof (options["onClose"]) == "function") {
options["onClose"].apply(Tea.Vue, arguments) options["onClose"].apply(Tea.Vue, arguments)
} }
} }
}); });
}, },
popupFinish: function () { popupFinish: function () {
if (window.POPUP_CALLBACK != null) { if (window.POPUP_CALLBACK != null) {
window.POPUP_CALLBACK.apply(window, arguments); window.POPUP_CALLBACK.apply(window, arguments);
} }
}, },
popupTip: function (html) { popupTip: function (html) {
Swal.fire({ Swal.fire({
html: '<i class="icon question circle"></i><span style="line-height: 1.7">' + html + "</span>", html: '<i class="icon question circle"></i><span style="line-height: 1.7">' + html + "</span>",
width: "30em", width: "30em",
padding: "5em", padding: "5em",
showConfirmButton: false, showConfirmButton: false,
showCloseButton: true, showCloseButton: true,
focusConfirm: false focusConfirm: false
}); });
}, },
isPopup: function () { isPopup: function () {
var hash = window.location.hash; var hash = window.location.hash;
return hash != null && hash.startsWith("#popup"); return hash != null && hash.startsWith("#popup");
}, },
closePopup: function () { closePopup: function () {
if (this.isPopup()) { if (this.isPopup()) {
window.parent.Swal.close(); window.parent.Swal.close();
} }
}, },
Swal: function () { Swal: function () {
return this.isPopup() ? window.parent.Swal : window.Swal; return this.isPopup() ? window.parent.Swal : window.Swal;
}, },
success: function (message, callback) { success: function (message, callback) {
var width = "20em"; var width = "20em";
if (message.length > 30) { if (message.length > 30) {
width = "30em"; width = "30em";
} }
let config = { let config = {
confirmButtonText: "确定", confirmButtonText: "确定",
buttonsStyling: false, buttonsStyling: false,
icon: "success", icon: "success",
customClass: { customClass: {
closeButton: "ui button", closeButton: "ui button",
cancelButton: "ui button", cancelButton: "ui button",
confirmButton: "ui button primary" confirmButton: "ui button primary"
}, },
width: width, width: width,
onAfterClose: function () { onAfterClose: function () {
if (typeof (callback) == "function") { if (typeof (callback) == "function") {
setTimeout(function () { setTimeout(function () {
callback(); callback();
}); });
} else if (typeof (callback) == "string") { } else if (typeof (callback) == "string") {
window.location = callback window.location = callback
} }
} }
} }
if (message.startsWith("html:")) { if (message.startsWith("html:")) {
config.html = message.substring(5) config.html = message.substring(5)
} else { } else {
config.text = message config.text = message
} }
Swal.fire(config); Swal.fire(config);
}, },
successToast: function (message, timeout) { successToast: function (message, timeout) {
if (timeout == null) { if (timeout == null) {
timeout = 2000 timeout = 2000
} }
var width = "20em"; var width = "20em";
if (message.length > 30) { if (message.length > 30) {
width = "30em"; width = "30em";
} }
Swal.fire({ Swal.fire({
text: message, text: message,
icon: "success", icon: "success",
width: width, width: width,
timer: timeout, timer: timeout,
showConfirmButton: false showConfirmButton: false
}); });
}, },
warn: function (message, callback) { warn: function (message, callback) {
var width = "20em"; var width = "20em";
if (message.length > 30) { if (message.length > 30) {
width = "30em"; width = "30em";
} }
Swal.fire({ Swal.fire({
text: message, text: message,
confirmButtonText: "确定", confirmButtonText: "确定",
buttonsStyling: false, buttonsStyling: false,
customClass: { customClass: {
closeButton: "ui button", closeButton: "ui button",
cancelButton: "ui button", cancelButton: "ui button",
confirmButton: "ui button primary" confirmButton: "ui button primary"
}, },
icon: "warning", icon: "warning",
width: width, width: width,
onAfterClose: function () { onAfterClose: function () {
if (typeof (callback) == "function") { if (typeof (callback) == "function") {
setTimeout(function () { setTimeout(function () {
callback(); callback();
}); });
} }
} }
}); });
}, },
confirm: function (message, callback) { confirm: function (message, callback) {
let width = "20em"; let width = "20em";
if (message.length > 30) { if (message.length > 30) {
width = "30em"; width = "30em";
} }
let config = { let config = {
confirmButtonText: "确定", confirmButtonText: "确定",
cancelButtonText: "取消", cancelButtonText: "取消",
showCancelButton: true, showCancelButton: true,
showCloseButton: false, showCloseButton: false,
buttonsStyling: false, buttonsStyling: false,
customClass: { customClass: {
closeButton: "ui button", closeButton: "ui button",
cancelButton: "ui button", cancelButton: "ui button",
confirmButton: "ui button primary" confirmButton: "ui button primary"
}, },
icon: "warning", icon: "warning",
width: width, width: width,
preConfirm: function () { preConfirm: function () {
if (typeof (callback) == "function") { if (typeof (callback) == "function") {
callback.call(Tea.Vue); callback.call(Tea.Vue);
} }
} }
} }
if (message.startsWith("html:")) { if (message.startsWith("html:")) {
config.html = message.substring(5) config.html = message.substring(5)
} else { } else {
config.text = message config.text = message
} }
Swal.fire(config); Swal.fire(config);
}, },
reload: function () { reload: function () {
window.location.reload() window.location.reload()
} }
}; };

View File

@@ -1,4 +1,4 @@
.chart-box { .chart-box {
height: 20em; height: 21em;
} }
/*# sourceMappingURL=index.css.map */ /*# sourceMappingURL=index.css.map */

View File

@@ -7,24 +7,11 @@
{$template "/left_menu"} {$template "/left_menu"}
<div class="right-box"> <div class="right-box">
{$ if eq .statIsOn false} <div class="ui column">
<p class="ui message"> <h4>请求数统计(小时)</h4>
要想查看统计数据,需要先开启统计功能,<a :href="'/servers/server/settings/stat?serverId=' + serverId">[点击这里]</a>修改配置。 <div class="chart-box" id="hourly-requests-chart"></div>
</p>
{$else}
<h4>地区排行</h4>
<div class="chart-box" id="country-chart">
</div> <h4>流量统计(小时)</h4>
<div class="chart-box" id="hourly-traffic-chart"></div>
<h4>省市排行</h4> </div>
<div class="chart-box" id="province-chart">
</div>
<h4>城市排行</h4>
<div class="chart-box" id="city-chart">
</div>
{$end}
</div> </div>

View File

@@ -1,116 +1,195 @@
Tea.context(function () { Tea.context(function () {
this.$delay(function () { this.$delay(function () {
let that = this let that = this
let countryUnit = this.processMaxUnit(this.countryStats) this.reloadRequestsChart("hourly-requests-chart", "请求数统计", this.hourlyStats, function (args) {
this.reloadChart("country-chart", "地区", this.countryStats, function (v) { if (args.seriesIndex == 0) {
return v.country.name return that.hourlyStats[args.dataIndex].day + " " + that.hourlyStats[args.dataIndex].hour + " 请求数: " + teaweb.formatNumber(that.hourlyStats[args.dataIndex].countRequests)
}, function (args) { }
return that.countryStats[args.dataIndex].country.name + ": " + teaweb.formatNumber(that.countryStats[args.dataIndex].rawCount) if (args.seriesIndex == 1) {
}, countryUnit) let ratio = 0
if (that.hourlyStats[args.dataIndex].countRequests > 0) {
ratio = Math.round(that.hourlyStats[args.dataIndex].countCachedRequests * 10000 / that.hourlyStats[args.dataIndex].countRequests) / 100
}
return that.hourlyStats[args.dataIndex].day + " " + that.hourlyStats[args.dataIndex].hour + " 缓存请求数: " + teaweb.formatNumber(that.hourlyStats[args.dataIndex].countCachedRequests) + ", 命中率:" + ratio + "%"
}
return ""
})
this.reloadTrafficChart("hourly-traffic-chart", "流量统计", this.hourlyStats, function (args) {
if (args.seriesIndex == 0) {
return that.hourlyStats[args.dataIndex].day + " " + that.hourlyStats[args.dataIndex].hour + " 流量: " + teaweb.formatBytes(that.hourlyStats[args.dataIndex].bytes)
}
if (args.seriesIndex == 1) {
let ratio = 0
if (that.hourlyStats[args.dataIndex].bytes > 0) {
ratio = Math.round(that.hourlyStats[args.dataIndex].cachedBytes * 10000 / that.hourlyStats[args.dataIndex].bytes) / 100
}
return that.hourlyStats[args.dataIndex].day + " " + that.hourlyStats[args.dataIndex].hour + " 缓存流量: " + teaweb.formatBytes(that.hourlyStats[args.dataIndex].cachedBytes) + ", 命中率:" + ratio + "%"
}
return ""
})
window.addEventListener("resize", function () {
that.resizeChart("hourly-requests-chart")
that.resizeChart("hourly-traffic-chart")
})
})
let provinceUnit = this.processMaxUnit(this.provinceStats) this.reloadRequestsChart = function (chartId, name, stats, tooltipFunc) {
this.reloadChart("province-chart", "省市", this.provinceStats, function (v) { let chartBox = document.getElementById(chartId)
return v.province.name if (chartBox == null) {
}, function (args) { return
return that.provinceStats[args.dataIndex].country.name + ": " + that.provinceStats[args.dataIndex].province.name + " " + teaweb.formatNumber(that.provinceStats[args.dataIndex].rawCount) }
}, provinceUnit)
let cityUnit = this.processMaxUnit(this.cityStats) let axis = teaweb.countAxis(stats, function (v) {
this.reloadChart("city-chart", "城市", this.cityStats, function (v) { return Math.max(v.countRequests, v.countCachedRequests)
return v.city.name })
}, function (args) {
return that.cityStats[args.dataIndex].country.name + ": " + that.cityStats[args.dataIndex].province.name + " " + that.cityStats[args.dataIndex].city.name + " " + teaweb.formatNumber(that.cityStats[args.dataIndex].rawCount)
}, cityUnit)
window.addEventListener("resize", function () { let chart = echarts.init(chartBox)
that.resizeChart("country-chart") let option = {
that.resizeChart("province-chart") xAxis: {
that.resizeChart("city-chart") data: stats.map(function (v) {
}) return v.hour
}) }),
axisLabel: {
interval: 0
}
},
yAxis: {
axisLabel: {
formatter: function (value) {
return value + axis.unit
}
}
},
tooltip: {
show: true,
trigger: "item",
formatter: tooltipFunc
},
grid: {
left: 50,
top: 40,
right: 20,
bottom: 20
},
series: [
{
name: "请求数",
type: "line",
data: stats.map(function (v) {
return v.countRequests / axis.divider
}),
itemStyle: {
color: "#9DD3E8"
},
areaStyle: {
color: "#9DD3E8"
}
},
{
name: "缓存请求数",
type: "line",
data: stats.map(function (v) {
return v.countCachedRequests / axis.divider
}),
itemStyle: {
color: "#61A0A8"
},
areaStyle: {
color: "#61A0A8"
}
}
],
legend: {
data: ['请求数', '缓存请求数']
},
animation: true
}
chart.setOption(option)
chart.resize()
}
this.reloadChart = function (chartId, name, stats, xFunc, tooltipFunc, unit) { this.reloadTrafficChart = function (chartId, name, stats, tooltipFunc) {
let chartBox = document.getElementById(chartId) let chartBox = document.getElementById(chartId)
if (chartBox == null) { if (chartBox == null) {
return return
} }
let chart = echarts.init(chartBox)
let option = {
xAxis: {
data: stats.map(xFunc),
axisLabel: {
interval: 0
}
},
yAxis: {
axisLabel: {
formatter: function (value) {
return value + unit
}
}
},
tooltip: {
show: true,
trigger: "item",
formatter: tooltipFunc
},
grid: {
left: 40,
top: 10,
right: 20,
bottom: 20
},
series: [
{
name: name,
type: "bar",
data: stats.map(function (v) {
return v.count;
}),
itemStyle: {
color: "#9DD3E8"
},
barWidth: "20em"
}
],
animation: true
}
chart.setOption(option)
chart.resize()
}
this.resizeChart = function (chartId) { let axis = teaweb.bytesAxis(stats, function (v) {
let chartBox = document.getElementById(chartId) return Math.max(v.bytes, v.cachedBytes)
if (chartBox == null) { })
return
}
let chart = echarts.init(chartBox)
chart.resize()
}
this.processMaxUnit = function (stats) { let chart = echarts.init(chartBox)
let max = stats.$map(function (k, v) { let option = {
return v.count xAxis: {
}).$max() data: stats.map(function (v) {
let divider = 0 return v.hour
let unit = "" }),
if (max >= 1000 * 1000 * 1000) { axisLabel: {
unit = "B" interval: 0
divider = 1000 * 1000 * 1000 }
} else if (max >= 1000 * 1000) { },
unit = "M" yAxis: {
divider = 1000 * 1000 axisLabel: {
} else if (max >= 1000) { formatter: function (value) {
unit = "K" return value + axis.unit
divider = 1000 }
} }
stats.forEach(function (v) { },
v.rawCount = v.count tooltip: {
if (divider > 0) { show: true,
v.count /= divider trigger: "item",
} formatter: tooltipFunc
}) },
return unit grid: {
} left: 50,
top: 40,
right: 20,
bottom: 20
},
series: [
{
name: "流量",
type: "line",
data: stats.map(function (v) {
return v.bytes / axis.divider
}),
itemStyle: {
color: "#9DD3E8"
},
areaStyle: {
color: "#9DD3E8"
}
},
{
name: "缓存流量",
type: "line",
data: stats.map(function (v) {
return v.cachedBytes / axis.divider
}),
itemStyle: {
color: "#61A0A8"
},
areaStyle: {
color: "#61A0A8"
}
}
],
legend: {
data: ['流量', '缓存流量']
},
animation: true
}
chart.setOption(option)
chart.resize()
}
this.resizeChart = function (chartId) {
let chartBox = document.getElementById(chartId)
if (chartBox == null) {
return
}
let chart = echarts.init(chartBox)
chart.resize()
}
}) })

View File

@@ -1,3 +1,3 @@
.chart-box { .chart-box {
height: 20em; height: 21em;
} }

View File

@@ -1,99 +1,79 @@
Tea.context(function () { Tea.context(function () {
this.$delay(function () { this.$delay(function () {
let that = this let that = this
let providerUnit = this.processMaxUnit(this.providerStats) let axis = teaweb.countAxis(this.providerStats, function (v) {
this.reloadChart("provider-chart", "运营商", this.providerStats, function (v) { return v.count
return v.provider.name })
}, function (args) { this.providerStats.forEach(function (v) {
return that.providerStats[args.dataIndex].provider.name + ": " + teaweb.formatNumber(that.providerStats[args.dataIndex].rawCount) v.count /= axis.divider
}, providerUnit) })
window.addEventListener("resize", function () { this.reloadChart("provider-chart", "运营商", this.providerStats, function (v) {
that.resizeChart("provider-chart") return v.provider.name
}) }, function (args) {
}) return that.providerStats[args.dataIndex].provider.name + ": " + teaweb.formatNumber(that.providerStats[args.dataIndex].rawCount)
}, axis.unit)
window.addEventListener("resize", function () {
that.resizeChart("provider-chart")
})
})
this.reloadChart = function (chartId, name, stats, xFunc, tooltipFunc, unit) { this.reloadChart = function (chartId, name, stats, xFunc, tooltipFunc, unit) {
let chartBox = document.getElementById(chartId) let chartBox = document.getElementById(chartId)
if (chartBox == null) { if (chartBox == null) {
return return
} }
let chart = echarts.init(chartBox) let chart = echarts.init(chartBox)
let option = { let option = {
xAxis: { xAxis: {
data: stats.map(xFunc), data: stats.map(xFunc),
axisLabel: { axisLabel: {
interval: 0 interval: 0
} }
}, },
yAxis: { yAxis: {
axisLabel: { axisLabel: {
formatter: function (value) { formatter: function (value) {
return value + unit return value + unit
} }
} }
}, },
tooltip: { tooltip: {
show: true, show: true,
trigger: "item", trigger: "item",
formatter: tooltipFunc formatter: tooltipFunc
}, },
grid: { grid: {
left: 40, left: 40,
top: 10, top: 10,
right: 20, right: 20,
bottom: 20 bottom: 20
}, },
series: [ series: [
{ {
name: name, name: name,
type: "bar", type: "bar",
data: stats.map(function (v) { data: stats.map(function (v) {
return v.count; return v.count;
}), }),
itemStyle: { itemStyle: {
color: "#9DD3E8" color: "#9DD3E8"
}, },
barWidth: "20em" barWidth: "20em"
} }
], ],
animation: true animation: true
} }
chart.setOption(option) chart.setOption(option)
chart.resize() chart.resize()
} }
this.resizeChart = function (chartId) { this.resizeChart = function (chartId) {
let chartBox = document.getElementById(chartId) let chartBox = document.getElementById(chartId)
if (chartBox == null) { if (chartBox == null) {
return return
} }
let chart = echarts.init(chartBox) let chart = echarts.init(chartBox)
chart.resize() chart.resize()
} }
this.processMaxUnit = function (stats) {
let max = stats.$map(function (k, v) {
return v.count
}).$max()
let divider = 0
let unit = ""
if (max >= 1000 * 1000 * 1000) {
unit = "B"
divider = 1000 * 1000 * 1000
} else if (max >= 1000 * 1000) {
unit = "M"
divider = 1000 * 1000
} else if (max >= 1000) {
unit = "K"
divider = 1000
}
stats.forEach(function (v) {
v.rawCount = v.count
if (divider > 0) {
v.count /= divider
}
})
return unit
}
}) })

View File

@@ -0,0 +1,4 @@
.chart-box {
height: 20em;
}
/*# sourceMappingURL=index.css.map */

View File

@@ -0,0 +1 @@
{"version":3,"sources":["index.less"],"names":[],"mappings":"AAAA;EACC,YAAA","file":"index.css"}

View File

@@ -0,0 +1,30 @@
{$layout}
{$var "header"}
<!-- echart -->
<script type="text/javascript" src="/js/echarts/echarts.min.js"></script>
{$end}
{$template "/left_menu"}
<div class="right-box">
{$ if eq .statIsOn false}
<p class="ui message">
要想查看统计数据,需要先开启统计功能,<a :href="'/servers/server/settings/stat?serverId=' + serverId">[点击这里]</a>修改配置。
</p>
{$else}
<h4>地区排行</h4>
<div class="chart-box" id="country-chart">
</div>
<h4>省市排行</h4>
<div class="chart-box" id="province-chart">
</div>
<h4>城市排行</h4>
<div class="chart-box" id="city-chart">
</div>
{$end}
</div>

View File

@@ -0,0 +1,116 @@
Tea.context(function () {
this.$delay(function () {
let that = this
let countryUnit = this.processMaxUnit(this.countryStats)
this.reloadChart("country-chart", "地区", this.countryStats, function (v) {
return v.country.name
}, function (args) {
return that.countryStats[args.dataIndex].country.name + ": " + teaweb.formatNumber(that.countryStats[args.dataIndex].rawCount)
}, countryUnit)
let provinceUnit = this.processMaxUnit(this.provinceStats)
this.reloadChart("province-chart", "省市", this.provinceStats, function (v) {
return v.province.name
}, function (args) {
return that.provinceStats[args.dataIndex].country.name + ": " + that.provinceStats[args.dataIndex].province.name + " " + teaweb.formatNumber(that.provinceStats[args.dataIndex].rawCount)
}, provinceUnit)
let cityUnit = this.processMaxUnit(this.cityStats)
this.reloadChart("city-chart", "城市", this.cityStats, function (v) {
return v.city.name
}, function (args) {
return that.cityStats[args.dataIndex].country.name + ": " + that.cityStats[args.dataIndex].province.name + " " + that.cityStats[args.dataIndex].city.name + " " + teaweb.formatNumber(that.cityStats[args.dataIndex].rawCount)
}, cityUnit)
window.addEventListener("resize", function () {
that.resizeChart("country-chart")
that.resizeChart("province-chart")
that.resizeChart("city-chart")
})
})
this.reloadChart = function (chartId, name, stats, xFunc, tooltipFunc, unit) {
let chartBox = document.getElementById(chartId)
if (chartBox == null) {
return
}
let chart = echarts.init(chartBox)
let option = {
xAxis: {
data: stats.map(xFunc),
axisLabel: {
interval: 0
}
},
yAxis: {
axisLabel: {
formatter: function (value) {
return value + unit
}
}
},
tooltip: {
show: true,
trigger: "item",
formatter: tooltipFunc
},
grid: {
left: 40,
top: 10,
right: 20,
bottom: 20
},
series: [
{
name: name,
type: "bar",
data: stats.map(function (v) {
return v.count;
}),
itemStyle: {
color: "#9DD3E8"
},
barWidth: "20em"
}
],
animation: true
}
chart.setOption(option)
chart.resize()
}
this.resizeChart = function (chartId) {
let chartBox = document.getElementById(chartId)
if (chartBox == null) {
return
}
let chart = echarts.init(chartBox)
chart.resize()
}
this.processMaxUnit = function (stats) {
let max = stats.$map(function (k, v) {
return v.count
}).$max()
let divider = 0
let unit = ""
if (max >= 1000 * 1000 * 1000) {
unit = "B"
divider = 1000 * 1000 * 1000
} else if (max >= 1000 * 1000) {
unit = "M"
divider = 1000 * 1000
} else if (max >= 1000) {
unit = "K"
divider = 1000
}
stats.forEach(function (v) {
v.rawCount = v.count
if (divider > 0) {
v.count /= divider
}
})
return unit
}
})

View File

@@ -0,0 +1,3 @@
.chart-box {
height: 20em;
}