Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple Gitea Doctor improvements #10943

Merged
merged 16 commits into from
Apr 6, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
300 changes: 268 additions & 32 deletions cmd/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@ import (
"path/filepath"
"regexp"
"strings"
"text/tabwriter"

"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/options"
"code.gitea.io/gitea/modules/setting"
"xorm.io/builder"

"github.com/urfave/cli"
)
Expand All @@ -28,10 +32,34 @@ var CmdDoctor = cli.Command{
Usage: "Diagnose problems",
Description: "A command to diagnose problems with the current Gitea instance according to the given configuration.",
Action: runDoctor,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "list",
jolheiser marked this conversation as resolved.
Show resolved Hide resolved
Usage: "List the available checks",
},
cli.BoolFlag{
Name: "default",
Usage: "Run the default checks (if neither run or all is set this is the default behaviour)",
zeripath marked this conversation as resolved.
Show resolved Hide resolved
},
cli.StringSliceFlag{
Name: "run",
Usage: "Run the provided checks - if default is set the default checks will also run",
zeripath marked this conversation as resolved.
Show resolved Hide resolved
},
cli.BoolFlag{
Name: "all",
Usage: "Run all the available checks",
},
cli.BoolFlag{
Name: "fix",
Usage: "Automatically fix if we can",
zeripath marked this conversation as resolved.
Show resolved Hide resolved
},
},
}

