1
0

admin.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package beego
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "net/http"
  20. "os"
  21. "text/template"
  22. "time"
  23. "reflect"
  24. "github.com/astaxie/beego/grace"
  25. "github.com/astaxie/beego/logs"
  26. "github.com/astaxie/beego/toolbox"
  27. "github.com/astaxie/beego/utils"
  28. )
  29. // BeeAdminApp is the default adminApp used by admin module.
  30. var beeAdminApp *adminApp
  31. // FilterMonitorFunc is default monitor filter when admin module is enable.
  32. // if this func returns, admin module records qbs for this request by condition of this function logic.
  33. // usage:
  34. // func MyFilterMonitor(method, requestPath string, t time.Duration) bool {
  35. // if method == "POST" {
  36. // return false
  37. // }
  38. // if t.Nanoseconds() < 100 {
  39. // return false
  40. // }
  41. // if strings.HasPrefix(requestPath, "/astaxie") {
  42. // return false
  43. // }
  44. // return true
  45. // }
  46. // beego.FilterMonitorFunc = MyFilterMonitor.
  47. var FilterMonitorFunc func(string, string, time.Duration) bool
  48. func init() {
  49. beeAdminApp = &adminApp{
  50. routers: make(map[string]http.HandlerFunc),
  51. }
  52. beeAdminApp.Route("/", adminIndex)
  53. beeAdminApp.Route("/qps", qpsIndex)
  54. beeAdminApp.Route("/prof", profIndex)
  55. beeAdminApp.Route("/healthcheck", healthcheck)
  56. beeAdminApp.Route("/task", taskStatus)
  57. beeAdminApp.Route("/listconf", listConf)
  58. FilterMonitorFunc = func(string, string, time.Duration) bool { return true }
  59. }
  60. // AdminIndex is the default http.Handler for admin module.
  61. // it matches url pattern "/".
  62. func adminIndex(rw http.ResponseWriter, r *http.Request) {
  63. execTpl(rw, map[interface{}]interface{}{}, indexTpl, defaultScriptsTpl)
  64. }
  65. // QpsIndex is the http.Handler for writing qbs statistics map result info in http.ResponseWriter.
  66. // it's registered with url pattern "/qbs" in admin module.
  67. func qpsIndex(rw http.ResponseWriter, r *http.Request) {
  68. data := make(map[interface{}]interface{})
  69. data["Content"] = toolbox.StatisticsMap.GetMap()
  70. execTpl(rw, data, qpsTpl, defaultScriptsTpl)
  71. }
  72. // ListConf is the http.Handler of displaying all beego configuration values as key/value pair.
  73. // it's registered with url pattern "/listconf" in admin module.
  74. func listConf(rw http.ResponseWriter, r *http.Request) {
  75. r.ParseForm()
  76. command := r.Form.Get("command")
  77. if command == "" {
  78. rw.Write([]byte("command not support"))
  79. return
  80. }
  81. data := make(map[interface{}]interface{})
  82. switch command {
  83. case "conf":
  84. m := make(map[string]interface{})
  85. list("BConfig", BConfig, m)
  86. m["AppConfigPath"] = appConfigPath
  87. m["AppConfigProvider"] = appConfigProvider
  88. tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
  89. tmpl = template.Must(tmpl.Parse(configTpl))
  90. tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
  91. data["Content"] = m
  92. tmpl.Execute(rw, data)
  93. case "router":
  94. var (
  95. content = map[string]interface{}{
  96. "Fields": []string{
  97. "Router Pattern",
  98. "Methods",
  99. "Controller",
  100. },
  101. }
  102. methods = []string{}
  103. methodsData = make(map[string]interface{})
  104. )
  105. for method, t := range BeeApp.Handlers.routers {
  106. resultList := new([][]string)
  107. printTree(resultList, t)
  108. methods = append(methods, method)
  109. methodsData[method] = resultList
  110. }
  111. content["Data"] = methodsData
  112. content["Methods"] = methods
  113. data["Content"] = content
  114. data["Title"] = "Routers"
  115. execTpl(rw, data, routerAndFilterTpl, defaultScriptsTpl)
  116. case "filter":
  117. var (
  118. content = map[string]interface{}{
  119. "Fields": []string{
  120. "Router Pattern",
  121. "Filter Function",
  122. },
  123. }
  124. filterTypes = []string{}
  125. filterTypeData = make(map[string]interface{})
  126. )
  127. if BeeApp.Handlers.enableFilter {
  128. var filterType string
  129. for k, fr := range map[int]string{
  130. BeforeStatic: "Before Static",
  131. BeforeRouter: "Before Router",
  132. BeforeExec: "Before Exec",
  133. AfterExec: "After Exec",
  134. FinishRouter: "Finish Router"} {
  135. if bf := BeeApp.Handlers.filters[k]; len(bf) > 0 {
  136. filterType = fr
  137. filterTypes = append(filterTypes, filterType)
  138. resultList := new([][]string)
  139. for _, f := range bf {
  140. var result = []string{
  141. fmt.Sprintf("%s", f.pattern),
  142. fmt.Sprintf("%s", utils.GetFuncName(f.filterFunc)),
  143. }
  144. *resultList = append(*resultList, result)
  145. }
  146. filterTypeData[filterType] = resultList
  147. }
  148. }
  149. }
  150. content["Data"] = filterTypeData
  151. content["Methods"] = filterTypes
  152. data["Content"] = content
  153. data["Title"] = "Filters"
  154. execTpl(rw, data, routerAndFilterTpl, defaultScriptsTpl)
  155. default:
  156. rw.Write([]byte("command not support"))
  157. }
  158. }
  159. func list(root string, p interface{}, m map[string]interface{}) {
  160. pt := reflect.TypeOf(p)
  161. pv := reflect.ValueOf(p)
  162. if pt.Kind() == reflect.Ptr {
  163. pt = pt.Elem()
  164. pv = pv.Elem()
  165. }
  166. for i := 0; i < pv.NumField(); i++ {
  167. var key string
  168. if root == "" {
  169. key = pt.Field(i).Name
  170. } else {
  171. key = root + "." + pt.Field(i).Name
  172. }
  173. if pv.Field(i).Kind() == reflect.Struct {
  174. list(key, pv.Field(i).Interface(), m)
  175. } else {
  176. m[key] = pv.Field(i).Interface()
  177. }
  178. }
  179. }
  180. func printTree(resultList *[][]string, t *Tree) {
  181. for _, tr := range t.fixrouters {
  182. printTree(resultList, tr)
  183. }
  184. if t.wildcard != nil {
  185. printTree(resultList, t.wildcard)
  186. }
  187. for _, l := range t.leaves {
  188. if v, ok := l.runObject.(*controllerInfo); ok {
  189. if v.routerType == routerTypeBeego {
  190. var result = []string{
  191. v.pattern,
  192. fmt.Sprintf("%s", v.methods),
  193. fmt.Sprintf("%s", v.controllerType),
  194. }
  195. *resultList = append(*resultList, result)
  196. } else if v.routerType == routerTypeRESTFul {
  197. var result = []string{
  198. v.pattern,
  199. fmt.Sprintf("%s", v.methods),
  200. "",
  201. }
  202. *resultList = append(*resultList, result)
  203. } else if v.routerType == routerTypeHandler {
  204. var result = []string{
  205. v.pattern,
  206. "",
  207. "",
  208. }
  209. *resultList = append(*resultList, result)
  210. }
  211. }
  212. }
  213. }
  214. // ProfIndex is a http.Handler for showing profile command.
  215. // it's in url pattern "/prof" in admin module.
  216. func profIndex(rw http.ResponseWriter, r *http.Request) {
  217. r.ParseForm()
  218. command := r.Form.Get("command")
  219. if command == "" {
  220. return
  221. }
  222. var (
  223. format = r.Form.Get("format")
  224. data = make(map[interface{}]interface{})
  225. result bytes.Buffer
  226. )
  227. toolbox.ProcessInput(command, &result)
  228. data["Content"] = result.String()
  229. if format == "json" && command == "gc summary" {
  230. dataJSON, err := json.Marshal(data)
  231. if err != nil {
  232. http.Error(rw, err.Error(), http.StatusInternalServerError)
  233. return
  234. }
  235. rw.Header().Set("Content-Type", "application/json")
  236. rw.Write(dataJSON)
  237. return
  238. }
  239. data["Title"] = command
  240. defaultTpl := defaultScriptsTpl
  241. if command == "gc summary" {
  242. defaultTpl = gcAjaxTpl
  243. }
  244. execTpl(rw, data, profillingTpl, defaultTpl)
  245. }
  246. // Healthcheck is a http.Handler calling health checking and showing the result.
  247. // it's in "/healthcheck" pattern in admin module.
  248. func healthcheck(rw http.ResponseWriter, req *http.Request) {
  249. var (
  250. data = make(map[interface{}]interface{})
  251. result = []string{}
  252. resultList = new([][]string)
  253. content = map[string]interface{}{
  254. "Fields": []string{"Name", "Message", "Status"},
  255. }
  256. )
  257. for name, h := range toolbox.AdminCheckList {
  258. if err := h.Check(); err != nil {
  259. result = []string{
  260. fmt.Sprintf("error"),
  261. fmt.Sprintf("%s", name),
  262. fmt.Sprintf("%s", err.Error()),
  263. }
  264. } else {
  265. result = []string{
  266. fmt.Sprintf("success"),
  267. fmt.Sprintf("%s", name),
  268. fmt.Sprintf("OK"),
  269. }
  270. }
  271. *resultList = append(*resultList, result)
  272. }
  273. content["Data"] = resultList
  274. data["Content"] = content
  275. data["Title"] = "Health Check"
  276. execTpl(rw, data, healthCheckTpl, defaultScriptsTpl)
  277. }
  278. // TaskStatus is a http.Handler with running task status (task name, status and the last execution).
  279. // it's in "/task" pattern in admin module.
  280. func taskStatus(rw http.ResponseWriter, req *http.Request) {
  281. data := make(map[interface{}]interface{})
  282. // Run Task
  283. req.ParseForm()
  284. taskname := req.Form.Get("taskname")
  285. if taskname != "" {
  286. if t, ok := toolbox.AdminTaskList[taskname]; ok {
  287. if err := t.Run(); err != nil {
  288. data["Message"] = []string{"error", fmt.Sprintf("%s", err)}
  289. }
  290. data["Message"] = []string{"success", fmt.Sprintf("%s run success,Now the Status is <br>%s", taskname, t.GetStatus())}
  291. } else {
  292. data["Message"] = []string{"warning", fmt.Sprintf("there's no task which named: %s", taskname)}
  293. }
  294. }
  295. // List Tasks
  296. content := make(map[string]interface{})
  297. resultList := new([][]string)
  298. var result = []string{}
  299. var fields = []string{
  300. "Task Name",
  301. "Task Spec",
  302. "Task Status",
  303. "Last Time",
  304. "",
  305. }
  306. for tname, tk := range toolbox.AdminTaskList {
  307. result = []string{
  308. tname,
  309. fmt.Sprintf("%s", tk.GetSpec()),
  310. fmt.Sprintf("%s", tk.GetStatus()),
  311. tk.GetPrev().String(),
  312. }
  313. *resultList = append(*resultList, result)
  314. }
  315. content["Fields"] = fields
  316. content["Data"] = resultList
  317. data["Content"] = content
  318. data["Title"] = "Tasks"
  319. execTpl(rw, data, tasksTpl, defaultScriptsTpl)
  320. }
  321. func execTpl(rw http.ResponseWriter, data map[interface{}]interface{}, tpls ...string) {
  322. tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
  323. for _, tpl := range tpls {
  324. tmpl = template.Must(tmpl.Parse(tpl))
  325. }
  326. tmpl.Execute(rw, data)
  327. }
  328. // adminApp is an http.HandlerFunc map used as beeAdminApp.
  329. type adminApp struct {
  330. routers map[string]http.HandlerFunc
  331. }
  332. // Route adds http.HandlerFunc to adminApp with url pattern.
  333. func (admin *adminApp) Route(pattern string, f http.HandlerFunc) {
  334. admin.routers[pattern] = f
  335. }
  336. // Run adminApp http server.
  337. // Its addr is defined in configuration file as adminhttpaddr and adminhttpport.
  338. func (admin *adminApp) Run() {
  339. if len(toolbox.AdminTaskList) > 0 {
  340. toolbox.StartTask()
  341. }
  342. addr := BConfig.Listen.AdminAddr
  343. if BConfig.Listen.AdminPort != 0 {
  344. addr = fmt.Sprintf("%s:%d", BConfig.Listen.AdminAddr, BConfig.Listen.AdminPort)
  345. }
  346. for p, f := range admin.routers {
  347. http.Handle(p, f)
  348. }
  349. logs.Info("Admin server Running on %s", addr)
  350. var err error
  351. if BConfig.Listen.Graceful {
  352. err = grace.ListenAndServe(addr, nil)
  353. } else {
  354. err = http.ListenAndServe(addr, nil)
  355. }
  356. if err != nil {
  357. logs.Critical("Admin ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid()))
  358. }
  359. }