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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. "context"
  7. "fmt"
  8. golog "log"
  9. "os"
  10. "strings"
  11. "text/tabwriter"
  12. "code.gitea.io/gitea/models/db"
  13. "code.gitea.io/gitea/models/migrations"
  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 problems",
  24. Description: "A command to diagnose problems with the current Gitea instance according to the given configuration.",
  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 := migrations.RecreateTables(beans...)
  103. return db.InitEngineWithMigration(context.Background(), 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 runDoctor(ctx *cli.Context) error {
  111. // Silence the default loggers
  112. log.DelNamedLogger("console")
  113. log.DelNamedLogger(log.DEFAULT)
  114. stdCtx, cancel := installSignals()
  115. defer cancel()
  116. // Now setup our own
  117. logFile := ctx.String("log-file")
  118. if !ctx.IsSet("log-file") {
  119. logFile = "doctor.log"
  120. }
  121. colorize := log.CanColorStdout
  122. if ctx.IsSet("color") {
  123. colorize = ctx.Bool("color")
  124. }
  125. if len(logFile) == 0 {
  126. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"NONE","stacktracelevel":"NONE","colorize":%t}`, colorize))
  127. } else if logFile == "-" {
  128. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"trace","stacktracelevel":"NONE","colorize":%t}`, colorize))
  129. } else {
  130. log.NewLogger(1000, "doctor", "file", fmt.Sprintf(`{"filename":%q,"level":"trace","stacktracelevel":"NONE"}`, logFile))
  131. }
  132. // Finally redirect the default golog to here
  133. golog.SetFlags(0)
  134. golog.SetPrefix("")
  135. golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
  136. if ctx.IsSet("list") {
  137. w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
  138. _, _ = w.Write([]byte("Default\tName\tTitle\n"))
  139. for _, check := range doctor.Checks {
  140. if check.IsDefault {
  141. _, _ = w.Write([]byte{'*'})
  142. }
  143. _, _ = w.Write([]byte{'\t'})
  144. _, _ = w.Write([]byte(check.Name))
  145. _, _ = w.Write([]byte{'\t'})
  146. _, _ = w.Write([]byte(check.Title))
  147. _, _ = w.Write([]byte{'\n'})
  148. }
  149. return w.Flush()
  150. }
  151. var checks []*doctor.Check
  152. if ctx.Bool("all") {
  153. checks = doctor.Checks
  154. } else if ctx.IsSet("run") {
  155. addDefault := ctx.Bool("default")
  156. names := ctx.StringSlice("run")
  157. for i, name := range names {
  158. names[i] = strings.ToLower(strings.TrimSpace(name))
  159. }
  160. for _, check := range doctor.Checks {
  161. if addDefault && check.IsDefault {
  162. checks = append(checks, check)
  163. continue
  164. }
  165. for _, name := range names {
  166. if name == check.Name {
  167. checks = append(checks, check)
  168. break
  169. }
  170. }
  171. }
  172. } else {
  173. for _, check := range doctor.Checks {
  174. if check.IsDefault {
  175. checks = append(checks, check)
  176. }
  177. }
  178. }
  179. // Now we can set up our own logger to return information about what the doctor is doing
  180. if err := log.NewNamedLogger("doctorouter",
  181. 1000,
  182. "console",
  183. "console",
  184. fmt.Sprintf(`{"level":"INFO","stacktracelevel":"NONE","colorize":%t,"flags":-1}`, colorize)); err != nil {
  185. fmt.Println(err)
  186. return err
  187. }
  188. logger := log.GetLogger("doctorouter")
  189. defer logger.Close()
  190. return doctor.RunChecks(stdCtx, logger, ctx.Bool("fix"), checks)
  191. }