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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "fmt"
  6. golog "log"
  7. "os"
  8. "path/filepath"
  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/v2"
  18. "xorm.io/xorm"
  19. )
  20. var cmdDoctorCheck = &cli.Command{
  21. Name: "check",
  22. Usage: "Diagnose and optionally fix problems",
  23. 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.",
  24. Action: runDoctorCheck,
  25. Flags: []cli.Flag{
  26. &cli.BoolFlag{
  27. Name: "list",
  28. Usage: "List the available checks",
  29. },
  30. &cli.BoolFlag{
  31. Name: "default",
  32. Usage: "Run the default checks (if neither --run or --all is set, this is the default behaviour)",
  33. },
  34. &cli.StringSliceFlag{
  35. Name: "run",
  36. Usage: "Run the provided checks - (if --default is set, the default checks will also run)",
  37. },
  38. &cli.BoolFlag{
  39. Name: "all",
  40. Usage: "Run all the available checks",
  41. },
  42. &cli.BoolFlag{
  43. Name: "fix",
  44. Usage: "Automatically fix what we can",
  45. },
  46. &cli.StringFlag{
  47. Name: "log-file",
  48. Usage: `Name of the log file (no verbose log output by default). Set to "-" to output to stdout`,
  49. },
  50. &cli.BoolFlag{
  51. Name: "color",
  52. Aliases: []string{"H"},
  53. Usage: "Use color for outputted information",
  54. },
  55. },
  56. }
  57. // CmdDoctor represents the available doctor sub-command.
  58. var CmdDoctor = &cli.Command{
  59. Name: "doctor",
  60. Usage: "Diagnose and optionally fix problems",
  61. 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.",
  62. Subcommands: []*cli.Command{
  63. cmdDoctorCheck,
  64. cmdRecreateTable,
  65. cmdDoctorConvert,
  66. },
  67. }
  68. var cmdRecreateTable = &cli.Command{
  69. Name: "recreate-table",
  70. Usage: "Recreate tables from XORM definitions and copy the data.",
  71. ArgsUsage: "[TABLE]... : (TABLEs to recreate - leave blank for all)",
  72. Flags: []cli.Flag{
  73. &cli.BoolFlag{
  74. Name: "debug",
  75. Usage: "Print SQL commands sent",
  76. },
  77. },
  78. Description: `The database definitions Gitea uses change across versions, sometimes changing default values and leaving old unused columns.
  79. This command will cause Xorm to recreate tables, copying over the data and deleting the old table.
  80. You should back-up your database before doing this and ensure that your database is up-to-date first.`,
  81. Action: runRecreateTable,
  82. }
  83. func runRecreateTable(ctx *cli.Context) error {
  84. stdCtx, cancel := installSignals()
  85. defer cancel()
  86. // Redirect the default golog to here
  87. golog.SetFlags(0)
  88. golog.SetPrefix("")
  89. golog.SetOutput(log.LoggerToWriter(log.GetLogger(log.DEFAULT).Info))
  90. debug := ctx.Bool("debug")
  91. setting.MustInstalled()
  92. setting.LoadDBSetting()
  93. if debug {
  94. setting.InitSQLLoggersForCli(log.DEBUG)
  95. } else {
  96. setting.InitSQLLoggersForCli(log.INFO)
  97. }
  98. setting.Database.LogSQL = debug
  99. if err := db.InitEngine(stdCtx); err != nil {
  100. fmt.Println(err)
  101. fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
  102. return nil
  103. }
  104. args := ctx.Args()
  105. names := make([]string, 0, ctx.NArg())
  106. for i := 0; i < ctx.NArg(); i++ {
  107. names = append(names, args.Get(i))
  108. }
  109. beans, err := db.NamesToBean(names...)
  110. if err != nil {
  111. return err
  112. }
  113. recreateTables := migrate_base.RecreateTables(beans...)
  114. return db.InitEngineWithMigration(stdCtx, func(x *xorm.Engine) error {
  115. if err := migrations.EnsureUpToDate(x); err != nil {
  116. return err
  117. }
  118. return recreateTables(x)
  119. })
  120. }
  121. func setupDoctorDefaultLogger(ctx *cli.Context, colorize bool) {
  122. // Silence the default loggers
  123. setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr)
  124. logFile := ctx.String("log-file")
  125. if logFile == "" {
  126. return // if no doctor log-file is set, do not show any log from default logger
  127. } else if logFile == "-" {
  128. setupConsoleLogger(log.TRACE, colorize, os.Stdout)
  129. } else {
  130. logFile, _ = filepath.Abs(logFile)
  131. writeMode := log.WriterMode{Level: log.TRACE, WriterOption: log.WriterFileOption{FileName: logFile}}
  132. writer, err := log.NewEventWriter("console-to-file", "file", writeMode)
  133. if err != nil {
  134. log.FallbackErrorf("unable to create file log writer: %v", err)
  135. return
  136. }
  137. log.GetManager().GetLogger(log.DEFAULT).ReplaceAllWriters(writer)
  138. }
  139. }
  140. func runDoctorCheck(ctx *cli.Context) error {
  141. stdCtx, cancel := installSignals()
  142. defer cancel()
  143. colorize := log.CanColorStdout
  144. if ctx.IsSet("color") {
  145. colorize = ctx.Bool("color")
  146. }
  147. setupDoctorDefaultLogger(ctx, colorize)
  148. // Finally redirect the default golang's log to here
  149. golog.SetFlags(0)
  150. golog.SetPrefix("")
  151. golog.SetOutput(log.LoggerToWriter(log.GetLogger(log.DEFAULT).Info))
  152. if ctx.IsSet("list") {
  153. w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
  154. _, _ = w.Write([]byte("Default\tName\tTitle\n"))
  155. for _, check := range doctor.Checks {
  156. if check.IsDefault {
  157. _, _ = w.Write([]byte{'*'})
  158. }
  159. _, _ = w.Write([]byte{'\t'})
  160. _, _ = w.Write([]byte(check.Name))
  161. _, _ = w.Write([]byte{'\t'})
  162. _, _ = w.Write([]byte(check.Title))
  163. _, _ = w.Write([]byte{'\n'})
  164. }
  165. return w.Flush()
  166. }
  167. var checks []*doctor.Check
  168. if ctx.Bool("all") {
  169. checks = doctor.Checks
  170. } else if ctx.IsSet("run") {
  171. addDefault := ctx.Bool("default")
  172. names := ctx.StringSlice("run")
  173. for i, name := range names {
  174. names[i] = strings.ToLower(strings.TrimSpace(name))
  175. }
  176. for _, check := range doctor.Checks {
  177. if addDefault && check.IsDefault {
  178. checks = append(checks, check)
  179. continue
  180. }
  181. for _, name := range names {
  182. if name == check.Name {
  183. checks = append(checks, check)
  184. break
  185. }
  186. }
  187. }
  188. } else {
  189. for _, check := range doctor.Checks {
  190. if check.IsDefault {
  191. checks = append(checks, check)
  192. }
  193. }
  194. }
  195. return doctor.RunChecks(stdCtx, colorize, ctx.Bool("fix"), checks)
  196. }