type check struct {
title string
name string
isDefault bool
f func(ctx *cli.Context) ([]string, error)
abortIfFailed bool
skipDatabaseInit bool
Expand All @@ -42,13 +70,23 @@ var checklist = []check{
{
// NOTE: this check should be the first in the list
title: "Check paths and basic configuration",
name: "paths",
isDefault: true,
f: runDoctorPathInfo,
abortIfFailed: true,
skipDatabaseInit: true,
},
{
title: "Check if OpenSSH authorized_keys file id correct",
f: runDoctorLocationMoved,
title: "Check if OpenSSH authorized_keys file id correct",
zeripath marked this conversation as resolved.
Show resolved Hide resolved
name: "authorized_keys",
isDefault: true,
f: runDoctorLocationMoved,
},
{
zeripath marked this conversation as resolved.
Show resolved Hide resolved
title: "Recalculate merge bases",
name: "recalculate_merge_bases",
isDefault: false,
f: runDoctorPRMergeBase,
},
// more checks please append here
}
Expand All @@ -60,9 +98,55 @@ func runDoctor(ctx *cli.Context) error {
log.DelNamedLogger("console")
log.DelNamedLogger(log.DEFAULT)

if ctx.IsSet("list") {
w := tabwriter.NewWriter(os.Stdout, 0, 8, 0, '\t', 0)
_, _ = w.Write([]byte("Default\tName\tTitle\n"))
for _, check := range checklist {
if check.isDefault {
_, _ = w.Write([]byte{'*'})
}
_, _ = w.Write([]byte{'\t'})
_, _ = w.Write([]byte(check.name))
_, _ = w.Write([]byte{'\t'})
_, _ = w.Write([]byte(check.title))
_, _ = w.Write([]byte{'\n'})
}
return w.Flush()
}

var checks []check
if ctx.Bool("all") {
checks = checklist
} else if ctx.IsSet("run") {
addDefault := ctx.Bool("default")
names := ctx.StringSlice("run")
for i, name := range names {
names[i] = strings.ToLower(strings.TrimSpace(name))
}

for _, check := range checklist {
if addDefault && check.isDefault {
checks = append(checks, check)
continue
}
for _, name := range names {
if name == check.name {
checks = append(checks, check)
break
}
}
}
} else {
for _, check := range checklist {
if check.isDefault {
checks = append(checks, check)
}
}
}

dbIsInit := false

for i, check := range checklist {
for i, check := range checks {
if !dbIsInit && !check.skipDatabaseInit {
// Only open database after the most basic configuration check
if err := initDB(); err != nil {
Expand Down Expand Up @@ -115,16 +199,31 @@ func runDoctorPathInfo(ctx *cli.Context) ([]string, error) {

check := func(name, path string, is_dir, required, is_write bool) {
res = append(res, fmt.Sprintf("%-25s '%s'", name+":", path))
if fi, err := os.Stat(path); err != nil {
fi, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) && ctx.Bool("fix") && is_dir {
if err := os.MkdirAll(path, 0777); err != nil {
res = append(res, fmt.Sprintf(" ERROR: %v", err))
fail = true
return
}
fi, err = os.Stat(path)
}
}
if err != nil {
if required {
res = append(res, fmt.Sprintf(" ERROR: %v", err))
fail = true
} else {
res = append(res, fmt.Sprintf(" NOTICE: not accessible (%v)", err))
return
}
} else if is_dir && !fi.IsDir() {
res = append(res, fmt.Sprintf(" NOTICE: not accessible (%v)", err))
return
}

if is_dir && !fi.IsDir() {
res = append(res, " ERROR: not a directory")
fail = true
return
} else if !is_dir && !fi.Mode().IsRegular() {
res = append(res, " ERROR: not a regular file")
fail = true
Expand Down Expand Up @@ -171,6 +270,10 @@ func runDoctorWritableDir(path string) error {
return nil
}

const tplCommentPrefix = `# gitea public key`

var giteaExpected = regexp.MustCompile(`^[ \t]*(?:command=")([^ ]+) --config='([^']+)' serv key-([^"]+)",(?:[^ ]+) ssh-rsa ([^ ]+) ([^ ]+)[ \t]*$`)

func runDoctorLocationMoved(ctx *cli.Context) ([]string, error) {
if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
return nil, nil
Expand All @@ -183,45 +286,178 @@ func runDoctorLocationMoved(ctx *cli.Context) ([]string, error) {
}
defer f.Close()

var firstline string
runFix := 0
results := make([]string, 0, 10)

scanner := bufio.NewScanner(f)
for scanner.Scan() {
firstline = strings.TrimSpace(scanner.Text())
if len(firstline) == 0 || firstline[0] == '#' {
continue
line := scanner.Text()
if strings.HasPrefix(line, tplCommentPrefix) {
res, err := checkGiteaLine(strings.TrimSpace(scanner.Text()))
if err != nil {
if ctx.Bool("fix") {
results = append(results, err.Error())
runFix++
} else {
return nil, err
}
}
if len(res) > 0 {
if ctx.Bool("fix") {
runFix++
} else {
results = append(results, res)
}
}
}
break
}

// command="/Volumes/data/Projects/gitea/gitea/gitea --config
if len(firstline) > 0 {
exp := regexp.MustCompile(`^[ \t]*(?:command=")([^ ]+) --config='([^']+)' serv key-([^"]+)",(?:[^ ]+) ssh-rsa ([^ ]+) ([^ ]+)[ \t]*$`)

// command="/home/user/gitea --config='/home/user/etc/app.ini' serv key-999",option-1,option-2,option-n ssh-rsa public-key-value key-name
res := exp.FindStringSubmatch(firstline)
if res == nil {
return nil, errors.New("Unknow authorized_keys format")
}

giteaPath := res[1] // => /home/user/gitea
iniPath := res[2] // => /home/user/etc/app.ini

p, err := exePath()
if runFix > 0 {
err := models.RewriteAllPublicKeys()
if err != nil {
return nil, err
}
p, err = filepath.Abs(p)
results = append(results, fmt.Sprintf("%d keys needed to be rewritten", runFix))
}

return results, nil
}

func checkGiteaLine(line string) (string, error) {
if len(line) == 0 {
return "", nil
}

fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")

// command="/home/user/gitea --config='/home/user/etc/app.ini' serv key-999",option-1,option-2,option-n ssh-rsa public-key-value key-name
res := giteaExpected.FindStringSubmatch(line)
if res == nil {
return "", errors.New("Unknown authorized_keys format")
}

giteaPath := res[1] // => /home/user/gitea
iniPath := res[2] // => /home/user/etc/app.ini

p, err := exePath()
if err != nil {
return "", err
}
p, err = filepath.Abs(p)
if err != nil {
return "", err
}

if len(giteaPath) > 0 && giteaPath != p {
return fmt.Sprintf("Gitea exe path wants %s but %s on %s", p, giteaPath, fPath), nil
}
if len(iniPath) > 0 && iniPath != setting.CustomConf {
return fmt.Sprintf("Gitea config path wants %s but %s on %s", setting.CustomConf, iniPath, fPath), nil
}

return "", nil
}

func runDoctorPRMergeBase(ctx *cli.Context) ([]string, error) {
opts := &models.SearchRepoOptions{
ListOptions: models.ListOptions{
Page: 1,
PageSize: 50,
},
}
results := make([]string, 0, 10)
numRepos := 0
numPRs := 0
numPRsUpdated := 0
for {
repos, _, err := models.SearchRepositoryByCondition(opts, builder.NewCond(), false)
if err != nil {
return nil, err
}

if len(giteaPath) > 0 && giteaPath != p {
return []string{fmt.Sprintf("Gitea exe path wants %s but %s on %s", p, giteaPath, fPath)}, nil
for _, repo := range repos {
prOpts := &models.PullRequestsOptions{
ListOptions: models.ListOptions{
Page: 1,
PageSize: 50,
},
}
for {
prs, _, err := models.PullRequests(repo.ID, prOpts)
if err != nil {
return nil, err
}
for _, pr := range prs {
pr.BaseRepo = repo
repoPath := repo.RepoPath()

oldMergeBase := pr.MergeBase

if !pr.HasMerged {
var err error
pr.MergeBase, err = git.NewCommand("merge-base", "--", pr.BaseBranch, pr.GetGitRefName()).RunInDir(repoPath)
if err != nil {
var err2 error
pr.MergeBase, err2 = git.NewCommand("rev-parse", git.BranchPrefix+pr.BaseBranch).RunInDir(repoPath)
if err2 != nil {
results = append(results, fmt.Sprintf("WARN: Unable to get merge base for PR ID %d, #%d onto %s in %s/%s", pr.ID, pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name))
log.Error("Unable to get merge base for PR ID %d, Index %d in %s/%s. Error: %v & %v", pr.ID, pr.Index, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, err, err2)
continue
}
}
} else {
parentsString, err := git.NewCommand("rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath)
if err != nil {
results = append(results, fmt.Sprintf("WARN: Unable to get parents for merged PR ID %d, #%d onto %s in %s/%s", pr.ID, pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name))
log.Error("Unable to get parents for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, err)
continue
}
parents := strings.Split(strings.TrimSpace(parentsString), " ")
if len(parents) < 2 {
continue
}

args := append([]string{"merge-base", "--"}, parents[1:]...)
args = append(args, pr.GetGitRefName())

pr.MergeBase, err = git.NewCommand(args...).RunInDir(repoPath)
if err != nil {
results = append(results, fmt.Sprintf("WARN: Unable to get merge base for merged PR ID %d, #%d onto %s in %s/%s", pr.ID, pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name))
log.Error("Unable to get merge base for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, err)
continue
}
}
pr.MergeBase = strings.TrimSpace(pr.MergeBase)
if pr.MergeBase != oldMergeBase {
if ctx.Bool("fix") {
if err := pr.UpdateCols("merge_base"); err != nil {
return results, err
}
} else {
results = append(results, fmt.Sprintf("#%d onto %s in %s/%s: MergeBase should be %s but is %s", pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, oldMergeBase, pr.MergeBase))
}
numPRsUpdated++
}
}
numPRs += len(prs)
if len(prs) < 50 {
break
}
}
prOpts.Page++
}
if len(iniPath) > 0 && iniPath != setting.CustomConf {
return []string{fmt.Sprintf("Gitea config path wants %s but %s on %s", setting.CustomConf, iniPath, fPath)}, nil

numRepos += len(repos)
if len(repos) < 50 {
break
}
opts.Page++
}
if ctx.Bool("fix") {
results = append(results, fmt.Sprintf("%d PRs with incorrect mergebases of %d PRs total in %d repos", numPRsUpdated, numPRs, numRepos))
} else {
results = append(results, fmt.Sprintf("%d PRs updated of %d PRs total in %d repos", numPRsUpdated, numPRs, numRepos))
}

return nil, nil
return results, nil
}