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.

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