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.

doctor.go 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. // Copyright 2019 The Gitea 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. "bufio"
  7. "bytes"
  8. "context"
  9. "fmt"
  10. "io/ioutil"
  11. golog "log"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "strings"
  16. "text/tabwriter"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/models/migrations"
  19. "code.gitea.io/gitea/modules/git"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/options"
  22. "code.gitea.io/gitea/modules/repository"
  23. "code.gitea.io/gitea/modules/setting"
  24. "xorm.io/builder"
  25. "github.com/urfave/cli"
  26. )
  27. // CmdDoctor represents the available doctor sub-command.
  28. var CmdDoctor = cli.Command{
  29. Name: "doctor",
  30. Usage: "Diagnose problems",
  31. Description: "A command to diagnose problems with the current Gitea instance according to the given configuration.",
  32. Action: runDoctor,
  33. Flags: []cli.Flag{
  34. cli.BoolFlag{
  35. Name: "list",
  36. Usage: "List the available checks",
  37. },
  38. cli.BoolFlag{
  39. Name: "default",
  40. Usage: "Run the default checks (if neither --run or --all is set, this is the default behaviour)",
  41. },
  42. cli.StringSliceFlag{
  43. Name: "run",
  44. Usage: "Run the provided checks - (if --default is set, the default checks will also run)",
  45. },
  46. cli.BoolFlag{
  47. Name: "all",
  48. Usage: "Run all the available checks",
  49. },
  50. cli.BoolFlag{
  51. Name: "fix",
  52. Usage: "Automatically fix what we can",
  53. },
  54. cli.StringFlag{
  55. Name: "log-file",
  56. Usage: `Name of the log file (default: "doctor.log"). Set to "-" to output to stdout, set to "" to disable`,
  57. },
  58. },
  59. }
  60. type check struct {
  61. title string
  62. name string
  63. isDefault bool
  64. f func(ctx *cli.Context) ([]string, error)
  65. abortIfFailed bool
  66. skipDatabaseInit bool
  67. }
  68. // checklist represents list for all checks
  69. var checklist = []check{
  70. {
  71. // NOTE: this check should be the first in the list
  72. title: "Check paths and basic configuration",
  73. name: "paths",
  74. isDefault: true,
  75. f: runDoctorPathInfo,
  76. abortIfFailed: true,
  77. skipDatabaseInit: true,
  78. },
  79. {
  80. title: "Check Database Version",
  81. name: "check-db-version",
  82. isDefault: true,
  83. f: runDoctorCheckDBVersion,
  84. abortIfFailed: false,
  85. },
  86. {
  87. title: "Check consistency of database",
  88. name: "check-db-consistency",
  89. isDefault: false,
  90. f: runDoctorCheckDBConsistency,
  91. },
  92. {
  93. title: "Check if OpenSSH authorized_keys file is up-to-date",
  94. name: "authorized_keys",
  95. isDefault: true,
  96. f: runDoctorAuthorizedKeys,
  97. },
  98. {
  99. title: "Check if SCRIPT_TYPE is available",
  100. name: "script-type",
  101. isDefault: false,
  102. f: runDoctorScriptType,
  103. },
  104. {
  105. title: "Check if hook files are up-to-date and executable",
  106. name: "hooks",
  107. isDefault: false,
  108. f: runDoctorHooks,
  109. },
  110. {
  111. title: "Recalculate merge bases",
  112. name: "recalculate_merge_bases",
  113. isDefault: false,
  114. f: runDoctorPRMergeBase,
  115. },
  116. {
  117. title: "Recalculate Stars number for all user",
  118. name: "recalculate_stars_number",
  119. isDefault: false,
  120. f: runDoctorUserStarNum,
  121. },
  122. // more checks please append here
  123. }
  124. func runDoctor(ctx *cli.Context) error {
  125. // Silence the default loggers
  126. log.DelNamedLogger("console")
  127. log.DelNamedLogger(log.DEFAULT)
  128. // Now setup our own
  129. logFile := ctx.String("log-file")
  130. if !ctx.IsSet("log-file") {
  131. logFile = "doctor.log"
  132. }
  133. if len(logFile) == 0 {
  134. log.NewLogger(1000, "doctor", "console", `{"level":"NONE","stacktracelevel":"NONE","colorize":"%t"}`)
  135. } else if logFile == "-" {
  136. log.NewLogger(1000, "doctor", "console", `{"level":"trace","stacktracelevel":"NONE"}`)
  137. } else {
  138. log.NewLogger(1000, "doctor", "file", fmt.Sprintf(`{"filename":%q,"level":"trace","stacktracelevel":"NONE"}`, logFile))
  139. }
  140. // Finally redirect the default golog to here
  141. golog.SetFlags(0)
  142. golog.SetPrefix("")
  143. golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
  144. if ctx.IsSet("list") {
  145. w := tabwriter.NewWriter(os.Stdout, 0, 8, 0, '\t', 0)
  146. _, _ = w.Write([]byte("Default\tName\tTitle\n"))
  147. for _, check := range checklist {
  148. if check.isDefault {
  149. _, _ = w.Write([]byte{'*'})
  150. }
  151. _, _ = w.Write([]byte{'\t'})
  152. _, _ = w.Write([]byte(check.name))
  153. _, _ = w.Write([]byte{'\t'})
  154. _, _ = w.Write([]byte(check.title))
  155. _, _ = w.Write([]byte{'\n'})
  156. }
  157. return w.Flush()
  158. }
  159. var checks []check
  160. if ctx.Bool("all") {
  161. checks = checklist
  162. } else if ctx.IsSet("run") {
  163. addDefault := ctx.Bool("default")
  164. names := ctx.StringSlice("run")
  165. for i, name := range names {
  166. names[i] = strings.ToLower(strings.TrimSpace(name))
  167. }
  168. for _, check := range checklist {
  169. if addDefault && check.isDefault {
  170. checks = append(checks, check)
  171. continue
  172. }
  173. for _, name := range names {
  174. if name == check.name {
  175. checks = append(checks, check)
  176. break
  177. }
  178. }
  179. }
  180. } else {
  181. for _, check := range checklist {
  182. if check.isDefault {
  183. checks = append(checks, check)
  184. }
  185. }
  186. }
  187. dbIsInit := false
  188. for i, check := range checks {
  189. if !dbIsInit && !check.skipDatabaseInit {
  190. // Only open database after the most basic configuration check
  191. setting.EnableXORMLog = false
  192. if err := initDBDisableConsole(true); err != nil {
  193. fmt.Println(err)
  194. fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
  195. return nil
  196. }
  197. dbIsInit = true
  198. }
  199. fmt.Println("[", i+1, "]", check.title)
  200. messages, err := check.f(ctx)
  201. for _, message := range messages {
  202. fmt.Println("-", message)
  203. }
  204. if err != nil {
  205. fmt.Println("Error:", err)
  206. if check.abortIfFailed {
  207. return nil
  208. }
  209. } else {
  210. fmt.Println("OK.")
  211. }
  212. fmt.Println()
  213. }
  214. return nil
  215. }
  216. func runDoctorPathInfo(ctx *cli.Context) ([]string, error) {
  217. res := make([]string, 0, 10)
  218. if fi, err := os.Stat(setting.CustomConf); err != nil || !fi.Mode().IsRegular() {
  219. res = append(res, fmt.Sprintf("Failed to find configuration file at '%s'.", setting.CustomConf))
  220. res = append(res, fmt.Sprintf("If you've never ran Gitea yet, this is normal and '%s' will be created for you on first run.", setting.CustomConf))
  221. res = append(res, "Otherwise check that you are running this command from the correct path and/or provide a `--config` parameter.")
  222. return res, fmt.Errorf("can't proceed without a configuration file")
  223. }
  224. setting.NewContext()
  225. fail := false
  226. check := func(name, path string, is_dir, required, is_write bool) {
  227. res = append(res, fmt.Sprintf("%-25s '%s'", name+":", path))
  228. fi, err := os.Stat(path)
  229. if err != nil {
  230. if os.IsNotExist(err) && ctx.Bool("fix") && is_dir {
  231. if err := os.MkdirAll(path, 0777); err != nil {
  232. res = append(res, fmt.Sprintf(" ERROR: %v", err))
  233. fail = true
  234. return
  235. }
  236. fi, err = os.Stat(path)
  237. }
  238. }
  239. if err != nil {
  240. if required {
  241. res = append(res, fmt.Sprintf(" ERROR: %v", err))
  242. fail = true
  243. return
  244. }
  245. res = append(res, fmt.Sprintf(" NOTICE: not accessible (%v)", err))
  246. return
  247. }
  248. if is_dir && !fi.IsDir() {
  249. res = append(res, " ERROR: not a directory")
  250. fail = true
  251. return
  252. } else if !is_dir && !fi.Mode().IsRegular() {
  253. res = append(res, " ERROR: not a regular file")
  254. fail = true
  255. } else if is_write {
  256. if err := runDoctorWritableDir(path); err != nil {
  257. res = append(res, fmt.Sprintf(" ERROR: not writable: %v", err))
  258. fail = true
  259. }
  260. }
  261. }
  262. // Note print paths inside quotes to make any leading/trailing spaces evident
  263. check("Configuration File Path", setting.CustomConf, false, true, false)
  264. check("Repository Root Path", setting.RepoRootPath, true, true, true)
  265. check("Data Root Path", setting.AppDataPath, true, true, true)
  266. check("Custom File Root Path", setting.CustomPath, true, false, false)
  267. check("Work directory", setting.AppWorkPath, true, true, false)
  268. check("Log Root Path", setting.LogRootPath, true, true, true)
  269. if options.IsDynamic() {
  270. // Do not check/report on StaticRootPath if data is embedded in Gitea (-tags bindata)
  271. check("Static File Root Path", setting.StaticRootPath, true, true, false)
  272. }
  273. if fail {
  274. return res, fmt.Errorf("please check your configuration file and try again")
  275. }
  276. return res, nil
  277. }
  278. func runDoctorWritableDir(path string) error {
  279. // There's no platform-independent way of checking if a directory is writable
  280. // https://stackoverflow.com/questions/20026320/how-to-tell-if-folder-exists-and-is-writable
  281. tmpFile, err := ioutil.TempFile(path, "doctors-order")
  282. if err != nil {
  283. return err
  284. }
  285. if err := os.Remove(tmpFile.Name()); err != nil {
  286. fmt.Printf("Warning: can't remove temporary file: '%s'\n", tmpFile.Name())
  287. }
  288. tmpFile.Close()
  289. return nil
  290. }
  291. const tplCommentPrefix = `# gitea public key`
  292. func runDoctorAuthorizedKeys(ctx *cli.Context) ([]string, error) {
  293. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  294. return nil, nil
  295. }
  296. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  297. f, err := os.Open(fPath)
  298. if err != nil {
  299. if ctx.Bool("fix") {
  300. return []string{fmt.Sprintf("Error whilst opening authorized_keys: %v. Attempting regeneration", err)}, models.RewriteAllPublicKeys()
  301. }
  302. return nil, err
  303. }
  304. defer f.Close()
  305. linesInAuthorizedKeys := map[string]bool{}
  306. scanner := bufio.NewScanner(f)
  307. for scanner.Scan() {
  308. line := scanner.Text()
  309. if strings.HasPrefix(line, tplCommentPrefix) {
  310. continue
  311. }
  312. linesInAuthorizedKeys[line] = true
  313. }
  314. f.Close()
  315. // now we regenerate and check if there are any lines missing
  316. regenerated := &bytes.Buffer{}
  317. if err := models.RegeneratePublicKeys(regenerated); err != nil {
  318. return nil, err
  319. }
  320. scanner = bufio.NewScanner(regenerated)
  321. for scanner.Scan() {
  322. line := scanner.Text()
  323. if strings.HasPrefix(line, tplCommentPrefix) {
  324. continue
  325. }
  326. if ok := linesInAuthorizedKeys[line]; ok {
  327. continue
  328. }
  329. if ctx.Bool("fix") {
  330. return []string{"authorized_keys is out of date, attempting regeneration"}, models.RewriteAllPublicKeys()
  331. }
  332. return nil, fmt.Errorf(`authorized_keys is out of date and should be regenerated with "gitea admin regenerate keys" or "gitea doctor --run authorized_keys --fix"`)
  333. }
  334. return nil, nil
  335. }
  336. func runDoctorCheckDBVersion(ctx *cli.Context) ([]string, error) {
  337. if err := models.NewEngine(context.Background(), migrations.EnsureUpToDate); err != nil {
  338. if ctx.Bool("fix") {
  339. return []string{fmt.Sprintf("WARN: Got Error %v during ensure up to date", err), "Attempting to migrate to the latest DB version to fix this."}, models.NewEngine(context.Background(), migrations.Migrate)
  340. }
  341. return nil, err
  342. }
  343. return nil, nil
  344. }
  345. func iterateRepositories(each func(*models.Repository) ([]string, error)) ([]string, error) {
  346. results := []string{}
  347. err := models.Iterate(
  348. models.DefaultDBContext(),
  349. new(models.Repository),
  350. builder.Gt{"id": 0},
  351. func(idx int, bean interface{}) error {
  352. res, err := each(bean.(*models.Repository))
  353. results = append(results, res...)
  354. return err
  355. },
  356. )
  357. return results, err
  358. }
  359. func iteratePRs(repo *models.Repository, each func(*models.Repository, *models.PullRequest) ([]string, error)) ([]string, error) {
  360. results := []string{}
  361. err := models.Iterate(
  362. models.DefaultDBContext(),
  363. new(models.PullRequest),
  364. builder.Eq{"base_repo_id": repo.ID},
  365. func(idx int, bean interface{}) error {
  366. res, err := each(repo, bean.(*models.PullRequest))
  367. results = append(results, res...)
  368. return err
  369. },
  370. )
  371. return results, err
  372. }
  373. func runDoctorHooks(ctx *cli.Context) ([]string, error) {
  374. // Need to iterate across all of the repositories
  375. return iterateRepositories(func(repo *models.Repository) ([]string, error) {
  376. results, err := repository.CheckDelegateHooks(repo.RepoPath())
  377. if err != nil {
  378. return nil, err
  379. }
  380. if len(results) > 0 && ctx.Bool("fix") {
  381. return []string{fmt.Sprintf("regenerated hooks for %s", repo.FullName())}, repository.CreateDelegateHooks(repo.RepoPath())
  382. }
  383. return results, nil
  384. })
  385. }
  386. func runDoctorPRMergeBase(ctx *cli.Context) ([]string, error) {
  387. numRepos := 0
  388. numPRs := 0
  389. numPRsUpdated := 0
  390. results, err := iterateRepositories(func(repo *models.Repository) ([]string, error) {
  391. numRepos++
  392. return iteratePRs(repo, func(repo *models.Repository, pr *models.PullRequest) ([]string, error) {
  393. numPRs++
  394. results := []string{}
  395. pr.BaseRepo = repo
  396. repoPath := repo.RepoPath()
  397. oldMergeBase := pr.MergeBase
  398. if !pr.HasMerged {
  399. var err error
  400. pr.MergeBase, err = git.NewCommand("merge-base", "--", pr.BaseBranch, pr.GetGitRefName()).RunInDir(repoPath)
  401. if err != nil {
  402. var err2 error
  403. pr.MergeBase, err2 = git.NewCommand("rev-parse", git.BranchPrefix+pr.BaseBranch).RunInDir(repoPath)
  404. if err2 != nil {
  405. 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))
  406. 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)
  407. return results, nil
  408. }
  409. }
  410. } else {
  411. parentsString, err := git.NewCommand("rev-list", "--parents", "-n", "1", pr.MergedCommitID).RunInDir(repoPath)
  412. if err != nil {
  413. 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))
  414. 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)
  415. return results, nil
  416. }
  417. parents := strings.Split(strings.TrimSpace(parentsString), " ")
  418. if len(parents) < 2 {
  419. return results, nil
  420. }
  421. args := append([]string{"merge-base", "--"}, parents[1:]...)
  422. args = append(args, pr.GetGitRefName())
  423. pr.MergeBase, err = git.NewCommand(args...).RunInDir(repoPath)
  424. if err != nil {
  425. 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))
  426. 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)
  427. return results, nil
  428. }
  429. }
  430. pr.MergeBase = strings.TrimSpace(pr.MergeBase)
  431. if pr.MergeBase != oldMergeBase {
  432. if ctx.Bool("fix") {
  433. if err := pr.UpdateCols("merge_base"); err != nil {
  434. return results, err
  435. }
  436. } else {
  437. 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))
  438. }
  439. numPRsUpdated++
  440. }
  441. return results, nil
  442. })
  443. })
  444. if ctx.Bool("fix") {
  445. results = append(results, fmt.Sprintf("%d PR mergebases updated of %d PRs total in %d repos", numPRsUpdated, numPRs, numRepos))
  446. } else {
  447. if numPRsUpdated > 0 && err == nil {
  448. return results, fmt.Errorf("%d PRs with incorrect mergebases of %d PRs total in %d repos", numPRsUpdated, numPRs, numRepos)
  449. }
  450. results = append(results, fmt.Sprintf("%d PRs with incorrect mergebases of %d PRs total in %d repos", numPRsUpdated, numPRs, numRepos))
  451. }
  452. return results, err
  453. }
  454. func runDoctorUserStarNum(ctx *cli.Context) ([]string, error) {
  455. return nil, models.DoctorUserStarNum()
  456. }
  457. func runDoctorScriptType(ctx *cli.Context) ([]string, error) {
  458. path, err := exec.LookPath(setting.ScriptType)
  459. if err != nil {
  460. return []string{fmt.Sprintf("ScriptType %s is not on the current PATH", setting.ScriptType)}, err
  461. }
  462. return []string{fmt.Sprintf("ScriptType %s is on the current PATH at %s", setting.ScriptType, path)}, nil
  463. }
  464. func runDoctorCheckDBConsistency(ctx *cli.Context) ([]string, error) {
  465. var results []string
  466. // make sure DB version is uptodate
  467. if err := models.NewEngine(context.Background(), migrations.EnsureUpToDate); err != nil {
  468. return nil, fmt.Errorf("model version on the database does not match the current Gitea version. Model consistency will not be checked until the database is upgraded")
  469. }
  470. //find labels without existing repo or org
  471. count, err := models.CountOrphanedLabels()
  472. if err != nil {
  473. return nil, err
  474. }
  475. if count > 0 {
  476. if ctx.Bool("fix") {
  477. if err = models.DeleteOrphanedLabels(); err != nil {
  478. return nil, err
  479. }
  480. results = append(results, fmt.Sprintf("%d labels without existing repository/organisation deleted", count))
  481. } else {
  482. results = append(results, fmt.Sprintf("%d labels without existing repository/organisation", count))
  483. }
  484. }
  485. //find issues without existing repository
  486. count, err = models.CountOrphanedIssues()
  487. if err != nil {
  488. return nil, err
  489. }
  490. if count > 0 {
  491. if ctx.Bool("fix") {
  492. if err = models.DeleteOrphanedIssues(); err != nil {
  493. return nil, err
  494. }
  495. results = append(results, fmt.Sprintf("%d issues without existing repository deleted", count))
  496. } else {
  497. results = append(results, fmt.Sprintf("%d issues without existing repository", count))
  498. }
  499. }
  500. //find pulls without existing issues
  501. count, err = models.CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
  502. if err != nil {
  503. return nil, err
  504. }
  505. if count > 0 {
  506. if ctx.Bool("fix") {
  507. if err = models.DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id"); err != nil {
  508. return nil, err
  509. }
  510. results = append(results, fmt.Sprintf("%d pull requests without existing issue deleted", count))
  511. } else {
  512. results = append(results, fmt.Sprintf("%d pull requests without existing issue", count))
  513. }
  514. }
  515. //find tracked times without existing issues/pulls
  516. count, err = models.CountOrphanedObjects("tracked_time", "issue", "tracked_time.issue_id=issue.id")
  517. if err != nil {
  518. return nil, err
  519. }
  520. if count > 0 {
  521. if ctx.Bool("fix") {
  522. if err = models.DeleteOrphanedObjects("tracked_time", "issue", "tracked_time.issue_id=issue.id"); err != nil {
  523. return nil, err
  524. }
  525. results = append(results, fmt.Sprintf("%d tracked times without existing issue deleted", count))
  526. } else {
  527. results = append(results, fmt.Sprintf("%d tracked times without existing issue", count))
  528. }
  529. }
  530. count, err = models.CountNullArchivedRepository()
  531. if err != nil {
  532. return nil, err
  533. }
  534. if count > 0 {
  535. if ctx.Bool("fix") {
  536. updatedCount, err := models.FixNullArchivedRepository()
  537. if err != nil {
  538. return nil, err
  539. }
  540. results = append(results, fmt.Sprintf("%d repositories with null is_archived updated", updatedCount))
  541. } else {
  542. results = append(results, fmt.Sprintf("%d repositories with null is_archived", count))
  543. }
  544. }
  545. //ToDo: function to recalc all counters
  546. return results, nil
  547. }