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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. _ "net/http/pprof" // Used for debugging if enabled and a web server is running
  11. "os"
  12. "strings"
  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. context2 "github.com/gorilla/context"
  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. source := fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.PortToRedirect)
  57. dest := strings.TrimSuffix(setting.AppURL, "/")
  58. log.Info("Redirecting: %s to %s", source, dest)
  59. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  60. target := dest + r.URL.Path
  61. if len(r.URL.RawQuery) > 0 {
  62. target += "?" + r.URL.RawQuery
  63. }
  64. http.Redirect(w, r, target, http.StatusTemporaryRedirect)
  65. })
  66. var err = runHTTP("tcp", source, "HTTP Redirector", context2.ClearHandler(handler))
  67. if err != nil {
  68. log.Fatal("Failed to start port redirection: %v", err)
  69. }
  70. }
  71. func runWeb(ctx *cli.Context) error {
  72. if ctx.Bool("verbose") {
  73. _ = log.DelLogger("console")
  74. log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "trace", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
  75. } else if ctx.Bool("quiet") {
  76. _ = log.DelLogger("console")
  77. log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "fatal", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
  78. }
  79. defer func() {
  80. if panicked := recover(); panicked != nil {
  81. log.Fatal("PANIC: %v\n%s", panicked, string(log.Stack(2)))
  82. }
  83. }()
  84. managerCtx, cancel := context.WithCancel(context.Background())
  85. graceful.InitManager(managerCtx)
  86. defer cancel()
  87. if os.Getppid() > 1 && len(os.Getenv("LISTEN_FDS")) > 0 {
  88. log.Info("Restarting Gitea on PID: %d from parent PID: %d", os.Getpid(), os.Getppid())
  89. } else {
  90. log.Info("Starting Gitea on PID: %d", os.Getpid())
  91. }
  92. // Set pid file setting
  93. if ctx.IsSet("pid") {
  94. setting.PIDFile = ctx.String("pid")
  95. setting.WritePIDFile = true
  96. }
  97. // Perform pre-initialization
  98. needsInstall := install.PreloadSettings(graceful.GetManager().HammerContext())
  99. if needsInstall {
  100. // Flag for port number in case first time run conflict
  101. if ctx.IsSet("port") {
  102. if err := setPort(ctx.String("port")); err != nil {
  103. return err
  104. }
  105. }
  106. if ctx.IsSet("install-port") {
  107. if err := setPort(ctx.String("install-port")); err != nil {
  108. return err
  109. }
  110. }
  111. c := install.Routes()
  112. err := listen(c, false)
  113. select {
  114. case <-graceful.GetManager().IsShutdown():
  115. <-graceful.GetManager().Done()
  116. log.Info("PID: %d Gitea Web Finished", os.Getpid())
  117. log.Close()
  118. return err
  119. default:
  120. }
  121. } else {
  122. NoInstallListener()
  123. }
  124. if setting.EnablePprof {
  125. go func() {
  126. log.Info("Starting pprof server on localhost:6060")
  127. log.Info("%v", http.ListenAndServe("localhost:6060", nil))
  128. }()
  129. }
  130. log.Info("Global init")
  131. // Perform global initialization
  132. routers.GlobalInit(graceful.GetManager().HammerContext())
  133. // Override the provided port number within the configuration
  134. if ctx.IsSet("port") {
  135. if err := setPort(ctx.String("port")); err != nil {
  136. return err
  137. }
  138. }
  139. // Set up Chi routes
  140. c := routers.NormalRoutes()
  141. err := listen(c, true)
  142. <-graceful.GetManager().Done()
  143. log.Info("PID: %d Gitea Web Finished", os.Getpid())
  144. log.Close()
  145. return err
  146. }
  147. func setPort(port string) error {
  148. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, port, 1)
  149. setting.HTTPPort = port
  150. switch setting.Protocol {
  151. case setting.UnixSocket:
  152. case setting.FCGI:
  153. case setting.FCGIUnix:
  154. default:
  155. defaultLocalURL := string(setting.Protocol) + "://"
  156. if setting.HTTPAddr == "0.0.0.0" {
  157. defaultLocalURL += "localhost"
  158. } else {
  159. defaultLocalURL += setting.HTTPAddr
  160. }
  161. defaultLocalURL += ":" + setting.HTTPPort + "/"
  162. // Save LOCAL_ROOT_URL if port changed
  163. setting.CreateOrAppendToCustomConf(func(cfg *ini.File) {
  164. cfg.Section("server").Key("LOCAL_ROOT_URL").SetValue(defaultLocalURL)
  165. })
  166. }
  167. return nil
  168. }
  169. func listen(m http.Handler, handleRedirector bool) error {
  170. listenAddr := setting.HTTPAddr
  171. if setting.Protocol != setting.UnixSocket && setting.Protocol != setting.FCGIUnix {
  172. listenAddr = net.JoinHostPort(listenAddr, setting.HTTPPort)
  173. }
  174. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  175. if setting.LFS.StartServer {
  176. log.Info("LFS server enabled")
  177. }
  178. var err error
  179. switch setting.Protocol {
  180. case setting.HTTP:
  181. if handleRedirector {
  182. NoHTTPRedirector()
  183. }
  184. err = runHTTP("tcp", listenAddr, "Web", context2.ClearHandler(m))
  185. case setting.HTTPS:
  186. if setting.EnableLetsEncrypt {
  187. err = runLetsEncrypt(listenAddr, setting.Domain, setting.LetsEncryptDirectory, setting.LetsEncryptEmail, context2.ClearHandler(m))
  188. break
  189. }
  190. if handleRedirector {
  191. if setting.RedirectOtherPort {
  192. go runHTTPRedirector()
  193. } else {
  194. NoHTTPRedirector()
  195. }
  196. }
  197. err = runHTTPS("tcp", listenAddr, "Web", setting.CertFile, setting.KeyFile, context2.ClearHandler(m))
  198. case setting.FCGI:
  199. if handleRedirector {
  200. NoHTTPRedirector()
  201. }
  202. err = runFCGI("tcp", listenAddr, "FCGI Web", context2.ClearHandler(m))
  203. case setting.UnixSocket:
  204. if handleRedirector {
  205. NoHTTPRedirector()
  206. }
  207. err = runHTTP("unix", listenAddr, "Web", context2.ClearHandler(m))
  208. case setting.FCGIUnix:
  209. if handleRedirector {
  210. NoHTTPRedirector()
  211. }
  212. err = runFCGI("unix", listenAddr, "Web", context2.ClearHandler(m))
  213. default:
  214. log.Fatal("Invalid protocol: %s", setting.Protocol)
  215. }
  216. if err != nil {
  217. log.Critical("Failed to start server: %v", err)
  218. }
  219. log.Info("HTTP Listener: %s Closed", listenAddr)
  220. return err
  221. }