gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package admin
  5. import (
  6. "fmt"
  7. "net/http"
  8. "runtime"
  9. "sort"
  10. "strings"
  11. "time"
  12. activities_model "code.gitea.io/gitea/models/activities"
  13. "code.gitea.io/gitea/models/db"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/cache"
  16. "code.gitea.io/gitea/modules/graceful"
  17. "code.gitea.io/gitea/modules/httplib"
  18. "code.gitea.io/gitea/modules/json"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/templates"
  22. "code.gitea.io/gitea/modules/updatechecker"
  23. "code.gitea.io/gitea/modules/web"
  24. "code.gitea.io/gitea/services/context"
  25. "code.gitea.io/gitea/services/cron"
  26. "code.gitea.io/gitea/services/forms"
  27. release_service "code.gitea.io/gitea/services/release"
  28. repo_service "code.gitea.io/gitea/services/repository"
  29. )
  30. const (
  31. tplDashboard templates.TplName = "admin/dashboard"
  32. tplSystemStatus templates.TplName = "admin/system_status"
  33. tplSelfCheck templates.TplName = "admin/self_check"
  34. tplCron templates.TplName = "admin/cron"
  35. tplQueue templates.TplName = "admin/queue"
  36. tplPerfTrace templates.TplName = "admin/perftrace"
  37. tplStacktrace templates.TplName = "admin/stacktrace"
  38. tplQueueManage templates.TplName = "admin/queue_manage"
  39. tplStats templates.TplName = "admin/stats"
  40. )
  41. var sysStatus struct {
  42. StartTime string
  43. NumGoroutine int
  44. // General statistics.
  45. MemAllocated string // bytes allocated and still in use
  46. MemTotal string // bytes allocated (even if freed)
  47. MemSys string // bytes obtained from system (sum of XxxSys below)
  48. Lookups uint64 // number of pointer lookups
  49. MemMallocs uint64 // number of mallocs
  50. MemFrees uint64 // number of frees
  51. // Main allocation heap statistics.
  52. HeapAlloc string // bytes allocated and still in use
  53. HeapSys string // bytes obtained from system
  54. HeapIdle string // bytes in idle spans
  55. HeapInuse string // bytes in non-idle span
  56. HeapReleased string // bytes released to the OS
  57. HeapObjects uint64 // total number of allocated objects
  58. // Low-level fixed-size structure allocator statistics.
  59. // Inuse is bytes used now.
  60. // Sys is bytes obtained from system.
  61. StackInuse string // bootstrap stacks
  62. StackSys string
  63. MSpanInuse string // mspan structures
  64. MSpanSys string
  65. MCacheInuse string // mcache structures
  66. MCacheSys string
  67. BuckHashSys string // profiling bucket hash table
  68. GCSys string // GC metadata
  69. OtherSys string // other system allocations
  70. // Garbage collector statistics.
  71. NextGC string // next run in HeapAlloc time (bytes)
  72. LastGCTime string // last run time
  73. PauseTotalNs string
  74. PauseNs string // circular buffer of recent GC pause times, most recent at [(NumGC+255)%256]
  75. NumGC uint32
  76. }
  77. func updateSystemStatus() {
  78. sysStatus.StartTime = setting.AppStartTime.Format(time.RFC3339)
  79. m := new(runtime.MemStats)
  80. runtime.ReadMemStats(m)
  81. sysStatus.NumGoroutine = runtime.NumGoroutine()
  82. sysStatus.MemAllocated = base.FileSize(int64(m.Alloc))
  83. sysStatus.MemTotal = base.FileSize(int64(m.TotalAlloc))
  84. sysStatus.MemSys = base.FileSize(int64(m.Sys))
  85. sysStatus.Lookups = m.Lookups
  86. sysStatus.MemMallocs = m.Mallocs
  87. sysStatus.MemFrees = m.Frees
  88. sysStatus.HeapAlloc = base.FileSize(int64(m.HeapAlloc))
  89. sysStatus.HeapSys = base.FileSize(int64(m.HeapSys))
  90. sysStatus.HeapIdle = base.FileSize(int64(m.HeapIdle))
  91. sysStatus.HeapInuse = base.FileSize(int64(m.HeapInuse))
  92. sysStatus.HeapReleased = base.FileSize(int64(m.HeapReleased))
  93. sysStatus.HeapObjects = m.HeapObjects
  94. sysStatus.StackInuse = base.FileSize(int64(m.StackInuse))
  95. sysStatus.StackSys = base.FileSize(int64(m.StackSys))
  96. sysStatus.MSpanInuse = base.FileSize(int64(m.MSpanInuse))
  97. sysStatus.MSpanSys = base.FileSize(int64(m.MSpanSys))
  98. sysStatus.MCacheInuse = base.FileSize(int64(m.MCacheInuse))
  99. sysStatus.MCacheSys = base.FileSize(int64(m.MCacheSys))
  100. sysStatus.BuckHashSys = base.FileSize(int64(m.BuckHashSys))
  101. sysStatus.GCSys = base.FileSize(int64(m.GCSys))
  102. sysStatus.OtherSys = base.FileSize(int64(m.OtherSys))
  103. sysStatus.NextGC = base.FileSize(int64(m.NextGC))
  104. sysStatus.LastGCTime = time.Unix(0, int64(m.LastGC)).Format(time.RFC3339)
  105. sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs)/1000/1000/1000)
  106. sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256])/1000/1000/1000)
  107. sysStatus.NumGC = m.NumGC
  108. }
  109. func prepareStartupProblemsAlert(ctx *context.Context) {
  110. if len(setting.StartupProblems) > 0 {
  111. content := setting.StartupProblems[0]
  112. if len(setting.StartupProblems) > 1 {
  113. content += fmt.Sprintf(" (and %d more)", len(setting.StartupProblems)-1)
  114. }
  115. ctx.Flash.Error(content, true)
  116. }
  117. }
  118. // Dashboard show admin panel dashboard
  119. func Dashboard(ctx *context.Context) {
  120. ctx.Data["Title"] = ctx.Tr("admin.dashboard")
  121. ctx.Data["PageIsAdminDashboard"] = true
  122. ctx.Data["NeedUpdate"] = updatechecker.GetNeedUpdate(ctx)
  123. ctx.Data["RemoteVersion"] = updatechecker.GetRemoteVersion(ctx)
  124. updateSystemStatus()
  125. ctx.Data["SysStatus"] = sysStatus
  126. ctx.Data["SSH"] = setting.SSH
  127. prepareStartupProblemsAlert(ctx)
  128. ctx.HTML(http.StatusOK, tplDashboard)
  129. }
  130. func SystemStatus(ctx *context.Context) {
  131. updateSystemStatus()
  132. ctx.Data["SysStatus"] = sysStatus
  133. ctx.HTML(http.StatusOK, tplSystemStatus)
  134. }
  135. // DashboardPost run an admin operation
  136. func DashboardPost(ctx *context.Context) {
  137. form := web.GetForm(ctx).(*forms.AdminDashboardForm)
  138. ctx.Data["Title"] = ctx.Tr("admin.dashboard")
  139. ctx.Data["PageIsAdminDashboard"] = true
  140. updateSystemStatus()
  141. ctx.Data["SysStatus"] = sysStatus
  142. // Run operation.
  143. if form.Op != "" {
  144. switch form.Op {
  145. case "sync_repo_branches":
  146. go func() {
  147. if err := repo_service.AddAllRepoBranchesToSyncQueue(graceful.GetManager().ShutdownContext()); err != nil {
  148. log.Error("AddAllRepoBranchesToSyncQueue: %v: %v", ctx.Doer.ID, err)
  149. }
  150. }()
  151. ctx.Flash.Success(ctx.Tr("admin.dashboard.sync_branch.started"))
  152. case "sync_repo_tags":
  153. go func() {
  154. if err := release_service.AddAllRepoTagsToSyncQueue(graceful.GetManager().ShutdownContext()); err != nil {
  155. log.Error("AddAllRepoTagsToSyncQueue: %v: %v", ctx.Doer.ID, err)
  156. }
  157. }()
  158. ctx.Flash.Success(ctx.Tr("admin.dashboard.sync_tag.started"))
  159. default:
  160. task := cron.GetTask(form.Op)
  161. if task != nil {
  162. go task.RunWithUser(ctx.Doer, nil)
  163. ctx.Flash.Success(ctx.Tr("admin.dashboard.task.started", ctx.Tr("admin.dashboard."+form.Op)))
  164. } else {
  165. ctx.Flash.Error(ctx.Tr("admin.dashboard.task.unknown", form.Op))
  166. }
  167. }
  168. }
  169. if form.From == "monitor" {
  170. ctx.Redirect(setting.AppSubURL + "/-/admin/monitor/cron")
  171. } else {
  172. ctx.Redirect(setting.AppSubURL + "/-/admin")
  173. }
  174. }
  175. func SelfCheck(ctx *context.Context) {
  176. ctx.Data["PageIsAdminSelfCheck"] = true
  177. ctx.Data["StartupProblems"] = setting.StartupProblems
  178. if len(setting.StartupProblems) == 0 && !setting.IsProd {
  179. if time.Now().Unix()%2 == 0 {
  180. ctx.Data["StartupProblems"] = []string{"This is a test warning message in dev mode"}
  181. }
  182. }
  183. r, err := db.CheckCollationsDefaultEngine()
  184. if err != nil {
  185. ctx.Flash.Error(fmt.Sprintf("CheckCollationsDefaultEngine: %v", err), true)
  186. }
  187. if r != nil {
  188. ctx.Data["DatabaseType"] = setting.Database.Type
  189. ctx.Data["DatabaseCheckResult"] = r
  190. hasProblem := false
  191. if !r.CollationEquals(r.DatabaseCollation, r.ExpectedCollation) {
  192. ctx.Data["DatabaseCheckCollationMismatch"] = true
  193. hasProblem = true
  194. }
  195. if !r.IsCollationCaseSensitive(r.DatabaseCollation) {
  196. ctx.Data["DatabaseCheckCollationCaseInsensitive"] = true
  197. hasProblem = true
  198. }
  199. ctx.Data["DatabaseCheckInconsistentCollationColumns"] = r.InconsistentCollationColumns
  200. hasProblem = hasProblem || len(r.InconsistentCollationColumns) > 0
  201. ctx.Data["DatabaseCheckHasProblems"] = hasProblem
  202. }
  203. elapsed, err := cache.Test()
  204. if err != nil {
  205. ctx.Data["CacheError"] = err
  206. } else if elapsed > cache.SlowCacheThreshold {
  207. ctx.Data["CacheSlow"] = fmt.Sprint(elapsed)
  208. }
  209. ctx.HTML(http.StatusOK, tplSelfCheck)
  210. }
  211. func SelfCheckPost(ctx *context.Context) {
  212. var problems []string
  213. frontendAppURL := ctx.FormString("location_origin") + setting.AppSubURL + "/"
  214. ctxAppURL := httplib.GuessCurrentAppURL(ctx)
  215. if !strings.HasPrefix(ctxAppURL, frontendAppURL) {
  216. problems = append(problems, ctx.Locale.TrString("admin.self_check.location_origin_mismatch", frontendAppURL, ctxAppURL))
  217. }
  218. ctx.JSON(http.StatusOK, map[string]any{"problems": problems})
  219. }
  220. func CronTasks(ctx *context.Context) {
  221. ctx.Data["Title"] = ctx.Tr("admin.monitor.cron")
  222. ctx.Data["PageIsAdminMonitorCron"] = true
  223. ctx.Data["Entries"] = cron.ListTasks()
  224. ctx.HTML(http.StatusOK, tplCron)
  225. }
  226. func MonitorStats(ctx *context.Context) {
  227. ctx.Data["Title"] = ctx.Tr("admin.monitor.stats")
  228. ctx.Data["PageIsAdminMonitorStats"] = true
  229. bs, err := json.Marshal(activities_model.GetStatistic(ctx).Counter)
  230. if err != nil {
  231. ctx.ServerError("MonitorStats", err)
  232. return
  233. }
  234. statsCounter := map[string]any{}
  235. err = json.Unmarshal(bs, &statsCounter)
  236. if err != nil {
  237. ctx.ServerError("MonitorStats", err)
  238. return
  239. }
  240. statsKeys := make([]string, 0, len(statsCounter))
  241. for k := range statsCounter {
  242. if statsCounter[k] == nil {
  243. continue
  244. }
  245. statsKeys = append(statsKeys, k)
  246. }
  247. sort.Strings(statsKeys)
  248. ctx.Data["StatsKeys"] = statsKeys
  249. ctx.Data["StatsCounter"] = statsCounter
  250. ctx.HTML(http.StatusOK, tplStats)
  251. }