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

admin.go 12 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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/graceful"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/process"
  22. "code.gitea.io/gitea/modules/setting"
  23. "code.gitea.io/gitea/modules/timeutil"
  24. "code.gitea.io/gitea/services/mailer"
  25. "gitea.com/macaron/macaron"
  26. "gitea.com/macaron/session"
  27. "github.com/unknwon/com"
  28. )
  29. const (
  30. tplDashboard base.TplName = "admin/dashboard"
  31. tplConfig base.TplName = "admin/config"
  32. tplMonitor base.TplName = "admin/monitor"
  33. )
  34. var (
  35. startTime = time.Now()
  36. )
  37. var sysStatus struct {
  38. Uptime string
  39. NumGoroutine int
  40. // General statistics.
  41. MemAllocated string // bytes allocated and still in use
  42. MemTotal string // bytes allocated (even if freed)
  43. MemSys string // bytes obtained from system (sum of XxxSys below)
  44. Lookups uint64 // number of pointer lookups
  45. MemMallocs uint64 // number of mallocs
  46. MemFrees uint64 // number of frees
  47. // Main allocation heap statistics.
  48. HeapAlloc string // bytes allocated and still in use
  49. HeapSys string // bytes obtained from system
  50. HeapIdle string // bytes in idle spans
  51. HeapInuse string // bytes in non-idle span
  52. HeapReleased string // bytes released to the OS
  53. HeapObjects uint64 // total number of allocated objects
  54. // Low-level fixed-size structure allocator statistics.
  55. // Inuse is bytes used now.
  56. // Sys is bytes obtained from system.
  57. StackInuse string // bootstrap stacks
  58. StackSys string
  59. MSpanInuse string // mspan structures
  60. MSpanSys string
  61. MCacheInuse string // mcache structures
  62. MCacheSys string
  63. BuckHashSys string // profiling bucket hash table
  64. GCSys string // GC metadata
  65. OtherSys string // other system allocations
  66. // Garbage collector statistics.
  67. NextGC string // next run in HeapAlloc time (bytes)
  68. LastGC string // last run in absolute time (ns)
  69. PauseTotalNs string
  70. PauseNs string // circular buffer of recent GC pause times, most recent at [(NumGC+255)%256]
  71. NumGC uint32
  72. }
  73. func updateSystemStatus() {
  74. sysStatus.Uptime = timeutil.TimeSincePro(startTime, "en")
  75. m := new(runtime.MemStats)
  76. runtime.ReadMemStats(m)
  77. sysStatus.NumGoroutine = runtime.NumGoroutine()
  78. sysStatus.MemAllocated = base.FileSize(int64(m.Alloc))
  79. sysStatus.MemTotal = base.FileSize(int64(m.TotalAlloc))
  80. sysStatus.MemSys = base.FileSize(int64(m.Sys))
  81. sysStatus.Lookups = m.Lookups
  82. sysStatus.MemMallocs = m.Mallocs
  83. sysStatus.MemFrees = m.Frees
  84. sysStatus.HeapAlloc = base.FileSize(int64(m.HeapAlloc))
  85. sysStatus.HeapSys = base.FileSize(int64(m.HeapSys))
  86. sysStatus.HeapIdle = base.FileSize(int64(m.HeapIdle))
  87. sysStatus.HeapInuse = base.FileSize(int64(m.HeapInuse))
  88. sysStatus.HeapReleased = base.FileSize(int64(m.HeapReleased))
  89. sysStatus.HeapObjects = m.HeapObjects
  90. sysStatus.StackInuse = base.FileSize(int64(m.StackInuse))
  91. sysStatus.StackSys = base.FileSize(int64(m.StackSys))
  92. sysStatus.MSpanInuse = base.FileSize(int64(m.MSpanInuse))
  93. sysStatus.MSpanSys = base.FileSize(int64(m.MSpanSys))
  94. sysStatus.MCacheInuse = base.FileSize(int64(m.MCacheInuse))
  95. sysStatus.MCacheSys = base.FileSize(int64(m.MCacheSys))
  96. sysStatus.BuckHashSys = base.FileSize(int64(m.BuckHashSys))
  97. sysStatus.GCSys = base.FileSize(int64(m.GCSys))
  98. sysStatus.OtherSys = base.FileSize(int64(m.OtherSys))
  99. sysStatus.NextGC = base.FileSize(int64(m.NextGC))
  100. sysStatus.LastGC = fmt.Sprintf("%.1fs", float64(time.Now().UnixNano()-int64(m.LastGC))/1000/1000/1000)
  101. sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs)/1000/1000/1000)
  102. sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256])/1000/1000/1000)
  103. sysStatus.NumGC = m.NumGC
  104. }
  105. // Operation Operation types.
  106. type Operation int
  107. const (
  108. cleanInactivateUser Operation = iota + 1
  109. cleanRepoArchives
  110. cleanMissingRepos
  111. gitGCRepos
  112. syncSSHAuthorizedKey
  113. syncRepositoryUpdateHook
  114. reinitMissingRepository
  115. syncExternalUsers
  116. gitFsck
  117. deleteGeneratedRepositoryAvatars
  118. )
  119. // Dashboard show admin panel dashboard
  120. func Dashboard(ctx *context.Context) {
  121. ctx.Data["Title"] = ctx.Tr("admin.dashboard")
  122. ctx.Data["PageIsAdmin"] = true
  123. ctx.Data["PageIsAdminDashboard"] = true
  124. // Run operation.
  125. op, _ := com.StrTo(ctx.Query("op")).Int()
  126. if op > 0 {
  127. var err error
  128. var success string
  129. switch Operation(op) {
  130. case cleanInactivateUser:
  131. success = ctx.Tr("admin.dashboard.delete_inactivate_accounts_success")
  132. err = models.DeleteInactivateUsers()
  133. case cleanRepoArchives:
  134. success = ctx.Tr("admin.dashboard.delete_repo_archives_success")
  135. err = models.DeleteRepositoryArchives()
  136. case cleanMissingRepos:
  137. success = ctx.Tr("admin.dashboard.delete_missing_repos_success")
  138. err = models.DeleteMissingRepositories(ctx.User)
  139. case gitGCRepos:
  140. success = ctx.Tr("admin.dashboard.git_gc_repos_success")
  141. err = models.GitGcRepos()
  142. case syncSSHAuthorizedKey:
  143. success = ctx.Tr("admin.dashboard.resync_all_sshkeys_success")
  144. err = models.RewriteAllPublicKeys()
  145. case syncRepositoryUpdateHook:
  146. success = ctx.Tr("admin.dashboard.resync_all_hooks_success")
  147. err = models.SyncRepositoryHooks()
  148. case reinitMissingRepository:
  149. success = ctx.Tr("admin.dashboard.reinit_missing_repos_success")
  150. err = models.ReinitMissingRepositories()
  151. case syncExternalUsers:
  152. success = ctx.Tr("admin.dashboard.sync_external_users_started")
  153. go graceful.GetManager().RunWithShutdownContext(models.SyncExternalUsers)
  154. case gitFsck:
  155. success = ctx.Tr("admin.dashboard.git_fsck_started")
  156. go graceful.GetManager().RunWithShutdownContext(models.GitFsck)
  157. case deleteGeneratedRepositoryAvatars:
  158. success = ctx.Tr("admin.dashboard.delete_generated_repository_avatars_success")
  159. err = models.RemoveRandomAvatars()
  160. }
  161. if err != nil {
  162. ctx.Flash.Error(err.Error())
  163. } else {
  164. ctx.Flash.Success(success)
  165. }
  166. ctx.Redirect(setting.AppSubURL + "/admin")
  167. return
  168. }
  169. ctx.Data["Stats"] = models.GetStatistic()
  170. // FIXME: update periodically
  171. updateSystemStatus()
  172. ctx.Data["SysStatus"] = sysStatus
  173. ctx.HTML(200, tplDashboard)
  174. }
  175. // SendTestMail send test mail to confirm mail service is OK
  176. func SendTestMail(ctx *context.Context) {
  177. email := ctx.Query("email")
  178. // Send a test email to the user's email address and redirect back to Config
  179. if err := mailer.SendTestMail(email); err != nil {
  180. ctx.Flash.Error(ctx.Tr("admin.config.test_mail_failed", email, err))
  181. } else {
  182. ctx.Flash.Info(ctx.Tr("admin.config.test_mail_sent", email))
  183. }
  184. ctx.Redirect(setting.AppSubURL + "/admin/config")
  185. }
  186. func shadowPasswordKV(cfgItem, splitter string) string {
  187. fields := strings.Split(cfgItem, splitter)
  188. for i := 0; i < len(fields); i++ {
  189. if strings.HasPrefix(fields[i], "password=") {
  190. fields[i] = "password=******"
  191. break
  192. }
  193. }
  194. return strings.Join(fields, splitter)
  195. }
  196. func shadowURL(provider, cfgItem string) string {
  197. u, err := url.Parse(cfgItem)
  198. if err != nil {
  199. log.Error("Shadowing Password for %v failed: %v", provider, err)
  200. return cfgItem
  201. }
  202. if u.User != nil {
  203. atIdx := strings.Index(cfgItem, "@")
  204. if atIdx > 0 {
  205. colonIdx := strings.LastIndex(cfgItem[:atIdx], ":")
  206. if colonIdx > 0 {
  207. return cfgItem[:colonIdx+1] + "******" + cfgItem[atIdx:]
  208. }
  209. }
  210. }
  211. return cfgItem
  212. }
  213. func shadowPassword(provider, cfgItem string) string {
  214. switch provider {
  215. case "redis":
  216. return shadowPasswordKV(cfgItem, ",")
  217. case "mysql":
  218. //root:@tcp(localhost:3306)/macaron?charset=utf8
  219. atIdx := strings.Index(cfgItem, "@")
  220. if atIdx > 0 {
  221. colonIdx := strings.Index(cfgItem[:atIdx], ":")
  222. if colonIdx > 0 {
  223. return cfgItem[:colonIdx+1] + "******" + cfgItem[atIdx:]
  224. }
  225. }
  226. return cfgItem
  227. case "postgres":
  228. // user=jiahuachen dbname=macaron port=5432 sslmode=disable
  229. if !strings.HasPrefix(cfgItem, "postgres://") {
  230. return shadowPasswordKV(cfgItem, " ")
  231. }
  232. fallthrough
  233. case "couchbase":
  234. return shadowURL(provider, cfgItem)
  235. // postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full
  236. // Notice: use shadowURL
  237. }
  238. return cfgItem
  239. }
  240. // Config show admin config page
  241. func Config(ctx *context.Context) {
  242. ctx.Data["Title"] = ctx.Tr("admin.config")
  243. ctx.Data["PageIsAdmin"] = true
  244. ctx.Data["PageIsAdminConfig"] = true
  245. ctx.Data["CustomConf"] = setting.CustomConf
  246. ctx.Data["AppUrl"] = setting.AppURL
  247. ctx.Data["Domain"] = setting.Domain
  248. ctx.Data["OfflineMode"] = setting.OfflineMode
  249. ctx.Data["DisableRouterLog"] = setting.DisableRouterLog
  250. ctx.Data["RunUser"] = setting.RunUser
  251. ctx.Data["RunMode"] = strings.Title(macaron.Env)
  252. ctx.Data["GitVersion"], _ = git.BinVersion()
  253. ctx.Data["RepoRootPath"] = setting.RepoRootPath
  254. ctx.Data["CustomRootPath"] = setting.CustomPath
  255. ctx.Data["StaticRootPath"] = setting.StaticRootPath
  256. ctx.Data["LogRootPath"] = setting.LogRootPath
  257. ctx.Data["ScriptType"] = setting.ScriptType
  258. ctx.Data["ReverseProxyAuthUser"] = setting.ReverseProxyAuthUser
  259. ctx.Data["ReverseProxyAuthEmail"] = setting.ReverseProxyAuthEmail
  260. ctx.Data["SSH"] = setting.SSH
  261. ctx.Data["LFS"] = setting.LFS
  262. ctx.Data["Service"] = setting.Service
  263. ctx.Data["DbCfg"] = setting.Database
  264. ctx.Data["Webhook"] = setting.Webhook
  265. ctx.Data["MailerEnabled"] = false
  266. if setting.MailService != nil {
  267. ctx.Data["MailerEnabled"] = true
  268. ctx.Data["Mailer"] = setting.MailService
  269. }
  270. ctx.Data["CacheAdapter"] = setting.CacheService.Adapter
  271. ctx.Data["CacheInterval"] = setting.CacheService.Interval
  272. ctx.Data["CacheConn"] = shadowPassword(setting.CacheService.Adapter, setting.CacheService.Conn)
  273. ctx.Data["CacheItemTTL"] = setting.CacheService.TTL
  274. sessionCfg := setting.SessionConfig
  275. if sessionCfg.Provider == "VirtualSession" {
  276. var realSession session.Options
  277. if err := json.Unmarshal([]byte(sessionCfg.ProviderConfig), &realSession); err != nil {
  278. log.Error("Unable to unmarshall session config for virtualed provider config: %s\nError: %v", sessionCfg.ProviderConfig, err)
  279. }
  280. sessionCfg = realSession
  281. }
  282. sessionCfg.ProviderConfig = shadowPassword(sessionCfg.Provider, sessionCfg.ProviderConfig)
  283. ctx.Data["SessionConfig"] = sessionCfg
  284. ctx.Data["DisableGravatar"] = setting.DisableGravatar
  285. ctx.Data["EnableFederatedAvatar"] = setting.EnableFederatedAvatar
  286. ctx.Data["Git"] = setting.Git
  287. type envVar struct {
  288. Name, Value string
  289. }
  290. envVars := map[string]*envVar{}
  291. if len(os.Getenv("GITEA_WORK_DIR")) > 0 {
  292. envVars["GITEA_WORK_DIR"] = &envVar{"GITEA_WORK_DIR", os.Getenv("GITEA_WORK_DIR")}
  293. }
  294. if len(os.Getenv("GITEA_CUSTOM")) > 0 {
  295. envVars["GITEA_CUSTOM"] = &envVar{"GITEA_CUSTOM", os.Getenv("GITEA_CUSTOM")}
  296. }
  297. ctx.Data["EnvVars"] = envVars
  298. ctx.Data["Loggers"] = setting.LogDescriptions
  299. ctx.Data["RedirectMacaronLog"] = setting.RedirectMacaronLog
  300. ctx.Data["EnableAccessLog"] = setting.EnableAccessLog
  301. ctx.Data["AccessLogTemplate"] = setting.AccessLogTemplate
  302. ctx.Data["DisableRouterLog"] = setting.DisableRouterLog
  303. ctx.Data["EnableXORMLog"] = setting.EnableXORMLog
  304. ctx.Data["LogSQL"] = setting.Database.LogSQL
  305. ctx.HTML(200, tplConfig)
  306. }
  307. // Monitor show admin monitor page
  308. func Monitor(ctx *context.Context) {
  309. ctx.Data["Title"] = ctx.Tr("admin.monitor")
  310. ctx.Data["PageIsAdmin"] = true
  311. ctx.Data["PageIsAdminMonitor"] = true
  312. ctx.Data["Processes"] = process.GetManager().Processes()
  313. ctx.Data["Entries"] = cron.ListTasks()
  314. ctx.HTML(200, tplMonitor)
  315. }
  316. // MonitorCancel cancels a process
  317. func MonitorCancel(ctx *context.Context) {
  318. pid := ctx.ParamsInt64("pid")
  319. process.GetManager().Cancel(pid)
  320. ctx.JSON(200, map[string]interface{}{
  321. "redirect": ctx.Repo.RepoLink + "/admin/monitor",
  322. })
  323. }