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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "errors"
  6. "fmt"
  7. golog "log"
  8. "os"
  9. "strings"
  10. "text/tabwriter"
  11. "code.gitea.io/gitea/models/db"
  12. "code.gitea.io/gitea/models/migrations"
  13. migrate_base "code.gitea.io/gitea/models/migrations/base"
  14. "code.gitea.io/gitea/modules/doctor"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/urfave/cli"
  18. "xorm.io/xorm"
  19. )
  20. // CmdDoctor represents the available doctor sub-command.
  21. var CmdDoctor = cli.Command{
  22. Name: "doctor",
  23. Usage: "Diagnose and optionally fix problems",
  24. Description: "A command to diagnose problems with the current Gitea instance according to the given configuration. Some problems can optionally be fixed by modifying the database or data storage.",
  25. Action: runDoctor,
  26. Flags: []cli.Flag{
  27. cli.BoolFlag{
  28. Name: "list",
  29. Usage: "List the available checks",
  30. },
  31. cli.BoolFlag{
  32. Name: "default",
  33. Usage: "Run the default checks (if neither --run or --all is set, this is the default behaviour)",
  34. },
  35. cli.StringSliceFlag{
  36. Name: "run",
  37. Usage: "Run the provided checks - (if --default is set, the default checks will also run)",
  38. },
  39. cli.BoolFlag{
  40. Name: "all",
  41. Usage: "Run all the available checks",
  42. },
  43. cli.BoolFlag{
  44. Name: "fix",
  45. Usage: "Automatically fix what we can",
  46. },
  47. cli.StringFlag{
  48. Name: "log-file",
  49. Usage: `Name of the log file (default: "doctor.log"). Set to "-" to output to stdout, set to "" to disable`,
  50. },
  51. cli.BoolFlag{
  52. Name: "color, H",
  53. Usage: "Use color for outputted information",
  54. },
  55. },
  56. Subcommands: []cli.Command{
  57. cmdRecreateTable,
  58. },
  59. }
  60. var cmdRecreateTable = cli.Command{
  61. Name: "recreate-table",
  62. Usage: "Recreate tables from XORM definitions and copy the data.",
  63. ArgsUsage: "[TABLE]... : (TABLEs to recreate - leave blank for all)",
  64. Flags: []cli.Flag{
  65. cli.BoolFlag{
  66. Name: "debug",
  67. Usage: "Print SQL commands sent",
  68. },
  69. },
  70. Description: `The database definitions Gitea uses change across versions, sometimes changing default values and leaving old unused columns.
  71. This command will cause Xorm to recreate tables, copying over the data and deleting the old table.
  72. You should back-up your database before doing this and ensure that your database is up-to-date first.`,
  73. Action: runRecreateTable,
  74. }
  75. func runRecreateTable(ctx *cli.Context) error {
  76. // Redirect the default golog to here
  77. golog.SetFlags(0)
  78. golog.SetPrefix("")
  79. golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
  80. setting.LoadFromExisting()
  81. setting.InitDBConfig()
  82. setting.EnableXORMLog = ctx.Bool("debug")
  83. setting.Database.LogSQL = ctx.Bool("debug")
  84. setting.Cfg.Section("log").Key("XORM").SetValue(",")
  85. setting.NewXORMLogService(!ctx.Bool("debug"))
  86. stdCtx, cancel := installSignals()
  87. defer cancel()
  88. if err := db.InitEngine(stdCtx); err != nil {
  89. fmt.Println(err)
  90. fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
  91. return nil
  92. }
  93. args := ctx.Args()
  94. names := make([]string, 0, ctx.NArg())
  95. for i := 0; i < ctx.NArg(); i++ {
  96. names = append(names, args.Get(i))
  97. }
  98. beans, err := db.NamesToBean(names...)
  99. if err != nil {
  100. return err
  101. }
  102. recreateTables := migrate_base.RecreateTables(beans...)
  103. return db.InitEngineWithMigration(stdCtx, func(x *xorm.Engine) error {
  104. if err := migrations.EnsureUpToDate(x); err != nil {
  105. return err
  106. }
  107. return recreateTables(x)
  108. })
  109. }
  110. func setDoctorLogger(ctx *cli.Context) {
  111. logFile := ctx.String("log-file")
  112. if !ctx.IsSet("log-file") {
  113. logFile = "doctor.log"
  114. }
  115. colorize := log.CanColorStdout
  116. if ctx.IsSet("color") {
  117. colorize = ctx.Bool("color")
  118. }
  119. if len(logFile) == 0 {
  120. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"NONE","stacktracelevel":"NONE","colorize":%t}`, colorize))
  121. return
  122. }
  123. defer func() {
  124. recovered := recover()
  125. if recovered == nil {
  126. return
  127. }
  128. err, ok := recovered.(error)
  129. if !ok {
  130. panic(recovered)
  131. }
  132. if errors.Is(err, os.ErrPermission) {
  133. fmt.Fprintf(os.Stderr, "ERROR: Unable to write logs to provided file due to permissions error: %s\n %v\n", logFile, err)
  134. } else {
  135. fmt.Fprintf(os.Stderr, "ERROR: Unable to write logs to provided file: %s\n %v\n", logFile, err)
  136. }
  137. fmt.Fprintf(os.Stderr, "WARN: Logging will be disabled\n Use `--log-file` to configure log file location\n")
  138. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"NONE","stacktracelevel":"NONE","colorize":%t}`, colorize))
  139. }()
  140. if logFile == "-" {
  141. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"trace","stacktracelevel":"NONE","colorize":%t}`, colorize))
  142. } else {
  143. log.NewLogger(1000, "doctor", "file", fmt.Sprintf(`{"filename":%q,"level":"trace","stacktracelevel":"NONE"}`, logFile))
  144. }
  145. }
  146. func runDoctor(ctx *cli.Context) error {
  147. stdCtx, cancel := installSignals()
  148. defer cancel()
  149. // Silence the default loggers
  150. log.DelNamedLogger("console")
  151. log.DelNamedLogger(log.DEFAULT)
  152. // Now setup our own
  153. setDoctorLogger(ctx)
  154. colorize := log.CanColorStdout
  155. if ctx.IsSet("color") {
  156. colorize = ctx.Bool("color")
  157. }
  158. // Finally redirect the default golog to here
  159. golog.SetFlags(0)
  160. golog.SetPrefix("")
  161. golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
  162. if ctx.IsSet("list") {
  163. w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
  164. _, _ = w.Write([]byte("Default\tName\tTitle\n"))
  165. for _, check := range doctor.Checks {
  166. if check.IsDefault {
  167. _, _ = w.Write([]byte{'*'})
  168. }
  169. _, _ = w.Write([]byte{'\t'})
  170. _, _ = w.Write([]byte(check.Name))
  171. _, _ = w.Write([]byte{'\t'})
  172. _, _ = w.Write([]byte(check.Title))
  173. _, _ = w.Write([]byte{'\n'})
  174. }
  175. return w.Flush()
  176. }
  177. var checks []*doctor.Check
  178. if ctx.Bool("all") {
  179. checks = doctor.Checks
  180. } else if ctx.IsSet("run") {
  181. addDefault := ctx.Bool("default")
  182. names := ctx.StringSlice("run")
  183. for i, name := range names {
  184. names[i] = strings.ToLower(strings.TrimSpace(name))
  185. }
  186. for _, check := range doctor.Checks {
  187. if addDefault && check.IsDefault {
  188. checks = append(checks, check)
  189. continue
  190. }
  191. for _, name := range names {
  192. if name == check.Name {
  193. checks = append(checks, check)
  194. break
  195. }
  196. }
  197. }
  198. } else {
  199. for _, check := range doctor.Checks {
  200. if check.IsDefault {
  201. checks = append(checks, check)
  202. }
  203. }
  204. }
  205. // Now we can set up our own logger to return information about what the doctor is doing
  206. if err := log.NewNamedLogger("doctorouter",
  207. 0,
  208. "console",
  209. "console",
  210. fmt.Sprintf(`{"level":"INFO","stacktracelevel":"NONE","colorize":%t,"flags":-1}`, colorize)); err != nil {
  211. fmt.Println(err)
  212. return err
  213. }
  214. logger := log.GetLogger("doctorouter")
  215. defer logger.Close()
  216. return doctor.RunChecks(stdCtx, logger, ctx.Bool("fix"), checks)
  217. }