You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

admin.go 12KB

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