Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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/modules/util"
  17. "code.gitea.io/gitea/routers"
  18. "code.gitea.io/gitea/routers/routes"
  19. context2 "github.com/gorilla/context"
  20. "github.com/urfave/cli"
  21. ini "gopkg.in/ini.v1"
  22. )
  23. // CmdWeb represents the available web sub-command.
  24. var CmdWeb = cli.Command{
  25. Name: "web",
  26. Usage: "Start Gitea web server",
  27. Description: `Gitea web server is the only thing you need to run,
  28. and it takes care of all the other things for you`,
  29. Action: runWeb,
  30. Flags: []cli.Flag{
  31. cli.StringFlag{
  32. Name: "port, p",
  33. Value: "3000",
  34. Usage: "Temporary port number to prevent conflict",
  35. },
  36. cli.StringFlag{
  37. Name: "install-port",
  38. Value: "3000",
  39. Usage: "Temporary port number to run the install page on to prevent conflict",
  40. },
  41. cli.StringFlag{
  42. Name: "pid, P",
  43. Value: setting.PIDFile,
  44. Usage: "Custom pid file path",
  45. },
  46. },
  47. }
  48. func runHTTPRedirector() {
  49. source := fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.PortToRedirect)
  50. dest := strings.TrimSuffix(setting.AppURL, "/")
  51. log.Info("Redirecting: %s to %s", source, dest)
  52. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  53. target := dest + r.URL.Path
  54. if len(r.URL.RawQuery) > 0 {
  55. target += "?" + r.URL.RawQuery
  56. }
  57. http.Redirect(w, r, target, http.StatusTemporaryRedirect)
  58. })
  59. var err = runHTTP("tcp", source, "HTTP Redirector", context2.ClearHandler(handler))
  60. if err != nil {
  61. log.Fatal("Failed to start port redirection: %v", err)
  62. }
  63. }
  64. func runWeb(ctx *cli.Context) error {
  65. managerCtx, cancel := context.WithCancel(context.Background())
  66. graceful.InitManager(managerCtx)
  67. defer cancel()
  68. if os.Getppid() > 1 && len(os.Getenv("LISTEN_FDS")) > 0 {
  69. log.Info("Restarting Gitea on PID: %d from parent PID: %d", os.Getpid(), os.Getppid())
  70. } else {
  71. log.Info("Starting Gitea on PID: %d", os.Getpid())
  72. }
  73. // Set pid file setting
  74. if ctx.IsSet("pid") {
  75. setting.PIDFile = ctx.String("pid")
  76. setting.WritePIDFile = true
  77. }
  78. // Perform pre-initialization
  79. needsInstall := routers.PreInstallInit(graceful.GetManager().HammerContext())
  80. if needsInstall {
  81. // Flag for port number in case first time run conflict
  82. if ctx.IsSet("port") {
  83. if err := setPort(ctx.String("port")); err != nil {
  84. return err
  85. }
  86. }
  87. if ctx.IsSet("install-port") {
  88. if err := setPort(ctx.String("install-port")); err != nil {
  89. return err
  90. }
  91. }
  92. c := routes.InstallRoutes()
  93. err := listen(c, false)
  94. select {
  95. case <-graceful.GetManager().IsShutdown():
  96. <-graceful.GetManager().Done()
  97. log.Info("PID: %d Gitea Web Finished", os.Getpid())
  98. log.Close()
  99. return err
  100. default:
  101. }
  102. } else {
  103. NoInstallListener()
  104. }
  105. if setting.EnablePprof {
  106. go func() {
  107. log.Info("Starting pprof server on localhost:6060")
  108. log.Info("%v", http.ListenAndServe("localhost:6060", nil))
  109. }()
  110. }
  111. log.Info("Global init")
  112. // Perform global initialization
  113. routers.GlobalInit(graceful.GetManager().HammerContext())
  114. // Override the provided port number within the configuration
  115. if ctx.IsSet("port") {
  116. if err := setPort(ctx.String("port")); err != nil {
  117. return err
  118. }
  119. }
  120. // Set up Chi routes
  121. c := routes.NormalRoutes()
  122. err := listen(c, true)
  123. <-graceful.GetManager().Done()
  124. log.Info("PID: %d Gitea Web Finished", os.Getpid())
  125. log.Close()
  126. return err
  127. }
  128. func setPort(port string) error {
  129. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, port, 1)
  130. setting.HTTPPort = port
  131. switch setting.Protocol {
  132. case setting.UnixSocket:
  133. case setting.FCGI:
  134. case setting.FCGIUnix:
  135. default:
  136. // Save LOCAL_ROOT_URL if port changed
  137. cfg := ini.Empty()
  138. isFile, err := util.IsFile(setting.CustomConf)
  139. if err != nil {
  140. log.Fatal("Unable to check if %s is a file", err)
  141. }
  142. if isFile {
  143. // Keeps custom settings if there is already something.
  144. if err := cfg.Append(setting.CustomConf); err != nil {
  145. return fmt.Errorf("Failed to load custom conf '%s': %v", setting.CustomConf, err)
  146. }
  147. }
  148. defaultLocalURL := string(setting.Protocol) + "://"
  149. if setting.HTTPAddr == "0.0.0.0" {
  150. defaultLocalURL += "localhost"
  151. } else {
  152. defaultLocalURL += setting.HTTPAddr
  153. }
  154. defaultLocalURL += ":" + setting.HTTPPort + "/"
  155. cfg.Section("server").Key("LOCAL_ROOT_URL").SetValue(defaultLocalURL)
  156. if err := cfg.SaveTo(setting.CustomConf); err != nil {
  157. return fmt.Errorf("Error saving generated JWT Secret to custom config: %v", err)
  158. }
  159. }
  160. return nil
  161. }
  162. func listen(m http.Handler, handleRedirector bool) error {
  163. listenAddr := setting.HTTPAddr
  164. if setting.Protocol != setting.UnixSocket && setting.Protocol != setting.FCGIUnix {
  165. listenAddr = net.JoinHostPort(listenAddr, setting.HTTPPort)
  166. }
  167. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  168. if setting.LFS.StartServer {
  169. log.Info("LFS server enabled")
  170. }
  171. var err error
  172. switch setting.Protocol {
  173. case setting.HTTP:
  174. if handleRedirector {
  175. NoHTTPRedirector()
  176. }
  177. err = runHTTP("tcp", listenAddr, "Web", context2.ClearHandler(m))
  178. case setting.HTTPS:
  179. if setting.EnableLetsEncrypt {
  180. err = runLetsEncrypt(listenAddr, setting.Domain, setting.LetsEncryptDirectory, setting.LetsEncryptEmail, context2.ClearHandler(m))
  181. break
  182. }
  183. if handleRedirector {
  184. if setting.RedirectOtherPort {
  185. go runHTTPRedirector()
  186. } else {
  187. NoHTTPRedirector()
  188. }
  189. }
  190. err = runHTTPS("tcp", listenAddr, "Web", setting.CertFile, setting.KeyFile, context2.ClearHandler(m))
  191. case setting.FCGI:
  192. if handleRedirector {
  193. NoHTTPRedirector()
  194. }
  195. err = runFCGI("tcp", listenAddr, "FCGI Web", context2.ClearHandler(m))
  196. case setting.UnixSocket:
  197. if handleRedirector {
  198. NoHTTPRedirector()
  199. }
  200. err = runHTTP("unix", listenAddr, "Web", context2.ClearHandler(m))
  201. case setting.FCGIUnix:
  202. if handleRedirector {
  203. NoHTTPRedirector()
  204. }
  205. err = runFCGI("unix", listenAddr, "Web", context2.ClearHandler(m))
  206. default:
  207. log.Fatal("Invalid protocol: %s", setting.Protocol)
  208. }
  209. if err != nil {
  210. log.Critical("Failed to start server: %v", err)
  211. }
  212. log.Info("HTTP Listener: %s Closed", listenAddr)
  213. return err
  214. }