Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

doctor.go 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. "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. "code.gitea.io/gitea/modules/doctor"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "github.com/urfave/cli"
  17. "xorm.io/xorm"
  18. )
  19. // CmdDoctor represents the available doctor sub-command.
  20. var CmdDoctor = cli.Command{
  21. Name: "doctor",
  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: runDoctor,
  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 (default: "doctor.log"). Set to "-" to output to stdout, set to "" to disable`,
  49. },
  50. cli.BoolFlag{
  51. Name: "color, H",
  52. Usage: "Use color for outputted information",
  53. },
  54. },
  55. Subcommands: []cli.Command{
  56. cmdRecreateTable,
  57. },
  58. }
  59. var cmdRecreateTable = cli.Command{
  60. Name: "recreate-table",
  61. Usage: "Recreate tables from XORM definitions and copy the data.",
  62. ArgsUsage: "[TABLE]... : (TABLEs to recreate - leave blank for all)",
  63. Flags: []cli.Flag{
  64. cli.BoolFlag{
  65. Name: "debug",
  66. Usage: "Print SQL commands sent",
  67. },
  68. },
  69. Description: `The database definitions Gitea uses change across versions, sometimes changing default values and leaving old unused columns.
  70. This command will cause Xorm to recreate tables, copying over the data and deleting the old table.
  71. You should back-up your database before doing this and ensure that your database is up-to-date first.`,
  72. Action: runRecreateTable,
  73. }
  74. func runRecreateTable(ctx *cli.Context) error {
  75. // Redirect the default golog to here
  76. golog.SetFlags(0)
  77. golog.SetPrefix("")
  78. golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
  79. setting.LoadFromExisting()
  80. setting.InitDBConfig()
  81. setting.EnableXORMLog = ctx.Bool("debug")
  82. setting.Database.LogSQL = ctx.Bool("debug")
  83. setting.Cfg.Section("log").Key("XORM").SetValue(",")
  84. setting.NewXORMLogService(!ctx.Bool("debug"))
  85. stdCtx, cancel := installSignals()
  86. defer cancel()
  87. if err := db.InitEngine(stdCtx); err != nil {
  88. fmt.Println(err)
  89. fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
  90. return nil
  91. }
  92. args := ctx.Args()
  93. names := make([]string, 0, ctx.NArg())
  94. for i := 0; i < ctx.NArg(); i++ {
  95. names = append(names, args.Get(i))
  96. }
  97. beans, err := db.NamesToBean(names...)
  98. if err != nil {
  99. return err
  100. }
  101. recreateTables := migrations.RecreateTables(beans...)
  102. return db.InitEngineWithMigration(stdCtx, func(x *xorm.Engine) error {
  103. if err := migrations.EnsureUpToDate(x); err != nil {
  104. return err
  105. }
  106. return recreateTables(x)
  107. })
  108. }
  109. func runDoctor(ctx *cli.Context) error {
  110. // Silence the default loggers
  111. log.DelNamedLogger("console")
  112. log.DelNamedLogger(log.DEFAULT)
  113. stdCtx, cancel := installSignals()
  114. defer cancel()
  115. // Now setup our own
  116. logFile := ctx.String("log-file")
  117. if !ctx.IsSet("log-file") {
  118. logFile = "doctor.log"
  119. }
  120. colorize := log.CanColorStdout
  121. if ctx.IsSet("color") {
  122. colorize = ctx.Bool("color")
  123. }
  124. if len(logFile) == 0 {
  125. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"NONE","stacktracelevel":"NONE","colorize":%t}`, colorize))
  126. } else if logFile == "-" {
  127. log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"trace","stacktracelevel":"NONE","colorize":%t}`, colorize))
  128. } else {
  129. log.NewLogger(1000, "doctor", "file", fmt.Sprintf(`{"filename":%q,"level":"trace","stacktracelevel":"NONE"}`, logFile))
  130. }
  131. // Finally redirect the default golog to here
  132. golog.SetFlags(0)
  133. golog.SetPrefix("")
  134. golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
  135. if ctx.IsSet("list") {
  136. w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
  137. _, _ = w.Write([]byte("Default\tName\tTitle\n"))
  138. for _, check := range doctor.Checks {
  139. if check.IsDefault {
  140. _, _ = w.Write([]byte{'*'})
  141. }
  142. _, _ = w.Write([]byte{'\t'})
  143. _, _ = w.Write([]byte(check.Name))
  144. _, _ = w.Write([]byte{'\t'})
  145. _, _ = w.Write([]byte(check.Title))
  146. _, _ = w.Write([]byte{'\n'})
  147. }
  148. return w.Flush()
  149. }
  150. var checks []*doctor.Check
  151. if ctx.Bool("all") {
  152. checks = doctor.Checks
  153. } else if ctx.IsSet("run") {
  154. addDefault := ctx.Bool("default")
  155. names := ctx.StringSlice("run")
  156. for i, name := range names {
  157. names[i] = strings.ToLower(strings.TrimSpace(name))
  158. }
  159. for _, check := range doctor.Checks {
  160. if addDefault && check.IsDefault {
  161. checks = append(checks, check)
  162. continue
  163. }
  164. for _, name := range names {
  165. if name == check.Name {
  166. checks = append(checks, check)
  167. break
  168. }
  169. }
  170. }
  171. } else {
  172. for _, check := range doctor.Checks {
  173. if check.IsDefault {
  174. checks = append(checks, check)
  175. }
  176. }
  177. }
  178. // Now we can set up our own logger to return information about what the doctor is doing
  179. if err := log.NewNamedLogger("doctorouter",
  180. 1000,
  181. "console",
  182. "console",
  183. fmt.Sprintf(`{"level":"INFO","stacktracelevel":"NONE","colorize":%t,"flags":-1}`, colorize)); err != nil {
  184. fmt.Println(err)
  185. return err
  186. }
  187. logger := log.GetLogger("doctorouter")
  188. defer logger.Close()
  189. return doctor.RunChecks(stdCtx, logger, ctx.Bool("fix"), checks)
  190. }