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.

web.go 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 cmd
  5. import (
  6. "context"
  7. "fmt"
  8. "net"
  9. "net/http"
  10. "os"
  11. "strings"
  12. _ "net/http/pprof" // Used for debugging if enabled and a web server is running
  13. "code.gitea.io/gitea/modules/graceful"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/routers"
  17. "code.gitea.io/gitea/routers/install"
  18. "github.com/urfave/cli"
  19. ini "gopkg.in/ini.v1"
  20. )
  21. // CmdWeb represents the available web sub-command.
  22. var CmdWeb = cli.Command{
  23. Name: "web",
  24. Usage: "Start Gitea web server",
  25. Description: `Gitea web server is the only thing you need to run,
  26. and it takes care of all the other things for you`,
  27. Action: runWeb,
  28. Flags: []cli.Flag{
  29. cli.StringFlag{
  30. Name: "port, p",
  31. Value: "3000",
  32. Usage: "Temporary port number to prevent conflict",
  33. },
  34. cli.StringFlag{
  35. Name: "install-port",
  36. Value: "3000",
  37. Usage: "Temporary port number to run the install page on to prevent conflict",
  38. },
  39. cli.StringFlag{
  40. Name: "pid, P",
  41. Value: setting.PIDFile,
  42. Usage: "Custom pid file path",
  43. },
  44. cli.BoolFlag{
  45. Name: "quiet, q",
  46. Usage: "Only display Fatal logging errors until logging is set-up",
  47. },
  48. cli.BoolFlag{
  49. Name: "verbose",
  50. Usage: "Set initial logging to TRACE level until logging is properly set-up",
  51. },
  52. },
  53. }
  54. func runHTTPRedirector() {
  55. source := fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.PortToRedirect)
  56. dest := strings.TrimSuffix(setting.AppURL, "/")
  57. log.Info("Redirecting: %s to %s", source, dest)
  58. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  59. target := dest + r.URL.Path
  60. if len(r.URL.RawQuery) > 0 {
  61. target += "?" + r.URL.RawQuery
  62. }
  63. http.Redirect(w, r, target, http.StatusTemporaryRedirect)
  64. })
  65. var err = runHTTP("tcp", source, "HTTP Redirector", handler)
  66. if err != nil {
  67. log.Fatal("Failed to start port redirection: %v", err)
  68. }
  69. }
  70. func runWeb(ctx *cli.Context) error {
  71. if ctx.Bool("verbose") {
  72. _ = log.DelLogger("console")
  73. log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "trace", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
  74. } else if ctx.Bool("quiet") {
  75. _ = log.DelLogger("console")
  76. log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "fatal", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
  77. }
  78. defer func() {
  79. if panicked := recover(); panicked != nil {
  80. log.Fatal("PANIC: %v\n%s", panicked, string(log.Stack(2)))
  81. }
  82. }()
  83. managerCtx, cancel := context.WithCancel(context.Background())
  84. graceful.InitManager(managerCtx)
  85. defer cancel()
  86. if os.Getppid() > 1 && len(os.Getenv("LISTEN_FDS")) > 0 {
  87. log.Info("Restarting Gitea on PID: %d from parent PID: %d", os.Getpid(), os.Getppid())
  88. } else {
  89. log.Info("Starting Gitea on PID: %d", os.Getpid())
  90. }
  91. // Set pid file setting
  92. if ctx.IsSet("pid") {
  93. setting.PIDFile = ctx.String("pid")
  94. setting.WritePIDFile = true
  95. }
  96. // Perform pre-initialization
  97. needsInstall := install.PreloadSettings(graceful.GetManager().HammerContext())
  98. if needsInstall {
  99. // Flag for port number in case first time run conflict
  100. if ctx.IsSet("port") {
  101. if err := setPort(ctx.String("port")); err != nil {
  102. return err
  103. }
  104. }
  105. if ctx.IsSet("install-port") {
  106. if err := setPort(ctx.String("install-port")); err != nil {
  107. return err
  108. }
  109. }
  110. c := install.Routes()
  111. err := listen(c, false)
  112. if err != nil {
  113. log.Critical("Unable to open listener for installer. Is Gitea already running?")
  114. graceful.GetManager().DoGracefulShutdown()
  115. }
  116. select {
  117. case <-graceful.GetManager().IsShutdown():
  118. <-graceful.GetManager().Done()
  119. log.Info("PID: %d Gitea Web Finished", os.Getpid())
  120. log.Close()
  121. return err
  122. default:
  123. }
  124. } else {
  125. NoInstallListener()
  126. }
  127. if setting.EnablePprof {
  128. go func() {
  129. log.Info("Starting pprof server on localhost:6060")
  130. log.Info("%v", http.ListenAndServe("localhost:6060", nil))
  131. }()
  132. }
  133. log.Info("Global init")
  134. // Perform global initialization
  135. setting.LoadFromExisting()
  136. routers.GlobalInitInstalled(graceful.GetManager().HammerContext())
  137. // We check that AppDataPath exists here (it should have been created during installation)
  138. // We can't check it in `GlobalInitInstalled`, because some integration tests
  139. // use cmd -> GlobalInitInstalled, but the AppDataPath doesn't exist during those tests.
  140. if _, err := os.Stat(setting.AppDataPath); err != nil {
  141. log.Fatal("Can not find APP_DATA_PATH '%s'", setting.AppDataPath)
  142. }
  143. // Override the provided port number within the configuration
  144. if ctx.IsSet("port") {
  145. if err := setPort(ctx.String("port")); err != nil {
  146. return err
  147. }
  148. }
  149. // Set up Chi routes
  150. c := routers.NormalRoutes()
  151. err := listen(c, true)
  152. <-graceful.GetManager().Done()
  153. log.Info("PID: %d Gitea Web Finished", os.Getpid())
  154. log.Close()
  155. return err
  156. }
  157. func setPort(port string) error {
  158. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, port, 1)
  159. setting.HTTPPort = port
  160. switch setting.Protocol {
  161. case setting.UnixSocket:
  162. case setting.FCGI:
  163. case setting.FCGIUnix:
  164. default:
  165. defaultLocalURL := string(setting.Protocol) + "://"
  166. if setting.HTTPAddr == "0.0.0.0" {
  167. defaultLocalURL += "localhost"
  168. } else {
  169. defaultLocalURL += setting.HTTPAddr
  170. }
  171. defaultLocalURL += ":" + setting.HTTPPort + "/"
  172. // Save LOCAL_ROOT_URL if port changed
  173. setting.CreateOrAppendToCustomConf(func(cfg *ini.File) {
  174. cfg.Section("server").Key("LOCAL_ROOT_URL").SetValue(defaultLocalURL)
  175. })
  176. }
  177. return nil
  178. }
  179. func listen(m http.Handler, handleRedirector bool) error {
  180. listenAddr := setting.HTTPAddr
  181. if setting.Protocol != setting.UnixSocket && setting.Protocol != setting.FCGIUnix {
  182. listenAddr = net.JoinHostPort(listenAddr, setting.HTTPPort)
  183. }
  184. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  185. // This can be useful for users, many users do wrong to their config and get strange behaviors behind a reverse-proxy.
  186. // A user may fix the configuration mistake when he sees this log.
  187. // And this is also very helpful to maintainers to provide help to users to resolve their configuration problems.
  188. log.Info("AppURL(ROOT_URL): %s", setting.AppURL)
  189. if setting.LFS.StartServer {
  190. log.Info("LFS server enabled")
  191. }
  192. var err error
  193. switch setting.Protocol {
  194. case setting.HTTP:
  195. if handleRedirector {
  196. NoHTTPRedirector()
  197. }
  198. err = runHTTP("tcp", listenAddr, "Web", m)
  199. case setting.HTTPS:
  200. if setting.EnableLetsEncrypt {
  201. err = runLetsEncrypt(listenAddr, setting.Domain, setting.LetsEncryptDirectory, setting.LetsEncryptEmail, m)
  202. break
  203. }
  204. if handleRedirector {
  205. if setting.RedirectOtherPort {
  206. go runHTTPRedirector()
  207. } else {
  208. NoHTTPRedirector()
  209. }
  210. }
  211. err = runHTTPS("tcp", listenAddr, "Web", setting.CertFile, setting.KeyFile, m)
  212. case setting.FCGI:
  213. if handleRedirector {
  214. NoHTTPRedirector()
  215. }
  216. err = runFCGI("tcp", listenAddr, "FCGI Web", m)
  217. case setting.UnixSocket:
  218. if handleRedirector {
  219. NoHTTPRedirector()
  220. }
  221. err = runHTTP("unix", listenAddr, "Web", m)
  222. case setting.FCGIUnix:
  223. if handleRedirector {
  224. NoHTTPRedirector()
  225. }
  226. err = runFCGI("unix", listenAddr, "Web", m)
  227. default:
  228. log.Fatal("Invalid protocol: %s", setting.Protocol)
  229. }
  230. if err != nil {
  231. log.Critical("Failed to start server: %v", err)
  232. }
  233. log.Info("HTTP Listener: %s Closed", listenAddr)
  234. return err
  235. }