install.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package routers
  5. import (
  6. "errors"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/Unknwon/macaron"
  14. "github.com/go-xorm/xorm"
  15. "gopkg.in/ini.v1"
  16. "github.com/gogits/gogs/models"
  17. "github.com/gogits/gogs/models/cron"
  18. "github.com/gogits/gogs/modules/auth"
  19. "github.com/gogits/gogs/modules/base"
  20. "github.com/gogits/gogs/modules/log"
  21. "github.com/gogits/gogs/modules/mailer"
  22. "github.com/gogits/gogs/modules/middleware"
  23. "github.com/gogits/gogs/modules/setting"
  24. "github.com/gogits/gogs/modules/social"
  25. "github.com/gogits/gogs/modules/user"
  26. )
  27. const (
  28. INSTALL base.TplName = "install"
  29. )
  30. func checkRunMode() {
  31. switch setting.Cfg.Section("").Key("RUN_MODE").String() {
  32. case "prod":
  33. macaron.Env = macaron.PROD
  34. macaron.ColorLog = false
  35. setting.ProdMode = true
  36. }
  37. log.Info("Run Mode: %s", strings.Title(macaron.Env))
  38. }
  39. func NewServices() {
  40. setting.NewServices()
  41. social.NewOauthService()
  42. }
  43. // GlobalInit is for global configuration reload-able.
  44. func GlobalInit() {
  45. setting.NewConfigContext()
  46. log.Trace("Custom path: %s", setting.CustomPath)
  47. log.Trace("Log path: %s", setting.LogRootPath)
  48. mailer.NewMailerContext()
  49. models.LoadModelsConfig()
  50. NewServices()
  51. if setting.InstallLock {
  52. models.LoadRepoConfig()
  53. models.NewRepoContext()
  54. if err := models.NewEngine(); err != nil {
  55. log.Fatal(4, "Fail to initialize ORM engine: %v", err)
  56. }
  57. models.HasEngine = true
  58. cron.NewCronContext()
  59. models.InitDeliverHooks()
  60. log.NewGitLogger(path.Join(setting.LogRootPath, "http.log"))
  61. }
  62. if models.EnableSQLite3 {
  63. log.Info("SQLite3 Supported")
  64. }
  65. checkRunMode()
  66. }
  67. func InstallInit(ctx *middleware.Context) {
  68. if setting.InstallLock {
  69. ctx.Handle(404, "Install", errors.New("Installation is prohibited"))
  70. return
  71. }
  72. ctx.Data["Title"] = ctx.Tr("install.install")
  73. ctx.Data["PageIsInstall"] = true
  74. dbOpts := []string{"MySQL", "PostgreSQL"}
  75. if models.EnableSQLite3 {
  76. dbOpts = append(dbOpts, "SQLite3")
  77. }
  78. if models.EnableTidb {
  79. dbOpts = append(dbOpts, "TiDB")
  80. }
  81. ctx.Data["DbOptions"] = dbOpts
  82. }
  83. func Install(ctx *middleware.Context) {
  84. form := auth.InstallForm{}
  85. // Database settings
  86. form.DbHost = models.DbCfg.Host
  87. form.DbUser = models.DbCfg.User
  88. form.DbName = models.DbCfg.Name
  89. form.DbPath = models.DbCfg.Path
  90. if models.EnableSQLite3 {
  91. ctx.Data["CurDbOption"] = "SQLite3" // Default when enabled.
  92. } else {
  93. ctx.Data["CurDbOption"] = "MySQL"
  94. }
  95. // Application general settings
  96. form.AppName = setting.AppName
  97. form.RepoRootPath = setting.RepoRootPath
  98. // Note(unknwon): it's hard for Windows users change a running user,
  99. // so just use current one if config says default.
  100. if setting.IsWindows && setting.RunUser == "git" {
  101. form.RunUser = user.CurrentUsername()
  102. } else {
  103. form.RunUser = setting.RunUser
  104. }
  105. form.Domain = setting.Domain
  106. form.SSHPort = setting.SSHPort
  107. form.HTTPPort = setting.HttpPort
  108. form.AppUrl = setting.AppUrl
  109. // E-mail service settings
  110. if setting.MailService != nil {
  111. form.SMTPHost = setting.MailService.Host
  112. form.SMTPFrom = setting.MailService.From
  113. form.SMTPEmail = setting.MailService.User
  114. }
  115. form.RegisterConfirm = setting.Service.RegisterEmailConfirm
  116. form.MailNotify = setting.Service.EnableNotifyMail
  117. // Server and other services settings
  118. form.OfflineMode = setting.OfflineMode
  119. form.DisableGravatar = setting.DisableGravatar
  120. form.DisableRegistration = setting.Service.DisableRegistration
  121. form.RequireSignInView = setting.Service.RequireSignInView
  122. auth.AssignForm(form, ctx.Data)
  123. ctx.HTML(200, INSTALL)
  124. }
  125. func InstallPost(ctx *middleware.Context, form auth.InstallForm) {
  126. ctx.Data["CurDbOption"] = form.DbType
  127. if ctx.HasError() {
  128. if ctx.HasValue("Err_SMTPEmail") {
  129. ctx.Data["Err_SMTP"] = true
  130. }
  131. if ctx.HasValue("Err_AdminName") ||
  132. ctx.HasValue("Err_AdminPasswd") ||
  133. ctx.HasValue("Err_AdminEmail") {
  134. ctx.Data["Err_Admin"] = true
  135. }
  136. ctx.HTML(200, INSTALL)
  137. return
  138. }
  139. if _, err := exec.LookPath("git"); err != nil {
  140. ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), INSTALL, &form)
  141. return
  142. }
  143. // Pass basic check, now test configuration.
  144. // Test database setting.
  145. dbTypes := map[string]string{"MySQL": "mysql", "PostgreSQL": "postgres", "SQLite3": "sqlite3", "TiDB": "tidb"}
  146. models.DbCfg.Type = dbTypes[form.DbType]
  147. models.DbCfg.Host = form.DbHost
  148. models.DbCfg.User = form.DbUser
  149. models.DbCfg.Passwd = form.DbPasswd
  150. models.DbCfg.Name = form.DbName
  151. models.DbCfg.SSLMode = form.SSLMode
  152. models.DbCfg.Path = form.DbPath
  153. if models.DbCfg.Type == "sqlite3" && len(models.DbCfg.Path) == 0 {
  154. ctx.Data["Err_DbPath"] = true
  155. ctx.RenderWithErr(ctx.Tr("install.err_empty_sqlite_path"), INSTALL, &form)
  156. return
  157. }
  158. // Set test engine.
  159. var x *xorm.Engine
  160. if err := models.NewTestEngine(x); err != nil {
  161. if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
  162. ctx.Data["Err_DbType"] = true
  163. ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "http://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &form)
  164. } else {
  165. ctx.Data["Err_DbSetting"] = true
  166. ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), INSTALL, &form)
  167. }
  168. return
  169. }
  170. // Test repository root path.
  171. if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
  172. ctx.Data["Err_RepoRootPath"] = true
  173. ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), INSTALL, &form)
  174. return
  175. }
  176. // Check run user.
  177. curUser := user.CurrentUsername()
  178. if form.RunUser != curUser {
  179. ctx.Data["Err_RunUser"] = true
  180. ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, curUser), INSTALL, &form)
  181. return
  182. }
  183. // Check admin password.
  184. if form.AdminPasswd != form.AdminConfirmPasswd {
  185. ctx.Data["Err_Admin"] = true
  186. ctx.Data["Err_AdminPasswd"] = true
  187. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), INSTALL, form)
  188. return
  189. }
  190. if form.AppUrl[len(form.AppUrl)-1] != '/' {
  191. form.AppUrl += "/"
  192. }
  193. // Save settings.
  194. cfg := ini.Empty()
  195. if com.IsFile(setting.CustomConf) {
  196. // Keeps custom settings if there is already something.
  197. if err := cfg.Append(setting.CustomConf); err != nil {
  198. log.Error(4, "Fail to load custom conf '%s': %v", setting.CustomConf, err)
  199. }
  200. }
  201. cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type)
  202. cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host)
  203. cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name)
  204. cfg.Section("database").Key("USER").SetValue(models.DbCfg.User)
  205. cfg.Section("database").Key("PASSWD").SetValue(models.DbCfg.Passwd)
  206. cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SSLMode)
  207. cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path)
  208. cfg.Section("").Key("APP_NAME").SetValue(form.AppName)
  209. cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
  210. cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
  211. cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
  212. cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort)
  213. cfg.Section("server").Key("ROOT_URL").SetValue(form.AppUrl)
  214. if form.SSHPort == 0 {
  215. cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
  216. } else {
  217. cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
  218. cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort))
  219. }
  220. if len(strings.TrimSpace(form.SMTPHost)) > 0 {
  221. cfg.Section("mailer").Key("ENABLED").SetValue("true")
  222. cfg.Section("mailer").Key("HOST").SetValue(form.SMTPHost)
  223. cfg.Section("mailer").Key("FROM").SetValue(form.SMTPFrom)
  224. cfg.Section("mailer").Key("USER").SetValue(form.SMTPEmail)
  225. cfg.Section("mailer").Key("PASSWD").SetValue(form.SMTPPasswd)
  226. } else {
  227. cfg.Section("mailer").Key("ENABLED").SetValue("false")
  228. }
  229. cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm))
  230. cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify))
  231. cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode))
  232. cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar))
  233. cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration))
  234. cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView))
  235. cfg.Section("").Key("RUN_MODE").SetValue("prod")
  236. cfg.Section("session").Key("PROVIDER").SetValue("file")
  237. cfg.Section("log").Key("MODE").SetValue("file")
  238. cfg.Section("log").Key("LEVEL").SetValue("Info")
  239. cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
  240. cfg.Section("security").Key("SECRET_KEY").SetValue(base.GetRandomString(15))
  241. os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm)
  242. if err := cfg.SaveTo(setting.CustomConf); err != nil {
  243. ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &form)
  244. return
  245. }
  246. GlobalInit()
  247. // Create admin account.
  248. if len(form.AdminName) > 0 {
  249. if err := models.CreateUser(&models.User{
  250. Name: form.AdminName,
  251. Email: form.AdminEmail,
  252. Passwd: form.AdminPasswd,
  253. IsAdmin: true,
  254. IsActive: true,
  255. }); err != nil {
  256. if !models.IsErrUserAlreadyExist(err) {
  257. setting.InstallLock = false
  258. ctx.Data["Err_AdminName"] = true
  259. ctx.Data["Err_AdminEmail"] = true
  260. ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), INSTALL, &form)
  261. return
  262. }
  263. log.Info("Admin account already exist")
  264. }
  265. }
  266. log.Info("First-time run install finished!")
  267. ctx.Flash.Success(ctx.Tr("install.install_success"))
  268. ctx.Redirect(form.AppUrl + "user/login")
  269. }