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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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.Init(&setting.Options{})
  81. setting.LoadDBSetting()
  82. setting.Log.EnableXORMLog = ctx.Bool("debug")
  83. setting.Database.LogSQL = ctx.Bool("debug")
  84. // FIXME: don't use CfgProvider directly
  85. setting.CfgProvider.Section("log").Key("XORM").SetValue(",")
  86. setting.InitSQLLog(!ctx.Bool("debug"))
  87. stdCtx, cancel := installSignals()
  88. defer cancel()
  89. if err := db.InitEngine(stdCtx); err != nil {
  90. fmt.Println(err)
  91. fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
  92. return nil
  93. }
  94. args := ctx.Args()
  95. names := make([]string, 0, ctx.NArg())
  96. for i := 0; i < ctx.NArg(); i++ {
  97. names = append(names, args.Get(i))
  98. }
  99. beans, err := db.NamesToBean(names...)
  100. if err != nil {
  101. return err
  102. }
  103. recreateTables := migrate_base.RecreateTables(beans...)
  104. return db.InitEngineWithMigration(stdCtx, func(x *xorm.Engine) error {
  105. if err := migrations.EnsureUpToDate(x); err != nil {
  106. return err
  107. }
  108. return recreateTables(x)
  109. })
  110. }
  111. func setDoctorLogger(ctx *cli.Context) {
  112. logFile := ctx.String("log-file")
  113. if !ctx.IsSet("log-file") {
  114. logFile = "doctor.log"
  115. }
  116. colorize := log.CanColorStdout
  117. if ctx.IsSet("color") {
  118. colorize = ctx.Bool("color")
  119. }
  120. if len(logFile) == 0 {
  121. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"NONE","stacktracelevel":"NONE","colorize":%t}`, colorize))
  122. return
  123. }
  124. defer func() {
  125. recovered := recover()
  126. if recovered == nil {
  127. return
  128. }
  129. err, ok := recovered.(error)
  130. if !ok {
  131. panic(recovered)
  132. }
  133. if errors.Is(err, os.ErrPermission) {
  134. fmt.Fprintf(os.Stderr, "ERROR: Unable to write logs to provided file due to permissions error: %s\n %v\n", logFile, err)
  135. } else {
  136. fmt.Fprintf(os.Stderr, "ERROR: Unable to write logs to provided file: %s\n %v\n", logFile, err)
  137. }
  138. fmt.Fprintf(os.Stderr, "WARN: Logging will be disabled\n Use `--log-file` to configure log file location\n")
  139. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"NONE","stacktracelevel":"NONE","colorize":%t}`, colorize))
  140. }()
  141. if logFile == "-" {
  142. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"trace","stacktracelevel":"NONE","colorize":%t}`, colorize))
  143. } else {
  144. log.NewLogger(1000, "doctor", "file", fmt.Sprintf(`{"filename":%q,"level":"trace","stacktracelevel":"NONE"}`, logFile))
  145. }
  146. }
  147. func runDoctor(ctx *cli.Context) error {
  148. stdCtx, cancel := installSignals()
  149. defer cancel()
  150. // Silence the default loggers
  151. log.DelNamedLogger("console")
  152. log.DelNamedLogger(log.DEFAULT)
  153. // Now setup our own
  154. setDoctorLogger(ctx)
  155. colorize := log.CanColorStdout
  156. if ctx.IsSet("color") {
  157. colorize = ctx.Bool("color")
  158. }
  159. // Finally redirect the default golog to here
  160. golog.SetFlags(0)
  161. golog.SetPrefix("")
  162. golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
  163. if ctx.IsSet("list") {
  164. w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
  165. _, _ = w.Write([]byte("Default\tName\tTitle\n"))
  166. for _, check := range doctor.Checks {
  167. if check.IsDefault {
  168. _, _ = w.Write([]byte{'*'})
  169. }
  170. _, _ = w.Write([]byte{'\t'})
  171. _, _ = w.Write([]byte(check.Name))
  172. _, _ = w.Write([]byte{'\t'})
  173. _, _ = w.Write([]byte(check.Title))
  174. _, _ = w.Write([]byte{'\n'})
  175. }
  176. return w.Flush()
  177. }
  178. var checks []*doctor.Check
  179. if ctx.Bool("all") {
  180. checks = doctor.Checks
  181. } else if ctx.IsSet("run") {
  182. addDefault := ctx.Bool("default")
  183. names := ctx.StringSlice("run")
  184. for i, name := range names {
  185. names[i] = strings.ToLower(strings.TrimSpace(name))
  186. }
  187. for _, check := range doctor.Checks {
  188. if addDefault && check.IsDefault {
  189. checks = append(checks, check)
  190. continue
  191. }
  192. for _, name := range names {
  193. if name == check.Name {
  194. checks = append(checks, check)
  195. break
  196. }
  197. }
  198. }
  199. } else {
  200. for _, check := range doctor.Checks {
  201. if check.IsDefault {
  202. checks = append(checks, check)
  203. }
  204. }
  205. }
  206. // Now we can set up our own logger to return information about what the doctor is doing
  207. if err := log.NewNamedLogger("doctorouter",
  208. 0,
  209. "console",
  210. "console",
  211. fmt.Sprintf(`{"level":"INFO","stacktracelevel":"NONE","colorize":%t,"flags":-1}`, colorize)); err != nil {
  212. fmt.Println(err)
  213. return err
  214. }
  215. logger := log.GetLogger("doctorouter")
  216. defer logger.Close()
  217. return doctor.RunChecks(stdCtx, logger, ctx.Bool("fix"), checks)
  218. }