Skip to content

Commit 2cdf260

Browse files
authored
Refactor path & config system (#25330)
# The problem There were many "path tricks": * By default, Gitea uses its program directory as its work path * Gitea tries to use the "work path" to guess its "custom path" and "custom conf (app.ini)" * Users might want to use other directories as work path * The non-default work path should be passed to Gitea by GITEA_WORK_DIR or "--work-path" * But some Gitea processes are started without these values * The "serv" process started by OpenSSH server * The CLI sub-commands started by site admin * The paths are guessed by SetCustomPathAndConf again and again * The default values of "work path / custom path / custom conf" can be changed when compiling # The solution * Use `InitWorkPathAndCommonConfig` to handle these path tricks, and use test code to cover its behaviors. * When Gitea's web server runs, write the WORK_PATH to "app.ini", this value must be the most correct one, because if this value is not right, users would find that the web UI doesn't work and then they should be able to fix it. * Then all other sub-commands can use the WORK_PATH in app.ini to initialize their paths. * By the way, when Gitea starts for git protocol, it shouldn't output any log, otherwise the git protocol gets broken and client blocks forever. The "work path" priority is: WORK_PATH in app.ini > cmd arg --work-path > env var GITEA_WORK_DIR > builtin default The "app.ini" searching order is: cmd arg --config > cmd arg "work path / custom path" > env var "work path / custom path" > builtin default ## ⚠️ BREAKING If your instance's "work path / custom path / custom conf" doesn't meet the requirements (eg: work path must be absolute), Gitea will report a fatal error and exit. You need to set these values according to the error log. ---- Close #24818 Close #24222 Close #21606 Close #21498 Close #25107 Close #24981 Maybe close #24503 Replace #23301 Replace #22754 And maybe more
1 parent 1454f9d commit 2cdf260

32 files changed

+650
-459
lines changed

.gitignore

-2
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,6 @@ cpu.out
5353
/bin
5454
/dist
5555
/custom/*
56-
!/custom/conf
57-
/custom/conf/*
5856
!/custom/conf/app.example.ini
5957
/data
6058
/indexers

cmd/actions.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func runGenerateActionsRunnerToken(c *cli.Context) error {
4242
ctx, cancel := installSignals()
4343
defer cancel()
4444

45-
setting.Init(&setting.Options{})
45+
setting.MustInstalled()
4646

4747
scope := c.String("scope")
4848

cmd/cmd.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ func confirm() (bool, error) {
5858
}
5959

6060
func initDB(ctx context.Context) error {
61-
setting.Init(&setting.Options{})
61+
setting.MustInstalled()
6262
setting.LoadDBSetting()
6363
setting.InitSQLLoggersForCli(log.INFO)
6464

cmd/doctor.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ func runRecreateTable(ctx *cli.Context) error {
9191
golog.SetOutput(log.LoggerToWriter(log.GetLogger(log.DEFAULT).Info))
9292

9393
debug := ctx.Bool("debug")
94-
setting.Init(&setting.Options{})
94+
setting.MustInstalled()
9595
setting.LoadDBSetting()
9696

9797
if debug {

cmd/dump.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ func runDump(ctx *cli.Context) error {
182182
}
183183
fileName += "." + outType
184184
}
185-
setting.Init(&setting.Options{})
185+
setting.MustInstalled()
186186

187187
// make sure we are logging to the console no matter what the configuration tells us do to
188188
// FIXME: don't use CfgProvider directly

cmd/embedded.go

-5
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,6 @@ type assetFile struct {
9999
func initEmbeddedExtractor(c *cli.Context) error {
100100
setupConsoleLogger(log.ERROR, log.CanColorStderr, os.Stderr)
101101

102-
// Read configuration file
103-
setting.Init(&setting.Options{
104-
AllowEmpty: true,
105-
})
106-
107102
patterns, err := compileCollectPatterns(c.Args())
108103
if err != nil {
109104
return err

cmd/mailer.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func runSendMail(c *cli.Context) error {
1616
ctx, cancel := installSignals()
1717
defer cancel()
1818

19-
setting.Init(&setting.Options{})
19+
setting.MustInstalled()
2020

2121
if err := argsSet(c, "title"); err != nil {
2222
return err

cmd/restore_repo.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func runRestoreRepository(c *cli.Context) error {
5151
ctx, cancel := installSignals()
5252
defer cancel()
5353

54-
setting.Init(&setting.Options{})
54+
setting.MustInstalled()
5555
var units []string
5656
if s := c.String("units"); s != "" {
5757
units = strings.Split(s, ",")

cmd/serv.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func setup(ctx context.Context, debug bool) {
6161
} else {
6262
setupConsoleLogger(log.FATAL, false, os.Stderr)
6363
}
64-
setting.Init(&setting.Options{})
64+
setting.MustInstalled()
6565
if debug {
6666
setting.RunMode = "dev"
6767
}

cmd/web.go

+108-60
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,110 @@ func createPIDFile(pidPath string) {
101101
}
102102
}
103103

104+
func serveInstall(ctx *cli.Context) error {
105+
log.Info("Gitea version: %s%s", setting.AppVer, setting.AppBuiltWith)
106+
log.Info("App path: %s", setting.AppPath)
107+
log.Info("Work path: %s", setting.AppWorkPath)
108+
log.Info("Custom path: %s", setting.CustomPath)
109+
log.Info("Config file: %s", setting.CustomConf)
110+
log.Info("Prepare to run install page")
111+
112+
routers.InitWebInstallPage(graceful.GetManager().HammerContext())
113+
114+
// Flag for port number in case first time run conflict
115+
if ctx.IsSet("port") {
116+
if err := setPort(ctx.String("port")); err != nil {
117+
return err
118+
}
119+
}
120+
if ctx.IsSet("install-port") {
121+
if err := setPort(ctx.String("install-port")); err != nil {
122+
return err
123+
}
124+
}
125+
c := install.Routes()
126+
err := listen(c, false)
127+
if err != nil {
128+
log.Critical("Unable to open listener for installer. Is Gitea already running?")
129+
graceful.GetManager().DoGracefulShutdown()
130+
}
131+
select {
132+
case <-graceful.GetManager().IsShutdown():
133+
<-graceful.GetManager().Done()
134+
log.Info("PID: %d Gitea Web Finished", os.Getpid())
135+
log.GetManager().Close()
136+
return err
137+
default:
138+
}
139+
return nil
140+
}
141+
142+
func serveInstalled(ctx *cli.Context) error {
143+
setting.InitCfgProvider(setting.CustomConf)
144+
setting.LoadCommonSettings()
145+
setting.MustInstalled()
146+
147+
log.Info("Gitea version: %s%s", setting.AppVer, setting.AppBuiltWith)
148+
log.Info("App path: %s", setting.AppPath)
149+
log.Info("Work path: %s", setting.AppWorkPath)
150+
log.Info("Custom path: %s", setting.CustomPath)
151+
log.Info("Config file: %s", setting.CustomConf)
152+
log.Info("Run mode: %s", setting.RunMode)
153+
log.Info("Prepare to run web server")
154+
155+
if setting.AppWorkPathMismatch {
156+
log.Error("WORK_PATH from config %q doesn't match other paths from environment variables or command arguments. "+
157+
"Only WORK_PATH in config should be set and used. Please remove the other outdated work paths from environment variables and command arguments", setting.CustomConf)
158+
}
159+
160+
rootCfg := setting.CfgProvider
161+
if rootCfg.Section("").Key("WORK_PATH").String() == "" {
162+
saveCfg, err := rootCfg.PrepareSaving()
163+
if err != nil {
164+
log.Error("Unable to prepare saving WORK_PATH=%s to config %q: %v\nYou must set it manually, otherwise there might be bugs when accessing the git repositories.", setting.AppWorkPath, setting.CustomConf, err)
165+
} else {
166+
rootCfg.Section("").Key("WORK_PATH").SetValue(setting.AppWorkPath)
167+
saveCfg.Section("").Key("WORK_PATH").SetValue(setting.AppWorkPath)
168+
if err = saveCfg.Save(); err != nil {
169+
log.Error("Unable to update WORK_PATH=%s to config %q: %v\nYou must set it manually, otherwise there might be bugs when accessing the git repositories.", setting.AppWorkPath, setting.CustomConf, err)
170+
}
171+
}
172+
}
173+
174+
routers.InitWebInstalled(graceful.GetManager().HammerContext())
175+
176+
// We check that AppDataPath exists here (it should have been created during installation)
177+
// We can't check it in `InitWebInstalled`, because some integration tests
178+
// use cmd -> InitWebInstalled, but the AppDataPath doesn't exist during those tests.
179+
if _, err := os.Stat(setting.AppDataPath); err != nil {
180+
log.Fatal("Can not find APP_DATA_PATH %q", setting.AppDataPath)
181+
}
182+
183+
// Override the provided port number within the configuration
184+
if ctx.IsSet("port") {
185+
if err := setPort(ctx.String("port")); err != nil {
186+
return err
187+
}
188+
}
189+
190+
// Set up Chi routes
191+
c := routers.NormalRoutes()
192+
err := listen(c, true)
193+
<-graceful.GetManager().Done()
194+
log.Info("PID: %d Gitea Web Finished", os.Getpid())
195+
log.GetManager().Close()
196+
return err
197+
}
198+
199+
func servePprof() {
200+
http.DefaultServeMux.Handle("/debug/fgprof", fgprof.Handler())
201+
_, _, finished := process.GetManager().AddTypedContext(context.Background(), "Web: PProf Server", process.SystemProcessType, true)
202+
// The pprof server is for debug purpose only, it shouldn't be exposed on public network. At the moment it's not worth to introduce a configurable option for it.
203+
log.Info("Starting pprof server on localhost:6060")
204+
log.Info("Stopped pprof server: %v", http.ListenAndServe("localhost:6060", nil))
205+
finished()
206+
}
207+
104208
func runWeb(ctx *cli.Context) error {
105209
if ctx.Bool("verbose") {
106210
setupConsoleLogger(log.TRACE, log.CanColorStdout, os.Stdout)
@@ -128,75 +232,19 @@ func runWeb(ctx *cli.Context) error {
128232
createPIDFile(ctx.String("pid"))
129233
}
130234

131-
// Perform pre-initialization
132-
needsInstall := install.PreloadSettings(graceful.GetManager().HammerContext())
133-
if needsInstall {
134-
// Flag for port number in case first time run conflict
135-
if ctx.IsSet("port") {
136-
if err := setPort(ctx.String("port")); err != nil {
137-
return err
138-
}
139-
}
140-
if ctx.IsSet("install-port") {
141-
if err := setPort(ctx.String("install-port")); err != nil {
142-
return err
143-
}
144-
}
145-
c := install.Routes()
146-
err := listen(c, false)
147-
if err != nil {
148-
log.Critical("Unable to open listener for installer. Is Gitea already running?")
149-
graceful.GetManager().DoGracefulShutdown()
150-
}
151-
select {
152-
case <-graceful.GetManager().IsShutdown():
153-
<-graceful.GetManager().Done()
154-
log.Info("PID: %d Gitea Web Finished", os.Getpid())
155-
log.GetManager().Close()
235+
if !setting.InstallLock {
236+
if err := serveInstall(ctx); err != nil {
156237
return err
157-
default:
158238
}
159239
} else {
160240
NoInstallListener()
161241
}
162242

163243
if setting.EnablePprof {
164-
go func() {
165-
http.DefaultServeMux.Handle("/debug/fgprof", fgprof.Handler())
166-
_, _, finished := process.GetManager().AddTypedContext(context.Background(), "Web: PProf Server", process.SystemProcessType, true)
167-
// The pprof server is for debug purpose only, it shouldn't be exposed on public network. At the moment it's not worth to introduce a configurable option for it.
168-
log.Info("Starting pprof server on localhost:6060")
169-
log.Info("Stopped pprof server: %v", http.ListenAndServe("localhost:6060", nil))
170-
finished()
171-
}()
244+
go servePprof()
172245
}
173246

174-
log.Info("Global init")
175-
// Perform global initialization
176-
setting.Init(&setting.Options{})
177-
routers.GlobalInitInstalled(graceful.GetManager().HammerContext())
178-
179-
// We check that AppDataPath exists here (it should have been created during installation)
180-
// We can't check it in `GlobalInitInstalled`, because some integration tests
181-
// use cmd -> GlobalInitInstalled, but the AppDataPath doesn't exist during those tests.
182-
if _, err := os.Stat(setting.AppDataPath); err != nil {
183-
log.Fatal("Can not find APP_DATA_PATH '%s'", setting.AppDataPath)
184-
}
185-
186-
// Override the provided port number within the configuration
187-
if ctx.IsSet("port") {
188-
if err := setPort(ctx.String("port")); err != nil {
189-
return err
190-
}
191-
}
192-
193-
// Set up Chi routes
194-
c := routers.NormalRoutes()
195-
err := listen(c, true)
196-
<-graceful.GetManager().Done()
197-
log.Info("PID: %d Gitea Web Finished", os.Getpid())
198-
log.GetManager().Close()
199-
return err
247+
return serveInstalled(ctx)
200248
}
201249

202250
func setPort(port string) error {

contrib/environment-to-ini/environment-to-ini.go

+6-7
Original file line numberDiff line numberDiff line change
@@ -81,21 +81,20 @@ func main() {
8181
},
8282
}
8383
app.Action = runEnvironmentToIni
84-
setting.SetCustomPathAndConf("", "", "")
85-
8684
err := app.Run(os.Args)
8785
if err != nil {
8886
log.Fatal("Failed to run app with %s: %v", os.Args, err)
8987
}
9088
}
9189

9290
func runEnvironmentToIni(c *cli.Context) error {
93-
providedCustom := c.String("custom-path")
94-
providedConf := c.String("config")
95-
providedWorkPath := c.String("work-path")
96-
setting.SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath)
91+
setting.InitWorkPathAndCommonConfig(os.Getenv, setting.ArgWorkPathAndCustomConf{
92+
WorkPath: c.String("work-path"),
93+
CustomPath: c.String("custom-path"),
94+
CustomConf: c.String("config"),
95+
})
9796

98-
cfg, err := setting.NewConfigProviderFromFile(&setting.Options{CustomConf: setting.CustomConf, AllowEmpty: true})
97+
cfg, err := setting.NewConfigProviderFromFile(setting.CustomConf)
9998
if err != nil {
10099
log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
101100
}

0 commit comments

Comments
 (0)