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 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/options"
  17. "code.gitea.io/gitea/modules/setting"
  18. "github.com/urfave/cli"
  19. )
  20. // CmdDoctor represents the available doctor sub-command.
  21. var CmdDoctor = cli.Command{
  22. Name: "doctor",
  23. Usage: "Diagnose problems",
  24. Description: "A command to diagnose problems with the current Gitea instance according to the given configuration.",
  25. Action: runDoctor,
  26. }
  27. type check struct {
  28. title string
  29. f func(ctx *cli.Context) ([]string, error)
  30. abortIfFailed bool
  31. skipDatabaseInit bool
  32. }
  33. // checklist represents list for all checks
  34. var checklist = []check{
  35. {
  36. // NOTE: this check should be the first in the list
  37. title: "Check paths and basic configuration",
  38. f: runDoctorPathInfo,
  39. abortIfFailed: true,
  40. skipDatabaseInit: true,
  41. },
  42. {
  43. title: "Check if OpenSSH authorized_keys file id correct",
  44. f: runDoctorLocationMoved,
  45. },
  46. // more checks please append here
  47. }
  48. func runDoctor(ctx *cli.Context) error {
  49. // Silence the console logger
  50. // TODO: Redirect all logs into `doctor.log` ignoring any other log configuration
  51. log.DelNamedLogger("console")
  52. log.DelNamedLogger(log.DEFAULT)
  53. dbIsInit := false
  54. for i, check := range checklist {
  55. if !dbIsInit && !check.skipDatabaseInit {
  56. // Only open database after the most basic configuration check
  57. if err := initDB(); err != nil {
  58. fmt.Println(err)
  59. fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
  60. return nil
  61. }
  62. dbIsInit = true
  63. }
  64. fmt.Println("[", i+1, "]", check.title)
  65. messages, err := check.f(ctx)
  66. for _, message := range messages {
  67. fmt.Println("-", message)
  68. }
  69. if err != nil {
  70. fmt.Println("Error:", err)
  71. if check.abortIfFailed {
  72. return nil
  73. }
  74. } else {
  75. fmt.Println("OK.")
  76. }
  77. fmt.Println()
  78. }
  79. return nil
  80. }
  81. func exePath() (string, error) {
  82. file, err := exec.LookPath(os.Args[0])
  83. if err != nil {
  84. return "", err
  85. }
  86. return filepath.Abs(file)
  87. }
  88. func runDoctorPathInfo(ctx *cli.Context) ([]string, error) {
  89. res := make([]string, 0, 10)
  90. if fi, err := os.Stat(setting.CustomConf); err != nil || !fi.Mode().IsRegular() {
  91. res = append(res, fmt.Sprintf("Failed to find configuration file at '%s'.", setting.CustomConf))
  92. 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))
  93. res = append(res, "Otherwise check that you are running this command from the correct path and/or provide a `--config` parameter.")
  94. return res, fmt.Errorf("can't proceed without a configuration file")
  95. }
  96. setting.NewContext()
  97. fail := false
  98. check := func(name, path string, is_dir, required, is_write bool) {
  99. res = append(res, fmt.Sprintf("%-25s '%s'", name+":", path))
  100. if fi, err := os.Stat(path); err != nil {
  101. if required {
  102. res = append(res, fmt.Sprintf(" ERROR: %v", err))
  103. fail = true
  104. } else {
  105. res = append(res, fmt.Sprintf(" NOTICE: not accessible (%v)", err))
  106. }
  107. } else if is_dir && !fi.IsDir() {
  108. res = append(res, " ERROR: not a directory")
  109. fail = true
  110. } else if !is_dir && !fi.Mode().IsRegular() {
  111. res = append(res, " ERROR: not a regular file")
  112. fail = true
  113. } else if is_write {
  114. if err := runDoctorWritableDir(path); err != nil {
  115. res = append(res, fmt.Sprintf(" ERROR: not writable: %v", err))
  116. fail = true
  117. }
  118. }
  119. }
  120. // Note print paths inside quotes to make any leading/trailing spaces evident
  121. check("Configuration File Path", setting.CustomConf, false, true, false)
  122. check("Repository Root Path", setting.RepoRootPath, true, true, true)
  123. check("Data Root Path", setting.AppDataPath, true, true, true)
  124. check("Custom File Root Path", setting.CustomPath, true, false, false)
  125. check("Work directory", setting.AppWorkPath, true, true, false)
  126. check("Log Root Path", setting.LogRootPath, true, true, true)
  127. if options.IsDynamic() {
  128. // Do not check/report on StaticRootPath if data is embedded in Gitea (-tags bindata)
  129. check("Static File Root Path", setting.StaticRootPath, true, true, false)
  130. }
  131. if fail {
  132. return res, fmt.Errorf("please check your configuration file and try again")
  133. }
  134. return res, nil
  135. }
  136. func runDoctorWritableDir(path string) error {
  137. // There's no platform-independent way of checking if a directory is writable
  138. // https://stackoverflow.com/questions/20026320/how-to-tell-if-folder-exists-and-is-writable
  139. tmpFile, err := ioutil.TempFile(path, "doctors-order")
  140. if err != nil {
  141. return err
  142. }
  143. if err := os.Remove(tmpFile.Name()); err != nil {
  144. fmt.Printf("Warning: can't remove temporary file: '%s'\n", tmpFile.Name())
  145. }
  146. tmpFile.Close()
  147. return nil
  148. }
  149. func runDoctorLocationMoved(ctx *cli.Context) ([]string, error) {
  150. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  151. return nil, nil
  152. }
  153. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  154. f, err := os.Open(fPath)
  155. if err != nil {
  156. return nil, err
  157. }
  158. defer f.Close()
  159. var firstline string
  160. scanner := bufio.NewScanner(f)
  161. for scanner.Scan() {
  162. firstline = strings.TrimSpace(scanner.Text())
  163. if len(firstline) == 0 || firstline[0] == '#' {
  164. continue
  165. }
  166. break
  167. }
  168. // command="/Volumes/data/Projects/gitea/gitea/gitea --config
  169. if len(firstline) > 0 {
  170. exp := regexp.MustCompile(`^[ \t]*(?:command=")([^ ]+) --config='([^']+)' serv key-([^"]+)",(?:[^ ]+) ssh-rsa ([^ ]+) ([^ ]+)[ \t]*$`)
  171. // 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
  172. res := exp.FindStringSubmatch(firstline)
  173. if res == nil {
  174. return nil, errors.New("Unknow authorized_keys format")
  175. }
  176. giteaPath := res[1] // => /home/user/gitea
  177. iniPath := res[2] // => /home/user/etc/app.ini
  178. p, err := exePath()
  179. if err != nil {
  180. return nil, err
  181. }
  182. p, err = filepath.Abs(p)
  183. if err != nil {
  184. return nil, err
  185. }
  186. if len(giteaPath) > 0 && giteaPath != p {
  187. return []string{fmt.Sprintf("Gitea exe path wants %s but %s on %s", p, giteaPath, fPath)}, nil
  188. }
  189. if len(iniPath) > 0 && iniPath != setting.CustomConf {
  190. return []string{fmt.Sprintf("Gitea config path wants %s but %s on %s", setting.CustomConf, iniPath, fPath)}, nil
  191. }
  192. }
  193. return nil, nil
  194. }