本站源代码
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

351 行
11KB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package admin
  6. import (
  7. "fmt"
  8. "net/url"
  9. "os"
  10. "runtime"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/cron"
  17. "code.gitea.io/gitea/modules/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/process"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/timeutil"
  22. "code.gitea.io/gitea/services/mailer"
  23. "gitea.com/macaron/macaron"
  24. "github.com/unknwon/com"
  25. )
  26. const (
  27. tplDashboard base.TplName = "admin/dashboard"
  28. tplConfig base.TplName = "admin/config"
  29. tplMonitor base.TplName = "admin/monitor"
  30. )
  31. var (
  32. startTime = time.Now()
  33. )
  34. var sysStatus struct {
  35. Uptime string
  36. NumGoroutine int
  37. // General statistics.
  38. MemAllocated string // bytes allocated and still in use
  39. MemTotal string // bytes allocated (even if freed)
  40. MemSys string // bytes obtained from system (sum of XxxSys below)
  41. Lookups uint64 // number of pointer lookups
  42. MemMallocs uint64 // number of mallocs
  43. MemFrees uint64 // number of frees
  44. // Main allocation heap statistics.
  45. HeapAlloc string // bytes allocated and still in use
  46. HeapSys string // bytes obtained from system
  47. HeapIdle string // bytes in idle spans
  48. HeapInuse string // bytes in non-idle span
  49. HeapReleased string // bytes released to the OS
  50. HeapObjects uint64 // total number of allocated objects
  51. // Low-level fixed-size structure allocator statistics.
  52. // Inuse is bytes used now.
  53. // Sys is bytes obtained from system.
  54. StackInuse string // bootstrap stacks
  55. StackSys string
  56. MSpanInuse string // mspan structures
  57. MSpanSys string
  58. MCacheInuse string // mcache structures
  59. MCacheSys string
  60. BuckHashSys string // profiling bucket hash table
  61. GCSys string // GC metadata
  62. OtherSys string // other system allocations
  63. // Garbage collector statistics.
  64. NextGC string // next run in HeapAlloc time (bytes)
  65. LastGC string // last run in absolute time (ns)
  66. PauseTotalNs string
  67. PauseNs string // circular buffer of recent GC pause times, most recent at [(NumGC+255)%256]
  68. NumGC uint32
  69. }
  70. func updateSystemStatus() {
  71. sysStatus.Uptime = timeutil.TimeSincePro(startTime, "en")
  72. m := new(runtime.MemStats)
  73. runtime.ReadMemStats(m)
  74. sysStatus.NumGoroutine = runtime.NumGoroutine()
  75. sysStatus.MemAllocated = base.FileSize(int64(m.Alloc))
  76. sysStatus.MemTotal = base.FileSize(int64(m.TotalAlloc))
  77. sysStatus.MemSys = base.FileSize(int64(m.Sys))
  78. sysStatus.Lookups = m.Lookups
  79. sysStatus.MemMallocs = m.Mallocs
  80. sysStatus.MemFrees = m.Frees
  81. sysStatus.HeapAlloc = base.FileSize(int64(m.HeapAlloc))
  82. sysStatus.HeapSys = base.FileSize(int64(m.HeapSys))
  83. sysStatus.HeapIdle = base.FileSize(int64(m.HeapIdle))
  84. sysStatus.HeapInuse = base.FileSize(int64(m.HeapInuse))
  85. sysStatus.HeapReleased = base.FileSize(int64(m.HeapReleased))
  86. sysStatus.HeapObjects = m.HeapObjects
  87. sysStatus.StackInuse = base.FileSize(int64(m.StackInuse))
  88. sysStatus.StackSys = base.FileSize(int64(m.StackSys))
  89. sysStatus.MSpanInuse = base.FileSize(int64(m.MSpanInuse))
  90. sysStatus.MSpanSys = base.FileSize(int64(m.MSpanSys))
  91. sysStatus.MCacheInuse = base.FileSize(int64(m.MCacheInuse))
  92. sysStatus.MCacheSys = base.FileSize(int64(m.MCacheSys))
  93. sysStatus.BuckHashSys = base.FileSize(int64(m.BuckHashSys))
  94. sysStatus.GCSys = base.FileSize(int64(m.GCSys))
  95. sysStatus.OtherSys = base.FileSize(int64(m.OtherSys))
  96. sysStatus.NextGC = base.FileSize(int64(m.NextGC))
  97. sysStatus.LastGC = fmt.Sprintf("%.1fs", float64(time.Now().UnixNano()-int64(m.LastGC))/1000/1000/1000)
  98. sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs)/1000/1000/1000)
  99. sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256])/1000/1000/1000)
  100. sysStatus.NumGC = m.NumGC
  101. }
  102. // Operation Operation types.
  103. type Operation int
  104. const (
  105. cleanInactivateUser Operation = iota + 1
  106. cleanRepoArchives
  107. cleanMissingRepos
  108. gitGCRepos
  109. syncSSHAuthorizedKey
  110. syncRepositoryUpdateHook
  111. reinitMissingRepository
  112. syncExternalUsers
  113. gitFsck
  114. deleteGeneratedRepositoryAvatars
  115. )
  116. // Dashboard show admin panel dashboard
  117. func Dashboard(ctx *context.Context) {
  118. ctx.Data["Title"] = ctx.Tr("admin.dashboard")
  119. ctx.Data["PageIsAdmin"] = true
  120. ctx.Data["PageIsAdminDashboard"] = true
  121. // Run operation.
  122. op, _ := com.StrTo(ctx.Query("op")).Int()
  123. if op > 0 {
  124. var err error
  125. var success string
  126. switch Operation(op) {
  127. case cleanInactivateUser:
  128. success = ctx.Tr("admin.dashboard.delete_inactivate_accounts_success")
  129. err = models.DeleteInactivateUsers()
  130. case cleanRepoArchives:
  131. success = ctx.Tr("admin.dashboard.delete_repo_archives_success")
  132. err = models.DeleteRepositoryArchives()
  133. case cleanMissingRepos:
  134. success = ctx.Tr("admin.dashboard.delete_missing_repos_success")
  135. err = models.DeleteMissingRepositories(ctx.User)
  136. case gitGCRepos:
  137. success = ctx.Tr("admin.dashboard.git_gc_repos_success")
  138. err = models.GitGcRepos()
  139. case syncSSHAuthorizedKey:
  140. success = ctx.Tr("admin.dashboard.resync_all_sshkeys_success")
  141. err = models.RewriteAllPublicKeys()
  142. case syncRepositoryUpdateHook:
  143. success = ctx.Tr("admin.dashboard.resync_all_hooks_success")
  144. err = models.SyncRepositoryHooks()
  145. case reinitMissingRepository:
  146. success = ctx.Tr("admin.dashboard.reinit_missing_repos_success")
  147. err = models.ReinitMissingRepositories()
  148. case syncExternalUsers:
  149. success = ctx.Tr("admin.dashboard.sync_external_users_started")
  150. go models.SyncExternalUsers()
  151. case gitFsck:
  152. success = ctx.Tr("admin.dashboard.git_fsck_started")
  153. go models.GitFsck()
  154. case deleteGeneratedRepositoryAvatars:
  155. success = ctx.Tr("admin.dashboard.delete_generated_repository_avatars_success")
  156. err = models.RemoveRandomAvatars()
  157. }
  158. if err != nil {
  159. ctx.Flash.Error(err.Error())
  160. } else {
  161. ctx.Flash.Success(success)
  162. }
  163. ctx.Redirect(setting.AppSubURL + "/admin")
  164. return
  165. }
  166. ctx.Data["Stats"] = models.GetStatistic()
  167. // FIXME: update periodically
  168. updateSystemStatus()
  169. ctx.Data["SysStatus"] = sysStatus
  170. ctx.HTML(200, tplDashboard)
  171. }
  172. // SendTestMail send test mail to confirm mail service is OK
  173. func SendTestMail(ctx *context.Context) {
  174. email := ctx.Query("email")
  175. // Send a test email to the user's email address and redirect back to Config
  176. if err := mailer.SendTestMail(email); err != nil {
  177. ctx.Flash.Error(ctx.Tr("admin.config.test_mail_failed", email, err))
  178. } else {
  179. ctx.Flash.Info(ctx.Tr("admin.config.test_mail_sent", email))
  180. }
  181. ctx.Redirect(setting.AppSubURL + "/admin/config")
  182. }
  183. func shadownPasswordKV(cfgItem, splitter string) string {
  184. fields := strings.Split(cfgItem, splitter)
  185. for i := 0; i < len(fields); i++ {
  186. if strings.HasPrefix(fields[i], "password=") {
  187. fields[i] = "password=******"
  188. break
  189. }
  190. }
  191. return strings.Join(fields, splitter)
  192. }
  193. func shadownURL(provider, cfgItem string) string {
  194. u, err := url.Parse(cfgItem)
  195. if err != nil {
  196. log.Error("shodowPassword %v failed: %v", provider, err)
  197. return cfgItem
  198. }
  199. if u.User != nil {
  200. atIdx := strings.Index(cfgItem, "@")
  201. if atIdx > 0 {
  202. colonIdx := strings.LastIndex(cfgItem[:atIdx], ":")
  203. if colonIdx > 0 {
  204. return cfgItem[:colonIdx+1] + "******" + cfgItem[atIdx:]
  205. }
  206. }
  207. }
  208. return cfgItem
  209. }
  210. func shadowPassword(provider, cfgItem string) string {
  211. switch provider {
  212. case "redis":
  213. return shadownPasswordKV(cfgItem, ",")
  214. case "mysql":
  215. //root:@tcp(localhost:3306)/macaron?charset=utf8
  216. atIdx := strings.Index(cfgItem, "@")
  217. if atIdx > 0 {
  218. colonIdx := strings.Index(cfgItem[:atIdx], ":")
  219. if colonIdx > 0 {
  220. return cfgItem[:colonIdx+1] + "******" + cfgItem[atIdx:]
  221. }
  222. }
  223. return cfgItem
  224. case "postgres":
  225. // user=jiahuachen dbname=macaron port=5432 sslmode=disable
  226. if !strings.HasPrefix(cfgItem, "postgres://") {
  227. return shadownPasswordKV(cfgItem, " ")
  228. }
  229. // postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full
  230. // Notice: use shadwonURL
  231. }
  232. // "couchbase"
  233. return shadownURL(provider, cfgItem)
  234. }
  235. // Config show admin config page
  236. func Config(ctx *context.Context) {
  237. ctx.Data["Title"] = ctx.Tr("admin.config")
  238. ctx.Data["PageIsAdmin"] = true
  239. ctx.Data["PageIsAdminConfig"] = true
  240. ctx.Data["CustomConf"] = setting.CustomConf
  241. ctx.Data["AppUrl"] = setting.AppURL
  242. ctx.Data["Domain"] = setting.Domain
  243. ctx.Data["OfflineMode"] = setting.OfflineMode
  244. ctx.Data["DisableRouterLog"] = setting.DisableRouterLog
  245. ctx.Data["RunUser"] = setting.RunUser
  246. ctx.Data["RunMode"] = strings.Title(macaron.Env)
  247. ctx.Data["GitVersion"], _ = git.BinVersion()
  248. ctx.Data["RepoRootPath"] = setting.RepoRootPath
  249. ctx.Data["CustomRootPath"] = setting.CustomPath
  250. ctx.Data["StaticRootPath"] = setting.StaticRootPath
  251. ctx.Data["LogRootPath"] = setting.LogRootPath
  252. ctx.Data["ScriptType"] = setting.ScriptType
  253. ctx.Data["ReverseProxyAuthUser"] = setting.ReverseProxyAuthUser
  254. ctx.Data["ReverseProxyAuthEmail"] = setting.ReverseProxyAuthEmail
  255. ctx.Data["SSH"] = setting.SSH
  256. ctx.Data["LFS"] = setting.LFS
  257. ctx.Data["Service"] = setting.Service
  258. ctx.Data["DbCfg"] = setting.Database
  259. ctx.Data["Webhook"] = setting.Webhook
  260. ctx.Data["MailerEnabled"] = false
  261. if setting.MailService != nil {
  262. ctx.Data["MailerEnabled"] = true
  263. ctx.Data["Mailer"] = setting.MailService
  264. }
  265. ctx.Data["CacheAdapter"] = setting.CacheService.Adapter
  266. ctx.Data["CacheInterval"] = setting.CacheService.Interval
  267. ctx.Data["CacheConn"] = shadowPassword(setting.CacheService.Adapter, setting.CacheService.Conn)
  268. ctx.Data["CacheItemTTL"] = setting.CacheService.TTL
  269. sessionCfg := setting.SessionConfig
  270. sessionCfg.ProviderConfig = shadowPassword(sessionCfg.Provider, sessionCfg.ProviderConfig)
  271. ctx.Data["SessionConfig"] = sessionCfg
  272. ctx.Data["DisableGravatar"] = setting.DisableGravatar
  273. ctx.Data["EnableFederatedAvatar"] = setting.EnableFederatedAvatar
  274. ctx.Data["Git"] = setting.Git
  275. type envVar struct {
  276. Name, Value string
  277. }
  278. envVars := map[string]*envVar{}
  279. if len(os.Getenv("GITEA_WORK_DIR")) > 0 {
  280. envVars["GITEA_WORK_DIR"] = &envVar{"GITEA_WORK_DIR", os.Getenv("GITEA_WORK_DIR")}
  281. }
  282. if len(os.Getenv("GITEA_CUSTOM")) > 0 {
  283. envVars["GITEA_CUSTOM"] = &envVar{"GITEA_CUSTOM", os.Getenv("GITEA_CUSTOM")}
  284. }
  285. ctx.Data["EnvVars"] = envVars
  286. ctx.Data["Loggers"] = setting.LogDescriptions
  287. ctx.Data["RedirectMacaronLog"] = setting.RedirectMacaronLog
  288. ctx.Data["EnableAccessLog"] = setting.EnableAccessLog
  289. ctx.Data["AccessLogTemplate"] = setting.AccessLogTemplate
  290. ctx.Data["DisableRouterLog"] = setting.DisableRouterLog
  291. ctx.Data["EnableXORMLog"] = setting.EnableXORMLog
  292. ctx.Data["LogSQL"] = setting.Database.LogSQL
  293. ctx.HTML(200, tplConfig)
  294. }
  295. // Monitor show admin monitor page
  296. func Monitor(ctx *context.Context) {
  297. ctx.Data["Title"] = ctx.Tr("admin.monitor")
  298. ctx.Data["PageIsAdmin"] = true
  299. ctx.Data["PageIsAdminMonitor"] = true
  300. ctx.Data["Processes"] = process.GetManager().Processes
  301. ctx.Data["Entries"] = cron.ListTasks()
  302. ctx.HTML(200, tplMonitor)
  303. }
上海开阖软件有限公司 沪ICP备12045867号-1