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.

607 lines
18 KiB

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