swirl/api/system.go

96 lines
2.5 KiB
Go
Raw Normal View History

2021-12-06 12:24:22 +00:00
package api
import (
"context"
"runtime"
"github.com/cuigh/auxo/app"
"github.com/cuigh/auxo/data"
2021-12-16 12:23:08 +00:00
"github.com/cuigh/auxo/errors"
2021-12-06 12:24:22 +00:00
"github.com/cuigh/auxo/net/web"
"github.com/cuigh/swirl/biz"
"github.com/cuigh/swirl/docker"
2021-12-16 12:23:08 +00:00
"github.com/cuigh/swirl/misc"
"github.com/cuigh/swirl/model"
2021-12-06 12:24:22 +00:00
)
// SystemHandler encapsulates system related handlers.
type SystemHandler struct {
CheckState web.HandlerFunc `path:"/check-state" auth:"*" desc:"check system state"`
CreateAdmin web.HandlerFunc `path:"/create-admin" method:"post" auth:"*" desc:"initialize administrator account"`
Version web.HandlerFunc `path:"/version" auth:"*" desc:"fetch app version"`
Summarize web.HandlerFunc `path:"/summarize" auth:"?" desc:"fetch statistics data"`
}
// NewSystem creates an instance of SystemHandler
2021-12-16 12:23:08 +00:00
func NewSystem(d *docker.Docker, b biz.SystemBiz, ub biz.UserBiz) *SystemHandler {
2021-12-06 12:24:22 +00:00
return &SystemHandler{
CheckState: systemCheckState(b),
2021-12-16 12:23:08 +00:00
CreateAdmin: systemCreateAdmin(ub),
2021-12-06 12:24:22 +00:00
Version: systemVersion,
Summarize: systemSummarize(d),
}
}
func systemCheckState(b biz.SystemBiz) web.HandlerFunc {
return func(c web.Context) (err error) {
state, err := b.CheckState()
if err != nil {
return err
}
return success(c, state)
}
}
func systemVersion(c web.Context) (err error) {
return success(c, data.Map{
"version": app.Version,
"goVersion": runtime.Version(),
})
}
func systemSummarize(d *docker.Docker) web.HandlerFunc {
return func(c web.Context) (err error) {
summary := struct {
NodeCount int `json:"nodeCount"`
NetworkCount int `json:"networkCount"`
ServiceCount int `json:"serviceCount"`
StackCount int `json:"stackCount"`
}{}
if summary.NodeCount, err = d.NodeCount(context.TODO()); err != nil {
return
}
if summary.NetworkCount, err = d.NetworkCount(context.TODO()); err != nil {
return
}
if summary.ServiceCount, err = d.ServiceCount(context.TODO()); err != nil {
return
}
if summary.StackCount, err = d.StackCount(context.TODO()); err != nil {
return
}
return success(c, summary)
}
}
2021-12-16 12:23:08 +00:00
func systemCreateAdmin(ub biz.UserBiz) web.HandlerFunc {
2021-12-06 12:24:22 +00:00
return func(c web.Context) (err error) {
2021-12-16 12:23:08 +00:00
user := &model.User{}
if err = c.Bind(user, true); err != nil {
return err
}
var count int
if count, err = ub.Count(); err == nil && count > 0 {
return errors.Coded(misc.ErrSystemInitialized, "system was already initialized")
2021-12-06 12:24:22 +00:00
}
2021-12-16 12:23:08 +00:00
user.Admin = true
user.Type = biz.UserTypeInternal
_, err = ub.Create(user, nil)
2021-12-06 12:24:22 +00:00
return ajax(c, err)
}
}