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 11 kB

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