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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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"
  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. stdCtx, cancel := installSignals()
  77. defer cancel()
  78. // Redirect the default golog to here
  79. golog.SetFlags(0)
  80. golog.SetPrefix("")
  81. golog.SetOutput(log.LoggerToWriter(log.GetLogger(log.DEFAULT).Info))
  82. debug := ctx.Bool("debug")
  83. setting.MustInstalled()
  84. setting.LoadDBSetting()
  85. if debug {
  86. setting.InitSQLLoggersForCli(log.DEBUG)
  87. } else {
  88. setting.InitSQLLoggersForCli(log.INFO)
  89. }
  90. setting.Database.LogSQL = debug
  91. if err := db.InitEngine(stdCtx); err != nil {
  92. fmt.Println(err)
  93. fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
  94. return nil
  95. }
  96. args := ctx.Args()
  97. names := make([]string, 0, ctx.NArg())
  98. for i := 0; i < ctx.NArg(); i++ {
  99. names = append(names, args.Get(i))
  100. }
  101. beans, err := db.NamesToBean(names...)
  102. if err != nil {
  103. return err
  104. }
  105. recreateTables := migrate_base.RecreateTables(beans...)
  106. return db.InitEngineWithMigration(stdCtx, func(x *xorm.Engine) error {
  107. if err := migrations.EnsureUpToDate(x); err != nil {
  108. return err
  109. }
  110. return recreateTables(x)
  111. })
  112. }
  113. func setupDoctorDefaultLogger(ctx *cli.Context, colorize bool) {
  114. // Silence the default loggers
  115. setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr)
  116. logFile := ctx.String("log-file")
  117. if !ctx.IsSet("log-file") {
  118. logFile = "doctor.log"
  119. }
  120. if len(logFile) == 0 {
  121. // if no doctor log-file is set, do not show any log from default logger
  122. return
  123. }
  124. if logFile == "-" {
  125. setupConsoleLogger(log.TRACE, colorize, os.Stdout)
  126. } else {
  127. logFile, _ = filepath.Abs(logFile)
  128. writeMode := log.WriterMode{Level: log.TRACE, WriterOption: log.WriterFileOption{FileName: logFile}}
  129. writer, err := log.NewEventWriter("console-to-file", "file", writeMode)
  130. if err != nil {
  131. log.FallbackErrorf("unable to create file log writer: %v", err)
  132. return
  133. }
  134. log.GetManager().GetLogger(log.DEFAULT).ReplaceAllWriters(writer)
  135. }
  136. }
  137. func runDoctor(ctx *cli.Context) error {
  138. stdCtx, cancel := installSignals()
  139. defer cancel()
  140. colorize := log.CanColorStdout
  141. if ctx.IsSet("color") {
  142. colorize = ctx.Bool("color")
  143. }
  144. setupDoctorDefaultLogger(ctx, colorize)
  145. // Finally redirect the default golang's log to here
  146. golog.SetFlags(0)
  147. golog.SetPrefix("")
  148. golog.SetOutput(log.LoggerToWriter(log.GetLogger(log.DEFAULT).Info))
  149. if ctx.IsSet("list") {
  150. w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
  151. _, _ = w.Write([]byte("Default\tName\tTitle\n"))
  152. for _, check := range doctor.Checks {
  153. if check.IsDefault {
  154. _, _ = w.Write([]byte{'*'})
  155. }
  156. _, _ = w.Write([]byte{'\t'})
  157. _, _ = w.Write([]byte(check.Name))
  158. _, _ = w.Write([]byte{'\t'})
  159. _, _ = w.Write([]byte(check.Title))
  160. _, _ = w.Write([]byte{'\n'})
  161. }
  162. return w.Flush()
  163. }
  164. var checks []*doctor.Check
  165. if ctx.Bool("all") {
  166. checks = doctor.Checks
  167. } else if ctx.IsSet("run") {
  168. addDefault := ctx.Bool("default")
  169. names := ctx.StringSlice("run")
  170. for i, name := range names {
  171. names[i] = strings.ToLower(strings.TrimSpace(name))
  172. }
  173. for _, check := range doctor.Checks {
  174. if addDefault && check.IsDefault {
  175. checks = append(checks, check)
  176. continue
  177. }
  178. for _, name := range names {
  179. if name == check.Name {
  180. checks = append(checks, check)
  181. break
  182. }
  183. }
  184. }
  185. } else {
  186. for _, check := range doctor.Checks {
  187. if check.IsDefault {
  188. checks = append(checks, check)
  189. }
  190. }
  191. }
  192. return doctor.RunChecks(stdCtx, colorize, ctx.Bool("fix"), checks)
  193. }