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.7KB

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