1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-16 19:10:55 +00:00
Beego/admin.go

459 lines
12 KiB
Go
Raw Normal View History

2014-08-18 08:41:43 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
//
2014-08-18 08:41:43 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
2014-08-18 08:41:43 +00:00
// http://www.apache.org/licenses/LICENSE-2.0
//
2014-08-18 08:41:43 +00:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package beego
import (
2014-08-14 09:35:23 +00:00
"bytes"
2014-08-15 06:24:55 +00:00
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"strconv"
2014-08-14 09:35:23 +00:00
"text/template"
2013-11-15 10:08:53 +00:00
"time"
2013-12-03 13:37:39 +00:00
2020-06-21 03:43:54 +00:00
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/astaxie/beego/grace"
"github.com/astaxie/beego/logs"
2013-12-03 13:37:39 +00:00
"github.com/astaxie/beego/toolbox"
2013-12-15 13:44:58 +00:00
"github.com/astaxie/beego/utils"
)
2014-04-05 17:02:10 +00:00
// BeeAdminApp is the default adminApp used by admin module.
var beeAdminApp *adminApp
2013-12-19 15:46:06 +00:00
// FilterMonitorFunc is default monitor filter when admin module is enable.
2018-10-24 02:38:59 +00:00
// if this func returns, admin module records qps for this request by condition of this function logic.
2013-12-19 15:46:06 +00:00
// usage:
// func MyFilterMonitor(method, requestPath string, t time.Duration, pattern string, statusCode int) bool {
2013-12-19 15:46:06 +00:00
// if method == "POST" {
// return false
// }
// if t.Nanoseconds() < 100 {
// return false
// }
// if strings.HasPrefix(requestPath, "/astaxie") {
// return false
// }
// return true
// }
// beego.FilterMonitorFunc = MyFilterMonitor.
2017-06-05 23:21:31 +00:00
var FilterMonitorFunc func(string, string, time.Duration, string, int) bool
2013-11-15 10:08:53 +00:00
func init() {
2014-04-05 17:02:10 +00:00
beeAdminApp = &adminApp{
routers: make(map[string]http.HandlerFunc),
}
// keep in mind that all data should be html escaped to avoid XSS attack
2014-04-05 17:02:10 +00:00
beeAdminApp.Route("/", adminIndex)
beeAdminApp.Route("/qps", qpsIndex)
beeAdminApp.Route("/prof", profIndex)
beeAdminApp.Route("/healthcheck", healthcheck)
beeAdminApp.Route("/task", taskStatus)
beeAdminApp.Route("/listconf", listConf)
2020-06-21 03:43:54 +00:00
beeAdminApp.Route("/metrics", promhttp.Handler().ServeHTTP)
2017-06-05 23:21:31 +00:00
FilterMonitorFunc = func(string, string, time.Duration, string, int) bool { return true }
}
2013-12-19 15:46:06 +00:00
// AdminIndex is the default http.Handler for admin module.
// it matches url pattern "/".
func adminIndex(rw http.ResponseWriter, _ *http.Request) {
2020-07-07 13:54:21 +00:00
writeTemplate(rw, map[interface{}]interface{}{}, indexTpl, defaultScriptsTpl)
}
2018-10-24 02:38:59 +00:00
// QpsIndex is the http.Handler for writing qps statistics map result info in http.ResponseWriter.
// it's registered with url pattern "/qps" in admin module.
func qpsIndex(rw http.ResponseWriter, _ *http.Request) {
2014-08-14 09:35:23 +00:00
data := make(map[interface{}]interface{})
data["Content"] = toolbox.StatisticsMap.GetMap()
// do html escape before display path, avoid xss
if content, ok := (data["Content"]).(M); ok {
if resultLists, ok := (content["Data"]).([][]string); ok {
for i := range resultLists {
if len(resultLists[i]) > 0 {
resultLists[i][0] = template.HTMLEscapeString(resultLists[i][0])
}
}
}
}
2020-07-07 13:54:21 +00:00
writeTemplate(rw, data, qpsTpl, defaultScriptsTpl)
2013-11-15 10:08:53 +00:00
}
2013-12-19 15:46:06 +00:00
// ListConf is the http.Handler of displaying all beego configuration values as key/value pair.
// it's registered with url pattern "/listconf" in admin module.
2014-04-05 17:02:10 +00:00
func listConf(rw http.ResponseWriter, r *http.Request) {
2013-12-15 13:22:50 +00:00
r.ParseForm()
command := r.Form.Get("command")
if command == "" {
rw.Write([]byte("command not support"))
return
}
2014-08-14 09:35:23 +00:00
data := make(map[interface{}]interface{})
switch command {
case "conf":
m := make(M)
2016-04-18 11:16:39 +00:00
list("BConfig", BConfig, m)
m["AppConfigPath"] = template.HTMLEscapeString(appConfigPath)
m["AppConfigProvider"] = template.HTMLEscapeString(appConfigProvider)
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
tmpl = template.Must(tmpl.Parse(configTpl))
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
2016-01-07 17:40:19 +00:00
data["Content"] = m
tmpl.Execute(rw, data)
case "router":
content := PrintTree()
content["Fields"] = []string{
"Router Pattern",
"Methods",
"Controller",
}
data["Content"] = content
data["Title"] = "Routers"
2020-07-07 13:54:21 +00:00
writeTemplate(rw, data, routerAndFilterTpl, defaultScriptsTpl)
case "filter":
var (
content = M{
"Fields": []string{
"Router Pattern",
"Filter Function",
},
2014-08-14 09:35:23 +00:00
}
filterTypes = []string{}
filterTypeData = make(M)
)
if BeeApp.Handlers.enableFilter {
var filterType string
for k, fr := range map[int]string{
BeforeStatic: "Before Static",
BeforeRouter: "Before Router",
BeforeExec: "Before Exec",
AfterExec: "After Exec",
FinishRouter: "Finish Router"} {
2016-03-15 03:49:23 +00:00
if bf := BeeApp.Handlers.filters[k]; len(bf) > 0 {
filterType = fr
filterTypes = append(filterTypes, filterType)
resultList := new([][]string)
for _, f := range bf {
var result = []string{
// void xss
template.HTMLEscapeString(f.pattern),
template.HTMLEscapeString(utils.GetFuncName(f.filterFunc)),
2014-08-14 09:35:23 +00:00
}
*resultList = append(*resultList, result)
2013-12-15 13:22:50 +00:00
}
filterTypeData[filterType] = resultList
2013-12-15 13:22:50 +00:00
}
}
}
2014-08-24 17:37:11 +00:00
content["Data"] = filterTypeData
content["Methods"] = filterTypes
2014-08-24 17:37:11 +00:00
data["Content"] = content
data["Title"] = "Filters"
2020-07-07 13:54:21 +00:00
writeTemplate(rw, data, routerAndFilterTpl, defaultScriptsTpl)
default:
rw.Write([]byte("command not support"))
2013-12-15 13:22:50 +00:00
}
}
func list(root string, p interface{}, m M) {
2016-04-18 11:16:39 +00:00
pt := reflect.TypeOf(p)
pv := reflect.ValueOf(p)
if pt.Kind() == reflect.Ptr {
pt = pt.Elem()
pv = pv.Elem()
}
for i := 0; i < pv.NumField(); i++ {
var key string
if root == "" {
key = pt.Field(i).Name
} else {
key = root + "." + pt.Field(i).Name
}
if pv.Field(i).Kind() == reflect.Struct {
list(key, pv.Field(i).Interface(), m)
} else {
m[key] = pv.Field(i).Interface()
}
}
}
// PrintTree prints all registered routers.
func PrintTree() M {
var (
content = M{}
methods = []string{}
methodsData = make(M)
)
for method, t := range BeeApp.Handlers.routers {
resultList := new([][]string)
printTree(resultList, t)
methods = append(methods, template.HTMLEscapeString(method))
methodsData[template.HTMLEscapeString(method)] = resultList
}
content["Data"] = methodsData
content["Methods"] = methods
return content
}
2014-08-14 09:35:23 +00:00
func printTree(resultList *[][]string, t *Tree) {
2014-06-12 16:08:43 +00:00
for _, tr := range t.fixrouters {
2014-08-14 09:35:23 +00:00
printTree(resultList, tr)
2014-06-12 16:08:43 +00:00
}
if t.wildcard != nil {
2014-08-14 09:35:23 +00:00
printTree(resultList, t.wildcard)
2014-06-12 16:08:43 +00:00
}
for _, l := range t.leaves {
if v, ok := l.runObject.(*ControllerInfo); ok {
2014-06-12 16:08:43 +00:00
if v.routerType == routerTypeBeego {
2014-08-14 09:35:23 +00:00
var result = []string{
template.HTMLEscapeString(v.pattern),
template.HTMLEscapeString(fmt.Sprintf("%s", v.methods)),
template.HTMLEscapeString(v.controllerType.String()),
2014-08-14 09:35:23 +00:00
}
*resultList = append(*resultList, result)
2014-06-12 16:08:43 +00:00
} else if v.routerType == routerTypeRESTFul {
2014-08-14 09:35:23 +00:00
var result = []string{
template.HTMLEscapeString(v.pattern),
template.HTMLEscapeString(fmt.Sprintf("%s", v.methods)),
"",
2014-08-14 09:35:23 +00:00
}
*resultList = append(*resultList, result)
2014-06-12 16:08:43 +00:00
} else if v.routerType == routerTypeHandler {
2014-08-14 09:35:23 +00:00
var result = []string{
template.HTMLEscapeString(v.pattern),
"",
"",
2014-08-14 09:35:23 +00:00
}
*resultList = append(*resultList, result)
2014-06-12 16:08:43 +00:00
}
}
}
}
2013-12-19 15:46:06 +00:00
// ProfIndex is a http.Handler for showing profile command.
// it's in url pattern "/prof" in admin module.
2014-04-05 17:02:10 +00:00
func profIndex(rw http.ResponseWriter, r *http.Request) {
2013-11-15 10:08:53 +00:00
r.ParseForm()
command := r.Form.Get("command")
if command == "" {
return
}
2014-08-15 06:24:55 +00:00
var (
format = r.Form.Get("format")
data = make(map[interface{}]interface{})
result bytes.Buffer
)
toolbox.ProcessInput(command, &result)
data["Content"] = template.HTMLEscapeString(result.String())
if format == "json" && command == "gc summary" {
dataJSON, err := json.Marshal(data)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
2014-08-15 06:24:55 +00:00
return
}
2020-07-07 13:54:21 +00:00
writeJSON(rw, dataJSON)
return
}
data["Title"] = template.HTMLEscapeString(command)
defaultTpl := defaultScriptsTpl
if command == "gc summary" {
defaultTpl = gcAjaxTpl
2013-11-15 10:08:53 +00:00
}
2020-07-07 13:54:21 +00:00
writeTemplate(rw, data, profillingTpl, defaultTpl)
2013-11-15 10:08:53 +00:00
}
2013-12-19 15:46:06 +00:00
// Healthcheck is a http.Handler calling health checking and showing the result.
// it's in "/healthcheck" pattern in admin module.
func healthcheck(rw http.ResponseWriter, r *http.Request) {
var (
result []string
data = make(map[interface{}]interface{})
resultList = new([][]string)
content = M{
"Fields": []string{"Name", "Message", "Status"},
}
)
2014-08-14 09:35:23 +00:00
2013-12-15 13:22:50 +00:00
for name, h := range toolbox.AdminCheckList {
if err := h.Check(); err != nil {
2014-08-14 09:35:23 +00:00
result = []string{
2017-03-17 17:24:45 +00:00
"error",
template.HTMLEscapeString(name),
template.HTMLEscapeString(err.Error()),
2014-08-14 09:35:23 +00:00
}
2014-05-23 07:56:25 +00:00
} else {
2014-08-14 09:35:23 +00:00
result = []string{
2017-03-17 17:24:45 +00:00
"success",
template.HTMLEscapeString(name),
2017-03-17 17:24:45 +00:00
"OK",
2014-08-14 09:35:23 +00:00
}
2013-12-15 13:22:50 +00:00
}
2014-08-14 09:35:23 +00:00
*resultList = append(*resultList, result)
2013-12-15 13:22:50 +00:00
}
queryParams := r.URL.Query()
jsonFlag := queryParams.Get("json")
shouldReturnJSON, _ := strconv.ParseBool(jsonFlag)
if shouldReturnJSON {
response := buildHealthCheckResponseList(resultList)
jsonResponse, err := json.Marshal(response)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
} else {
writeJSON(rw, jsonResponse)
}
return
}
2014-08-24 17:37:11 +00:00
content["Data"] = resultList
data["Content"] = content
2014-08-14 09:35:23 +00:00
data["Title"] = "Health Check"
2020-07-07 13:54:21 +00:00
writeTemplate(rw, data, healthCheckTpl, defaultScriptsTpl)
2013-12-15 13:22:50 +00:00
}
func buildHealthCheckResponseList(healthCheckResults *[][]string) []map[string]interface{} {
response := make([]map[string]interface{}, len(*healthCheckResults))
for i, healthCheckResult := range *healthCheckResults {
currentResultMap := make(map[string]interface{})
currentResultMap["name"] = healthCheckResult[0]
currentResultMap["message"] = healthCheckResult[1]
currentResultMap["status"] = healthCheckResult[2]
response[i] = currentResultMap
}
return response
}
2020-07-07 13:54:21 +00:00
func writeJSON(rw http.ResponseWriter, jsonData []byte) {
rw.Header().Set("Content-Type", "application/json")
rw.Write(jsonData)
}
2013-12-19 15:46:06 +00:00
// TaskStatus is a http.Handler with running task status (task name, status and the last execution).
// it's in "/task" pattern in admin module.
2014-04-05 17:02:10 +00:00
func taskStatus(rw http.ResponseWriter, req *http.Request) {
2014-08-14 09:35:23 +00:00
data := make(map[interface{}]interface{})
2013-12-15 13:22:50 +00:00
2014-08-14 09:35:23 +00:00
// Run Task
2013-12-15 13:22:50 +00:00
req.ParseForm()
taskname := req.Form.Get("taskname")
2014-08-14 09:35:23 +00:00
if taskname != "" {
if t, ok := toolbox.AdminTaskList[taskname]; ok {
if err := t.Run(); err != nil {
data["Message"] = []string{"error", template.HTMLEscapeString(fmt.Sprintf("%s", err))}
2014-08-14 09:35:23 +00:00
}
data["Message"] = []string{"success", template.HTMLEscapeString(fmt.Sprintf("%s run success,Now the Status is <br>%s", taskname, t.GetStatus()))}
2014-08-14 09:35:23 +00:00
} else {
data["Message"] = []string{"warning", template.HTMLEscapeString(fmt.Sprintf("there's no task which named: %s", taskname))}
2013-12-15 13:22:50 +00:00
}
}
2014-08-14 09:35:23 +00:00
// List Tasks
content := make(M)
2014-08-14 09:35:23 +00:00
resultList := new([][]string)
2014-08-24 17:37:11 +00:00
var fields = []string{
"Task Name",
"Task Spec",
"Task Status",
"Last Time",
"",
2014-08-14 09:35:23 +00:00
}
for tname, tk := range toolbox.AdminTaskList {
result := []string{
template.HTMLEscapeString(tname),
template.HTMLEscapeString(tk.GetSpec()),
template.HTMLEscapeString(tk.GetStatus()),
template.HTMLEscapeString(tk.GetPrev().String()),
2014-08-14 09:35:23 +00:00
}
*resultList = append(*resultList, result)
}
2014-08-24 17:37:11 +00:00
content["Fields"] = fields
content["Data"] = resultList
data["Content"] = content
2014-08-14 09:35:23 +00:00
data["Title"] = "Tasks"
2020-07-07 13:54:21 +00:00
writeTemplate(rw, data, tasksTpl, defaultScriptsTpl)
2015-09-19 12:05:57 +00:00
}
2020-07-07 13:54:21 +00:00
func writeTemplate(rw http.ResponseWriter, data map[interface{}]interface{}, tpls ...string) {
2014-08-14 09:35:23 +00:00
tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
2015-09-19 12:05:57 +00:00
for _, tpl := range tpls {
tmpl = template.Must(tmpl.Parse(tpl))
}
2014-08-14 09:35:23 +00:00
tmpl.Execute(rw, data)
2013-12-15 13:22:50 +00:00
}
2014-04-05 17:02:10 +00:00
// adminApp is an http.HandlerFunc map used as beeAdminApp.
type adminApp struct {
routers map[string]http.HandlerFunc
}
2014-04-05 17:02:10 +00:00
// Route adds http.HandlerFunc to adminApp with url pattern.
func (admin *adminApp) Route(pattern string, f http.HandlerFunc) {
admin.routers[pattern] = f
}
2014-04-05 17:02:10 +00:00
// Run adminApp http server.
2013-12-19 15:46:06 +00:00
// Its addr is defined in configuration file as adminhttpaddr and adminhttpport.
2014-04-05 17:02:10 +00:00
func (admin *adminApp) Run() {
2013-11-20 15:53:54 +00:00
if len(toolbox.AdminTaskList) > 0 {
toolbox.StartTask()
}
2015-12-09 15:35:04 +00:00
addr := BConfig.Listen.AdminAddr
2015-12-09 15:35:04 +00:00
if BConfig.Listen.AdminPort != 0 {
addr = fmt.Sprintf("%s:%d", BConfig.Listen.AdminAddr, BConfig.Listen.AdminPort)
}
for p, f := range admin.routers {
http.Handle(p, f)
}
logs.Info("Admin server Running on %s", addr)
var err error
2015-12-09 15:35:04 +00:00
if BConfig.Listen.Graceful {
err = grace.ListenAndServe(addr, nil)
} else {
err = http.ListenAndServe(addr, nil)
}
if err != nil {
logs.Critical("Admin ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid()))
}
}