Skip to content

Commit c34ad62

Browse files
authored
Mulitple Gitea Doctor improvements (#10943) (#10990) (#10064) (#9095) (#10991)
* Mulitple Gitea Doctor improvements (#10943) Backport #10943 * Add `gitea doctor --list` flag to list the checks that will be run, including those by default * Add `gitea doctor --run` to run specific checks * Add `gitea doctor --all` to run all checks * Add db version checker * Add non-default recalculate merge bases check/fixer to doctor * Add hook checker (Fix #9878) and ensure hooks are executable (Fix #6319) * Fix authorized_keys checker - slight change of functionality here because parsing the command is fragile and we should just check if the authorized_keys file is essentially the same as what gitea would produce. (This is still not perfect as order matters - we should probably just md5sum the two files.) * Add SCRIPT_TYPE check (Fix #10977) * Add `gitea doctor --fix` to attempt to fix what is possible to easily fix * Add `gitea doctor --log-file` to set the log-file, be it a file, stdout or to switch off completely. (Fixes previously undetected bug with certain xorm logging configurations - see @6543 comment.) Signed-off-by: Andrew Thornton <[email protected]> * Switch to io.Writer instead of io.StringWriter Signed-off-by: Andrew Thornton <[email protected]>
1 parent f7d7cf4 commit c34ad62

File tree

8 files changed

+679
-21
lines changed

8 files changed

+679
-21
lines changed

cmd/doctor.go

Lines changed: 496 additions & 0 deletions
Large diffs are not rendered by default.

main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ arguments - which can alternatively be run by running the subcommand web.`
6868
cmd.CmdMigrate,
6969
cmd.CmdKeys,
7070
cmd.CmdConvert,
71+
cmd.CmdDoctor,
7172
}
7273
// Now adjust these commands to add our global configuration options
7374

models/context.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44

55
package models
66

7+
import (
8+
"code.gitea.io/gitea/modules/setting"
9+
"xorm.io/builder"
10+
)
11+
712
// DBContext represents a db context
813
type DBContext struct {
914
e Engine
@@ -53,3 +58,10 @@ func WithTx(f func(ctx DBContext) error) error {
5358
sess.Close()
5459
return err
5560
}
61+
62+
// Iterate iterates the databases and doing something
63+
func Iterate(ctx DBContext, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error {
64+
return ctx.e.Where(cond).
65+
BufferSize(setting.Database.IterateBufferSize).
66+
Iterate(tableBean, fun)
67+
}

models/migrations/migrations.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,52 @@ var migrations = []Migration{
292292
NewMigration("Add block on rejected reviews branch protection", addBlockOnRejectedReviews),
293293
}
294294

295+
// GetCurrentDBVersion returns the current db version
296+
func GetCurrentDBVersion(x *xorm.Engine) (int64, error) {
297+
if err := x.Sync(new(Version)); err != nil {
298+
return -1, fmt.Errorf("sync: %v", err)
299+
}
300+
301+
currentVersion := &Version{ID: 1}
302+
has, err := x.Get(currentVersion)
303+
if err != nil {
304+
return -1, fmt.Errorf("get: %v", err)
305+
}
306+
if !has {
307+
return -1, nil
308+
}
309+
return currentVersion.Version, nil
310+
}
311+
312+
// ExpectedVersion returns the expected db version
313+
func ExpectedVersion() int64 {
314+
return int64(minDBVersion + len(migrations))
315+
}
316+
317+
// EnsureUpToDate will check if the db is at the correct version
318+
func EnsureUpToDate(x *xorm.Engine) error {
319+
currentDB, err := GetCurrentDBVersion(x)
320+
if err != nil {
321+
return err
322+
}
323+
324+
if currentDB < 0 {
325+
return fmt.Errorf("Database has not been initialised")
326+
}
327+
328+
if minDBVersion > currentDB {
329+
return fmt.Errorf("DB version %d (<= %d) is too old for auto-migration. Upgrade to Gitea 1.6.4 first then upgrade to this version", currentDB, minDBVersion)
330+
}
331+
332+
expected := ExpectedVersion()
333+
334+
if currentDB != expected {
335+
return fmt.Errorf(`Current database version %d is not equal to the expected version %d. Please run "gitea [--config /path/to/app.ini] migrate" to update the database version`, currentDB, expected)
336+
}
337+
338+
return nil
339+
}
340+
295341
// Migrate database to current version
296342
func Migrate(x *xorm.Engine) error {
297343
if err := x.Sync(new(Version)); err != nil {

models/repo.go

Lines changed: 94 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -968,28 +968,29 @@ func CheckCreateRepository(doer, u *User, name string) error {
968968
return nil
969969
}
970970

971+
func getHookTemplates() (hookNames, hookTpls, giteaHookTpls []string) {
972+
hookNames = []string{"pre-receive", "update", "post-receive"}
973+
hookTpls = []string{
974+
fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
975+
fmt.Sprintf("#!/usr/bin/env %s\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\n\"${hook}\" $1 $2 $3\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
976+
fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
977+
}
978+
giteaHookTpls = []string{
979+
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
980+
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
981+
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
982+
}
983+
return
984+
}
985+
971986
// CreateDelegateHooks creates all the hooks scripts for the repo
972987
func CreateDelegateHooks(repoPath string) error {
973988
return createDelegateHooks(repoPath)
974989
}
975990

976991
// createDelegateHooks creates all the hooks scripts for the repo
977992
func createDelegateHooks(repoPath string) (err error) {
978-
979-
var (
980-
hookNames = []string{"pre-receive", "update", "post-receive"}
981-
hookTpls = []string{
982-
fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
983-
fmt.Sprintf("#!/usr/bin/env %s\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\n\"${hook}\" $1 $2 $3\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
984-
fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
985-
}
986-
giteaHookTpls = []string{
987-
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
988-
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
989-
fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
990-
}
991-
)
992-
993+
hookNames, hookTpls, giteaHookTpls := getHookTemplates()
993994
hookDir := filepath.Join(repoPath, "hooks")
994995

995996
for i, hookName := range hookNames {
@@ -1008,16 +1009,94 @@ func createDelegateHooks(repoPath string) (err error) {
10081009
return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
10091010
}
10101011

1012+
if err = ensureExecutable(oldHookPath); err != nil {
1013+
return fmt.Errorf("Unable to set %s executable. Error %v", oldHookPath, err)
1014+
}
1015+
10111016
if err = os.Remove(newHookPath); err != nil && !os.IsNotExist(err) {
10121017
return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %v", newHookPath, err)
10131018
}
10141019
if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
10151020
return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
10161021
}
1022+
1023+
if err = ensureExecutable(newHookPath); err != nil {
1024+
return fmt.Errorf("Unable to set %s executable. Error %v", oldHookPath, err)
1025+
}
10171026
}
10181027

10191028
return nil
10201029
}
1030+
func checkExecutable(filename string) bool {
1031+
fileInfo, err := os.Stat(filename)
1032+
if err != nil {
1033+
return false
1034+
}
1035+
return (fileInfo.Mode() & 0100) > 0
1036+
}
1037+
1038+
func ensureExecutable(filename string) error {
1039+
fileInfo, err := os.Stat(filename)
1040+
if err != nil {
1041+
return err
1042+
}
1043+
if (fileInfo.Mode() & 0100) > 0 {
1044+
return nil
1045+
}
1046+
mode := fileInfo.Mode() | 0100
1047+
return os.Chmod(filename, mode)
1048+
}
1049+
1050+
// CheckDelegateHooks checks the hooks scripts for the repo
1051+
func CheckDelegateHooks(repoPath string) ([]string, error) {
1052+
hookNames, hookTpls, giteaHookTpls := getHookTemplates()
1053+
1054+
hookDir := filepath.Join(repoPath, "hooks")
1055+
results := make([]string, 0, 10)
1056+
1057+
for i, hookName := range hookNames {
1058+
oldHookPath := filepath.Join(hookDir, hookName)
1059+
newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
1060+
1061+
cont := false
1062+
if !com.IsExist(oldHookPath) {
1063+
results = append(results, fmt.Sprintf("old hook file %s does not exist", oldHookPath))
1064+
cont = true
1065+
}
1066+
if !com.IsExist(oldHookPath + ".d") {
1067+
results = append(results, fmt.Sprintf("hooks directory %s does not exist", oldHookPath+".d"))
1068+
cont = true
1069+
}
1070+
if !com.IsExist(newHookPath) {
1071+
results = append(results, fmt.Sprintf("new hook file %s does not exist", newHookPath))
1072+
cont = true
1073+
}
1074+
if cont {
1075+
continue
1076+
}
1077+
contents, err := ioutil.ReadFile(oldHookPath)
1078+
if err != nil {
1079+
return results, err
1080+
}
1081+
if string(contents) != hookTpls[i] {
1082+
results = append(results, fmt.Sprintf("old hook file %s is out of date", oldHookPath))
1083+
}
1084+
if !checkExecutable(oldHookPath) {
1085+
results = append(results, fmt.Sprintf("old hook file %s is not executable", oldHookPath))
1086+
}
1087+
contents, err = ioutil.ReadFile(newHookPath)
1088+
if err != nil {
1089+
return results, err
1090+
}
1091+
if string(contents) != giteaHookTpls[i] {
1092+
results = append(results, fmt.Sprintf("new hook file %s is out of date", newHookPath))
1093+
}
1094+
if !checkExecutable(newHookPath) {
1095+
results = append(results, fmt.Sprintf("new hook file %s is not executable", newHookPath))
1096+
}
1097+
}
1098+
return results, nil
1099+
}
10211100

10221101
// initRepoCommit temporarily changes with work directory.
10231102
func initRepoCommit(tmpPath string, repo *Repository, u *User) (err error) {

models/ssh_key.go

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"encoding/pem"
1616
"errors"
1717
"fmt"
18+
"io"
1819
"io/ioutil"
1920
"math/big"
2021
"os"
@@ -687,14 +688,29 @@ func rewriteAllPublicKeys(e Engine) error {
687688
}
688689
}
689690

690-
err = e.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
691-
_, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
691+
if err := regeneratePublicKeys(e, t); err != nil {
692+
return err
693+
}
694+
695+
t.Close()
696+
return os.Rename(tmpPath, fPath)
697+
}
698+
699+
// RegeneratePublicKeys regenerates the authorized_keys file
700+
func RegeneratePublicKeys(t io.Writer) error {
701+
return regeneratePublicKeys(x, t)
702+
}
703+
704+
func regeneratePublicKeys(e Engine, t io.Writer) error {
705+
err := e.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
706+
_, err = t.Write([]byte((bean.(*PublicKey)).AuthorizedString()))
692707
return err
693708
})
694709
if err != nil {
695710
return err
696711
}
697712

713+
fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
698714
if com.IsExist(fPath) {
699715
f, err := os.Open(fPath)
700716
if err != nil {
@@ -707,17 +723,15 @@ func rewriteAllPublicKeys(e Engine) error {
707723
scanner.Scan()
708724
continue
709725
}
710-
_, err = t.WriteString(line + "\n")
726+
_, err = t.Write([]byte(line + "\n"))
711727
if err != nil {
712728
f.Close()
713729
return err
714730
}
715731
}
716732
f.Close()
717733
}
718-
719-
t.Close()
720-
return os.Rename(tmpPath, fPath)
734+
return nil
721735
}
722736

723737
// ________ .__ ____ __.

modules/options/dynamic.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,8 @@ func fileFromDir(name string) ([]byte, error) {
9898

9999
return []byte{}, fmt.Errorf("Asset file does not exist: %s", name)
100100
}
101+
102+
// IsDynamic will return false when using embedded data (-tags bindata)
103+
func IsDynamic() bool {
104+
return true
105+
}

modules/options/static.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,8 @@ func fileFromDir(name string) ([]byte, error) {
112112

113113
return ioutil.ReadAll(f)
114114
}
115+
116+
// IsDynamic will return false when using embedded data (-tags bindata)
117+
func IsDynamic() bool {
118+
return false
119+
}

0 commit comments

Comments
 (0)