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.

dump.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package cmd
  5. import (
  6. "fmt"
  7. "io"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/models/db"
  14. "code.gitea.io/gitea/modules/json"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/storage"
  18. "code.gitea.io/gitea/modules/util"
  19. "gitea.com/go-chi/session"
  20. "github.com/mholt/archiver/v3"
  21. "github.com/urfave/cli"
  22. )
  23. func addReader(w archiver.Writer, r io.ReadCloser, info os.FileInfo, customName string, verbose bool) error {
  24. if verbose {
  25. log.Info("Adding file %s", customName)
  26. }
  27. return w.Write(archiver.File{
  28. FileInfo: archiver.FileInfo{
  29. FileInfo: info,
  30. CustomName: customName,
  31. },
  32. ReadCloser: r,
  33. })
  34. }
  35. func addFile(w archiver.Writer, filePath, absPath string, verbose bool) error {
  36. file, err := os.Open(absPath)
  37. if err != nil {
  38. return err
  39. }
  40. defer file.Close()
  41. fileInfo, err := file.Stat()
  42. if err != nil {
  43. return err
  44. }
  45. return addReader(w, file, fileInfo, filePath, verbose)
  46. }
  47. func isSubdir(upper, lower string) (bool, error) {
  48. if relPath, err := filepath.Rel(upper, lower); err != nil {
  49. return false, err
  50. } else if relPath == "." || !strings.HasPrefix(relPath, ".") {
  51. return true, nil
  52. }
  53. return false, nil
  54. }
  55. type outputType struct {
  56. Enum []string
  57. Default string
  58. selected string
  59. }
  60. func (o outputType) Join() string {
  61. return strings.Join(o.Enum, ", ")
  62. }
  63. func (o *outputType) Set(value string) error {
  64. for _, enum := range o.Enum {
  65. if enum == value {
  66. o.selected = value
  67. return nil
  68. }
  69. }
  70. return fmt.Errorf("allowed values are %s", o.Join())
  71. }
  72. func (o outputType) String() string {
  73. if o.selected == "" {
  74. return o.Default
  75. }
  76. return o.selected
  77. }
  78. var outputTypeEnum = &outputType{
  79. Enum: []string{"zip", "tar", "tar.sz", "tar.gz", "tar.xz", "tar.bz2", "tar.br", "tar.lz4", "tar.zst"},
  80. Default: "zip",
  81. }
  82. // CmdDump represents the available dump sub-command.
  83. var CmdDump = cli.Command{
  84. Name: "dump",
  85. Usage: "Dump Gitea files and database",
  86. Description: `Dump compresses all related files and database into zip file.
  87. It can be used for backup and capture Gitea server image to send to maintainer`,
  88. Action: runDump,
  89. Flags: []cli.Flag{
  90. cli.StringFlag{
  91. Name: "file, f",
  92. Value: fmt.Sprintf("gitea-dump-%d.zip", time.Now().Unix()),
  93. Usage: "Name of the dump file which will be created. Supply '-' for stdout. See type for available types.",
  94. },
  95. cli.BoolFlag{
  96. Name: "verbose, V",
  97. Usage: "Show process details",
  98. },
  99. cli.BoolFlag{
  100. Name: "quiet, q",
  101. Usage: "Only display warnings and errors",
  102. },
  103. cli.StringFlag{
  104. Name: "tempdir, t",
  105. Value: os.TempDir(),
  106. Usage: "Temporary dir path",
  107. },
  108. cli.StringFlag{
  109. Name: "database, d",
  110. Usage: "Specify the database SQL syntax",
  111. },
  112. cli.BoolFlag{
  113. Name: "skip-repository, R",
  114. Usage: "Skip the repository dumping",
  115. },
  116. cli.BoolFlag{
  117. Name: "skip-log, L",
  118. Usage: "Skip the log dumping",
  119. },
  120. cli.BoolFlag{
  121. Name: "skip-custom-dir",
  122. Usage: "Skip custom directory",
  123. },
  124. cli.BoolFlag{
  125. Name: "skip-lfs-data",
  126. Usage: "Skip LFS data",
  127. },
  128. cli.BoolFlag{
  129. Name: "skip-attachment-data",
  130. Usage: "Skip attachment data",
  131. },
  132. cli.BoolFlag{
  133. Name: "skip-package-data",
  134. Usage: "Skip package data",
  135. },
  136. cli.BoolFlag{
  137. Name: "skip-index",
  138. Usage: "Skip bleve index data",
  139. },
  140. cli.GenericFlag{
  141. Name: "type",
  142. Value: outputTypeEnum,
  143. Usage: fmt.Sprintf("Dump output format: %s", outputTypeEnum.Join()),
  144. },
  145. },
  146. }
  147. func fatal(format string, args ...any) {
  148. fmt.Fprintf(os.Stderr, format+"\n", args...)
  149. log.Fatal(format, args...)
  150. }
  151. func runDump(ctx *cli.Context) error {
  152. var file *os.File
  153. fileName := ctx.String("file")
  154. outType := ctx.String("type")
  155. if fileName == "-" {
  156. file = os.Stdout
  157. setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr)
  158. } else {
  159. for _, suffix := range outputTypeEnum.Enum {
  160. if strings.HasSuffix(fileName, "."+suffix) {
  161. fileName = strings.TrimSuffix(fileName, "."+suffix)
  162. break
  163. }
  164. }
  165. fileName += "." + outType
  166. }
  167. setting.MustInstalled()
  168. // make sure we are logging to the console no matter what the configuration tells us do to
  169. // FIXME: don't use CfgProvider directly
  170. if _, err := setting.CfgProvider.Section("log").NewKey("MODE", "console"); err != nil {
  171. fatal("Setting logging mode to console failed: %v", err)
  172. }
  173. if _, err := setting.CfgProvider.Section("log.console").NewKey("STDERR", "true"); err != nil {
  174. fatal("Setting console logger to stderr failed: %v", err)
  175. }
  176. // Set loglevel to Warn if quiet-mode is requested
  177. if ctx.Bool("quiet") {
  178. if _, err := setting.CfgProvider.Section("log.console").NewKey("LEVEL", "Warn"); err != nil {
  179. fatal("Setting console log-level failed: %v", err)
  180. }
  181. }
  182. if !setting.InstallLock {
  183. log.Error("Is '%s' really the right config path?\n", setting.CustomConf)
  184. return fmt.Errorf("gitea is not initialized")
  185. }
  186. setting.LoadSettings() // cannot access session settings otherwise
  187. verbose := ctx.Bool("verbose")
  188. if verbose && ctx.Bool("quiet") {
  189. return fmt.Errorf("--quiet and --verbose cannot both be set")
  190. }
  191. stdCtx, cancel := installSignals()
  192. defer cancel()
  193. err := db.InitEngine(stdCtx)
  194. if err != nil {
  195. return err
  196. }
  197. if err := storage.Init(); err != nil {
  198. return err
  199. }
  200. if file == nil {
  201. file, err = os.Create(fileName)
  202. if err != nil {
  203. fatal("Unable to open %s: %v", fileName, err)
  204. }
  205. }
  206. defer file.Close()
  207. absFileName, err := filepath.Abs(fileName)
  208. if err != nil {
  209. return err
  210. }
  211. var iface any
  212. if fileName == "-" {
  213. iface, err = archiver.ByExtension(fmt.Sprintf(".%s", outType))
  214. } else {
  215. iface, err = archiver.ByExtension(fileName)
  216. }
  217. if err != nil {
  218. fatal("Unable to get archiver for extension: %v", err)
  219. }
  220. w, _ := iface.(archiver.Writer)
  221. if err := w.Create(file); err != nil {
  222. fatal("Creating archiver.Writer failed: %v", err)
  223. }
  224. defer w.Close()
  225. if ctx.IsSet("skip-repository") && ctx.Bool("skip-repository") {
  226. log.Info("Skip dumping local repositories")
  227. } else {
  228. log.Info("Dumping local repositories... %s", setting.RepoRootPath)
  229. if err := addRecursiveExclude(w, "repos", setting.RepoRootPath, []string{absFileName}, verbose); err != nil {
  230. fatal("Failed to include repositories: %v", err)
  231. }
  232. if ctx.IsSet("skip-lfs-data") && ctx.Bool("skip-lfs-data") {
  233. log.Info("Skip dumping LFS data")
  234. } else if !setting.LFS.StartServer {
  235. log.Info("LFS isn't enabled. Skip dumping LFS data")
  236. } else if err := storage.LFS.IterateObjects("", func(objPath string, object storage.Object) error {
  237. info, err := object.Stat()
  238. if err != nil {
  239. return err
  240. }
  241. return addReader(w, object, info, path.Join("data", "lfs", objPath), verbose)
  242. }); err != nil {
  243. fatal("Failed to dump LFS objects: %v", err)
  244. }
  245. }
  246. tmpDir := ctx.String("tempdir")
  247. if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
  248. fatal("Path does not exist: %s", tmpDir)
  249. }
  250. dbDump, err := os.CreateTemp(tmpDir, "gitea-db.sql")
  251. if err != nil {
  252. fatal("Failed to create tmp file: %v", err)
  253. }
  254. defer func() {
  255. _ = dbDump.Close()
  256. if err := util.Remove(dbDump.Name()); err != nil {
  257. log.Warn("Unable to remove temporary file: %s: Error: %v", dbDump.Name(), err)
  258. }
  259. }()
  260. targetDBType := ctx.String("database")
  261. if len(targetDBType) > 0 && targetDBType != setting.Database.Type.String() {
  262. log.Info("Dumping database %s => %s...", setting.Database.Type, targetDBType)
  263. } else {
  264. log.Info("Dumping database...")
  265. }
  266. if err := db.DumpDatabase(dbDump.Name(), targetDBType); err != nil {
  267. fatal("Failed to dump database: %v", err)
  268. }
  269. if err := addFile(w, "gitea-db.sql", dbDump.Name(), verbose); err != nil {
  270. fatal("Failed to include gitea-db.sql: %v", err)
  271. }
  272. if len(setting.CustomConf) > 0 {
  273. log.Info("Adding custom configuration file from %s", setting.CustomConf)
  274. if err := addFile(w, "app.ini", setting.CustomConf, verbose); err != nil {
  275. fatal("Failed to include specified app.ini: %v", err)
  276. }
  277. }
  278. if ctx.IsSet("skip-custom-dir") && ctx.Bool("skip-custom-dir") {
  279. log.Info("Skipping custom directory")
  280. } else {
  281. customDir, err := os.Stat(setting.CustomPath)
  282. if err == nil && customDir.IsDir() {
  283. if is, _ := isSubdir(setting.AppDataPath, setting.CustomPath); !is {
  284. if err := addRecursiveExclude(w, "custom", setting.CustomPath, []string{absFileName}, verbose); err != nil {
  285. fatal("Failed to include custom: %v", err)
  286. }
  287. } else {
  288. log.Info("Custom dir %s is inside data dir %s, skipped", setting.CustomPath, setting.AppDataPath)
  289. }
  290. } else {
  291. log.Info("Custom dir %s doesn't exist, skipped", setting.CustomPath)
  292. }
  293. }
  294. isExist, err := util.IsExist(setting.AppDataPath)
  295. if err != nil {
  296. log.Error("Unable to check if %s exists. Error: %v", setting.AppDataPath, err)
  297. }
  298. if isExist {
  299. log.Info("Packing data directory...%s", setting.AppDataPath)
  300. var excludes []string
  301. if setting.SessionConfig.OriginalProvider == "file" {
  302. var opts session.Options
  303. if err = json.Unmarshal([]byte(setting.SessionConfig.ProviderConfig), &opts); err != nil {
  304. return err
  305. }
  306. excludes = append(excludes, opts.ProviderConfig)
  307. }
  308. if ctx.IsSet("skip-index") && ctx.Bool("skip-index") {
  309. excludes = append(excludes, setting.Indexer.RepoPath)
  310. excludes = append(excludes, setting.Indexer.IssuePath)
  311. }
  312. excludes = append(excludes, setting.RepoRootPath)
  313. excludes = append(excludes, setting.LFS.Storage.Path)
  314. excludes = append(excludes, setting.Attachment.Storage.Path)
  315. excludes = append(excludes, setting.Packages.Storage.Path)
  316. excludes = append(excludes, setting.Log.RootPath)
  317. excludes = append(excludes, absFileName)
  318. if err := addRecursiveExclude(w, "data", setting.AppDataPath, excludes, verbose); err != nil {
  319. fatal("Failed to include data directory: %v", err)
  320. }
  321. }
  322. if ctx.IsSet("skip-attachment-data") && ctx.Bool("skip-attachment-data") {
  323. log.Info("Skip dumping attachment data")
  324. } else if err := storage.Attachments.IterateObjects("", func(objPath string, object storage.Object) error {
  325. info, err := object.Stat()
  326. if err != nil {
  327. return err
  328. }
  329. return addReader(w, object, info, path.Join("data", "attachments", objPath), verbose)
  330. }); err != nil {
  331. fatal("Failed to dump attachments: %v", err)
  332. }
  333. if ctx.IsSet("skip-package-data") && ctx.Bool("skip-package-data") {
  334. log.Info("Skip dumping package data")
  335. } else if !setting.Packages.Enabled {
  336. log.Info("Packages isn't enabled. Skip dumping package data")
  337. } else if err := storage.Packages.IterateObjects("", func(objPath string, object storage.Object) error {
  338. info, err := object.Stat()
  339. if err != nil {
  340. return err
  341. }
  342. return addReader(w, object, info, path.Join("data", "packages", objPath), verbose)
  343. }); err != nil {
  344. fatal("Failed to dump packages: %v", err)
  345. }
  346. // Doesn't check if LogRootPath exists before processing --skip-log intentionally,
  347. // ensuring that it's clear the dump is skipped whether the directory's initialized
  348. // yet or not.
  349. if ctx.IsSet("skip-log") && ctx.Bool("skip-log") {
  350. log.Info("Skip dumping log files")
  351. } else {
  352. isExist, err := util.IsExist(setting.Log.RootPath)
  353. if err != nil {
  354. log.Error("Unable to check if %s exists. Error: %v", setting.Log.RootPath, err)
  355. }
  356. if isExist {
  357. if err := addRecursiveExclude(w, "log", setting.Log.RootPath, []string{absFileName}, verbose); err != nil {
  358. fatal("Failed to include log: %v", err)
  359. }
  360. }
  361. }
  362. if fileName != "-" {
  363. if err = w.Close(); err != nil {
  364. _ = util.Remove(fileName)
  365. fatal("Failed to save %s: %v", fileName, err)
  366. }
  367. if err := os.Chmod(fileName, 0o600); err != nil {
  368. log.Info("Can't change file access permissions mask to 0600: %v", err)
  369. }
  370. }
  371. if fileName != "-" {
  372. log.Info("Finish dumping in file %s", fileName)
  373. } else {
  374. log.Info("Finish dumping to stdout")
  375. }
  376. return nil
  377. }
  378. // addRecursiveExclude zips absPath to specified insidePath inside writer excluding excludeAbsPath
  379. func addRecursiveExclude(w archiver.Writer, insidePath, absPath string, excludeAbsPath []string, verbose bool) error {
  380. absPath, err := filepath.Abs(absPath)
  381. if err != nil {
  382. return err
  383. }
  384. dir, err := os.Open(absPath)
  385. if err != nil {
  386. return err
  387. }
  388. defer dir.Close()
  389. files, err := dir.Readdir(0)
  390. if err != nil {
  391. return err
  392. }
  393. for _, file := range files {
  394. currentAbsPath := path.Join(absPath, file.Name())
  395. currentInsidePath := path.Join(insidePath, file.Name())
  396. if file.IsDir() {
  397. if !util.SliceContainsString(excludeAbsPath, currentAbsPath) {
  398. if err := addFile(w, currentInsidePath, currentAbsPath, false); err != nil {
  399. return err
  400. }
  401. if err = addRecursiveExclude(w, currentInsidePath, currentAbsPath, excludeAbsPath, verbose); err != nil {
  402. return err
  403. }
  404. }
  405. } else {
  406. // only copy regular files and symlink regular files, skip non-regular files like socket/pipe/...
  407. shouldAdd := file.Mode().IsRegular()
  408. if !shouldAdd && file.Mode()&os.ModeSymlink == os.ModeSymlink {
  409. target, err := filepath.EvalSymlinks(currentAbsPath)
  410. if err != nil {
  411. return err
  412. }
  413. targetStat, err := os.Stat(target)
  414. if err != nil {
  415. return err
  416. }
  417. shouldAdd = targetStat.Mode().IsRegular()
  418. }
  419. if shouldAdd {
  420. if err = addFile(w, currentInsidePath, currentAbsPath, verbose); err != nil {
  421. return err
  422. }
  423. }
  424. }
  425. }
  426. return nil
  427. }