swirl/biz/chart.go

421 lines
10 KiB
Go
Raw Normal View History

2018-03-22 08:13:54 +00:00
package biz
import (
2021-12-06 12:24:22 +00:00
"context"
"os"
2018-03-22 08:13:54 +00:00
"time"
"github.com/cuigh/auxo/data"
"github.com/cuigh/auxo/errors"
2018-03-22 08:13:54 +00:00
"github.com/cuigh/auxo/log"
"github.com/cuigh/auxo/net/web"
"github.com/cuigh/swirl/dao"
"github.com/cuigh/swirl/model"
2021-12-06 12:24:22 +00:00
"github.com/jinzhu/copier"
2018-03-22 08:13:54 +00:00
)
2021-12-06 12:24:22 +00:00
type ChartBiz interface {
2021-12-16 08:11:16 +00:00
Search(args *model.ChartSearchArgs) (charts []*Chart, total int, err error)
2021-12-06 12:24:22 +00:00
Delete(id, title string, user web.User) (err error)
2021-12-15 12:15:25 +00:00
Find(id string) (chart *Chart, err error)
2021-12-06 12:24:22 +00:00
Batch(ids ...string) (charts []*model.Chart, err error)
2021-12-15 12:15:25 +00:00
Create(chart *Chart, user web.User) (err error)
Update(chart *Chart, user web.User) (err error)
2021-12-06 12:24:22 +00:00
FetchData(key string, ids []string, period time.Duration) (data.Map, error)
FindDashboard(name, key string) (dashboard *Dashboard, err error)
UpdateDashboard(dashboard *model.Dashboard, user web.User) (err error)
}
2018-03-22 08:13:54 +00:00
2021-12-06 12:24:22 +00:00
func NewChart(d dao.Interface, mb MetricBiz, eb EventBiz) ChartBiz {
return &chartBiz{
d: d,
mb: mb,
eb: eb,
builtin: []*model.Chart{
model.NewChart("service", "$cpu", "CPU", "${name}", `rate(container_cpu_user_seconds_total{container_label_com_docker_swarm_service_name="${service}"}[5m]) * 100`, "percent:100", 60),
model.NewChart("service", "$memory", "Memory", "${name}", `container_memory_usage_bytes{container_label_com_docker_swarm_service_name="${service}"}`, "size:bytes", 60),
model.NewChart("service", "$network_in", "Network Receive", "${name}", `sum(irate(container_network_receive_bytes_total{container_label_com_docker_swarm_service_name="${service}"}[5m])) by(name)`, "size:bytes", 60),
model.NewChart("service", "$network_out", "Network Send", "${name}", `sum(irate(container_network_transmit_bytes_total{container_label_com_docker_swarm_service_name="${service}"}[5m])) by(name)`, "size:bytes", 60),
},
}
}
2021-12-06 12:24:22 +00:00
type chartBiz struct {
builtin []*model.Chart
d dao.Interface
mb MetricBiz
eb EventBiz
2018-03-22 08:13:54 +00:00
}
2021-12-16 08:11:16 +00:00
func (b *chartBiz) Search(args *model.ChartSearchArgs) (charts []*Chart, total int, err error) {
2021-12-06 12:24:22 +00:00
var list []*model.Chart
2021-12-16 08:11:16 +00:00
list, total, err = b.d.ChartSearch(context.TODO(), args)
2021-12-06 12:24:22 +00:00
if err == nil {
charts = make([]*Chart, len(list))
for i, c := range list {
charts[i] = newChart(c)
}
}
2018-03-22 08:13:54 +00:00
return
}
2021-12-15 12:15:25 +00:00
func (b *chartBiz) Create(chart *Chart, user web.User) (err error) {
c := &model.Chart{
ID: createId(),
CreatedAt: time.Now(),
2021-12-16 08:11:16 +00:00
CreatedBy: model.Operator{ID: user.ID(), Name: user.Name()},
2021-12-15 12:15:25 +00:00
}
c.UpdatedAt = c.CreatedAt
if err = copier.CopyWithOption(c, chart, copier.Option{IgnoreEmpty: true, DeepCopy: true}); err != nil {
return err
}
err = b.d.ChartCreate(context.TODO(), c)
2021-12-06 12:24:22 +00:00
if err == nil {
2021-12-15 12:15:25 +00:00
b.eb.CreateChart(EventActionCreate, c.ID, c.Title, user)
2021-12-06 12:24:22 +00:00
}
2018-03-22 08:13:54 +00:00
return
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) Delete(id, title string, user web.User) (err error) {
err = b.d.ChartDelete(context.TODO(), id)
if err == nil {
b.eb.CreateChart(EventActionDelete, id, title, user)
}
2018-03-22 08:13:54 +00:00
return
}
2021-12-15 12:15:25 +00:00
func (b *chartBiz) Find(id string) (chart *Chart, err error) {
var c *model.Chart
c, err = b.d.ChartGet(context.TODO(), id)
if err == nil {
chart = newChart(c)
}
2018-03-22 08:13:54 +00:00
return
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) Batch(ids ...string) (charts []*model.Chart, err error) {
2021-12-16 08:11:16 +00:00
charts, err = b.d.ChartGetBatch(context.TODO(), ids...)
return
}
2021-12-15 12:15:25 +00:00
func (b *chartBiz) Update(chart *Chart, user web.User) (err error) {
c := &model.Chart{
UpdatedAt: time.Now(),
}
if err = copier.CopyWithOption(c, chart, copier.Option{IgnoreEmpty: true, DeepCopy: true}); err != nil {
return err
}
2021-12-16 08:11:16 +00:00
c.UpdatedBy.ID = user.ID()
c.UpdatedBy.Name = user.Name()
2021-12-15 12:15:25 +00:00
err = b.d.ChartUpdate(context.TODO(), c)
2021-12-06 12:24:22 +00:00
if err == nil {
b.eb.CreateChart(EventActionUpdate, chart.ID, chart.Title, user)
}
2018-03-22 08:13:54 +00:00
return
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) FindDashboard(name, key string) (dashboard *Dashboard, err error) {
var d *model.Dashboard
d, err = b.d.DashboardGet(context.TODO(), name, key)
if err != nil {
return
}
2018-03-22 08:13:54 +00:00
2021-12-06 12:24:22 +00:00
if d == nil {
dashboard = defaultDashboard(name, key)
} else {
dashboard = newDashboard(d)
}
err = b.fillCharts(dashboard)
2018-03-27 08:32:30 +00:00
return
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) UpdateDashboard(dashboard *model.Dashboard, user web.User) (err error) {
2021-12-16 08:11:16 +00:00
dashboard.UpdatedAt = time.Now()
dashboard.UpdatedBy.ID = user.ID()
dashboard.UpdatedBy.Name = user.Name()
2021-12-06 12:24:22 +00:00
return b.d.DashboardUpdate(context.TODO(), dashboard)
2018-03-27 08:32:30 +00:00
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) FetchData(key string, ids []string, period time.Duration) (data.Map, error) {
if !b.mb.Enabled() {
return data.Map{}, nil
}
2018-03-22 08:13:54 +00:00
2021-12-06 12:24:22 +00:00
charts, err := b.getCharts(ids)
if err != nil {
return nil, err
}
2018-07-04 06:50:19 +00:00
type Data struct {
2021-12-06 12:24:22 +00:00
id string
2018-07-04 06:50:19 +00:00
data interface{}
err error
}
ch := make(chan Data, len(charts))
2018-03-22 08:13:54 +00:00
end := time.Now()
start := end.Add(-period)
for _, chart := range charts {
2018-07-02 09:33:14 +00:00
go func(c *model.Chart) {
2021-12-06 12:24:22 +00:00
d := Data{id: c.ID}
2018-07-02 09:33:14 +00:00
switch c.Type {
case "line", "bar":
2018-07-04 06:50:19 +00:00
d.data, d.err = b.fetchMatrixData(c, key, start, end)
2018-07-02 09:33:14 +00:00
case "pie":
2018-07-04 06:50:19 +00:00
d.data, d.err = b.fetchVectorData(c, key, end)
2018-07-02 09:33:14 +00:00
case "gauge":
2018-07-04 06:50:19 +00:00
d.data, d.err = b.fetchScalarData(c, key, end)
default:
d.err = errors.New("invalid chart type: " + c.Type)
2018-07-02 09:33:14 +00:00
}
2018-07-04 06:50:19 +00:00
ch <- d
2018-07-02 09:33:14 +00:00
}(chart)
}
2018-07-04 06:50:19 +00:00
ds := data.Map{}
for range charts {
d := <-ch
if d.err != nil {
2018-07-24 08:51:32 +00:00
log.Get("metric").Error(d.err)
2018-07-04 06:50:19 +00:00
} else {
2021-12-06 12:24:22 +00:00
ds.Set(d.id, d.data)
2018-07-04 06:50:19 +00:00
}
}
close(ch)
return ds, nil
2018-07-02 09:33:14 +00:00
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) fetchMatrixData(chart *model.Chart, key string, start, end time.Time) (md *MatrixData, err error) {
var (
q string
d *MatrixData
)
2018-07-02 09:33:14 +00:00
for i, m := range chart.Metrics {
2021-12-06 12:24:22 +00:00
q, err = b.formatQuery(m.Query, chart.Dashboard, key)
if err != nil {
return nil, err
}
2021-12-06 12:24:22 +00:00
if d, err = b.mb.GetMatrix(q, m.Legend, start, end); err != nil {
2018-07-02 09:33:14 +00:00
log.Get("metric").Error(err)
} else if i == 0 {
2021-12-06 12:24:22 +00:00
md = d
2018-07-02 09:33:14 +00:00
} else {
2021-12-06 12:24:22 +00:00
md.Legend = append(md.Legend, d.Legend...)
md.Series = append(md.Series, d.Series...)
2018-03-22 08:13:54 +00:00
}
}
2021-12-06 12:24:22 +00:00
return md, nil
2018-07-02 09:33:14 +00:00
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) fetchVectorData(chart *model.Chart, key string, end time.Time) (cvd *VectorData, err error) {
var (
q string
d *VectorData
)
2018-08-21 09:24:07 +00:00
for i, m := range chart.Metrics {
2021-12-06 12:24:22 +00:00
q, err = b.formatQuery(m.Query, chart.Dashboard, key)
2018-08-21 09:24:07 +00:00
if err != nil {
return nil, err
}
2018-07-02 09:33:14 +00:00
2021-12-06 12:24:22 +00:00
if d, err = b.mb.GetVector(q, m.Legend, end); err != nil {
2018-08-21 09:24:07 +00:00
log.Get("metric").Error(err)
} else if i == 0 {
cvd = d
} else {
cvd.Legend = append(cvd.Legend, d.Legend...)
cvd.Data = append(cvd.Data, d.Data...)
}
}
return cvd, nil
2018-03-22 08:13:54 +00:00
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) fetchScalarData(chart *model.Chart, key string, end time.Time) (*VectorValue, error) {
2018-07-02 09:33:14 +00:00
query, err := b.formatQuery(chart.Metrics[0].Query, chart.Dashboard, key)
if err != nil {
2018-07-04 06:50:19 +00:00
return nil, err
}
2021-12-06 12:24:22 +00:00
v, err := b.mb.GetScalar(query, end)
2018-07-04 06:50:19 +00:00
if err != nil {
return nil, err
2018-07-02 09:33:14 +00:00
}
2021-12-06 12:24:22 +00:00
return &VectorValue{
2018-07-04 06:50:19 +00:00
//Name: "",
Value: v,
}, nil
2018-07-02 09:33:14 +00:00
}
func (b *chartBiz) formatQuery(query, dashboard, key string) (string, error) {
if dashboard == "home" {
return query, nil
}
var errs []error
2018-07-02 09:33:14 +00:00
m := map[string]string{dashboard: key}
q := os.Expand(query, func(k string) string {
if v, ok := m[k]; ok {
return v
}
2018-07-02 09:33:14 +00:00
errs = append(errs, errors.New("invalid argument in query: "+query))
return ""
})
if len(errs) == 0 {
2018-07-02 09:33:14 +00:00
return q, nil
}
return "", errs[0]
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) getCharts(ids []string) (charts map[string]*model.Chart, err error) {
var (
2021-12-06 12:24:22 +00:00
customIds []string
customCharts []*model.Chart
)
2021-12-06 12:24:22 +00:00
charts = make(map[string]*model.Chart)
for _, id := range ids {
if id[0] == '$' {
for _, c := range b.builtin {
2021-12-06 12:24:22 +00:00
if c.ID == id {
charts[id] = c
}
}
} else {
2021-12-06 12:24:22 +00:00
customIds = append(customIds, id)
}
}
2021-12-06 12:24:22 +00:00
if len(customIds) > 0 {
if customCharts, err = b.Batch(customIds...); err == nil {
for _, chart := range customCharts {
charts[chart.ID] = chart
}
}
}
return
}
2021-12-06 12:24:22 +00:00
func (b *chartBiz) fillCharts(d *Dashboard) (err error) {
if len(d.Charts) == 0 {
return
}
var (
m map[string]*model.Chart
ids = make([]string, len(d.Charts))
)
for i, c := range d.Charts {
ids[i] = c.ID
}
m, err = b.getCharts(ids)
if err != nil {
return err
}
for _, info := range d.Charts {
if c := m[info.ID]; c != nil {
info.Type = c.Type
info.Title = c.Title
info.Unit = c.Unit
if info.Width == 0 {
info.Width = c.Width
}
if info.Height == 0 {
info.Height = c.Height
}
info.Margin.Left = c.Margin.Left
info.Margin.Right = c.Margin.Right
info.Margin.Top = c.Margin.Top
info.Margin.Bottom = c.Margin.Bottom
}
}
return nil
}
type Dashboard struct {
Name string `json:"name"`
Key string `json:"key,omitempty"`
Period int32 `json:"period,omitempty"` // data range in minutes
Interval int32 `json:"interval,omitempty"` // refresh interval in seconds, 0 means disabled.
Charts []*Chart `json:"charts,omitempty"`
}
type Chart struct {
ID string `json:"id"`
Title string `json:"title" valid:"required"`
Description string `json:"desc,omitempty"`
Dashboard string `json:"dashboard,omitempty"`
Type string `json:"type" valid:"required"`
Unit string `json:"unit"`
Width int32 `json:"width" valid:"required"`
Height int32 `json:"height" valid:"required"`
Margin struct {
Left int32 `json:"left,omitempty"`
Right int32 `json:"right,omitempty"`
Top int32 `json:"top,omitempty"`
Bottom int32 `json:"bottom,omitempty"`
} `json:"margin"`
Metrics []model.ChartMetric `json:"metrics" valid:"required"`
Options data.Map `json:"options,omitempty"`
CreatedAt string `json:"createdAt,omitempty" copier:"-"`
UpdatedAt string `json:"updatedAt,omitempty" copier:"-"`
2021-12-16 08:11:16 +00:00
CreatedBy model.Operator `json:"createdBy"`
UpdatedBy model.Operator `json:"updatedBy"`
2021-12-06 12:24:22 +00:00
}
func newChart(c *model.Chart) *Chart {
chart := &Chart{
CreatedAt: formatTime(c.CreatedAt),
UpdatedAt: formatTime(c.UpdatedAt),
}
if err := copier.CopyWithOption(chart, c, copier.Option{IgnoreEmpty: true, DeepCopy: true}); err != nil {
panic(err)
}
return chart
}
func defaultDashboard(name, key string) *Dashboard {
d := &Dashboard{
Name: name,
Key: key,
Period: 30,
Interval: 15,
}
if name == "service" {
d.Charts = []*Chart{
{ID: "$cpu"},
{ID: "$memory"},
{ID: "$network_in"},
{ID: "$network_out"},
}
}
return d
}
func newDashboard(d *model.Dashboard) *Dashboard {
dashboard := &Dashboard{
Name: d.Name,
Key: d.Key,
Period: d.Period,
Interval: d.Interval,
}
if len(d.Charts) > 0 {
dashboard.Charts = make([]*Chart, len(d.Charts))
for i, c := range d.Charts {
dashboard.Charts[i] = &Chart{
ID: c.ID,
Width: c.Width,
Height: c.Height,
}
}
}
return dashboard
}