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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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.StringFlag{
  100. Name: "tempdir, t",
  101. Value: os.TempDir(),
  102. Usage: "Temporary dir path",
  103. },
  104. cli.StringFlag{
  105. Name: "database, d",
  106. Usage: "Specify the database SQL syntax",
  107. },
  108. cli.BoolFlag{
  109. Name: "skip-repository, R",
  110. Usage: "Skip the repository dumping",
  111. },
  112. cli.BoolFlag{
  113. Name: "skip-log, L",
  114. Usage: "Skip the log dumping",
  115. },
  116. cli.BoolFlag{
  117. Name: "skip-custom-dir",
  118. Usage: "Skip custom directory",
  119. },
  120. cli.BoolFlag{
  121. Name: "skip-lfs-data",
  122. Usage: "Skip LFS data",
  123. },
  124. cli.BoolFlag{
  125. Name: "skip-attachment-data",
  126. Usage: "Skip attachment data",
  127. },
  128. cli.BoolFlag{
  129. Name: "skip-package-data",
  130. Usage: "Skip package data",
  131. },
  132. cli.BoolFlag{
  133. Name: "skip-index",
  134. Usage: "Skip bleve index data",
  135. },
  136. cli.GenericFlag{
  137. Name: "type",
  138. Value: outputTypeEnum,
  139. Usage: fmt.Sprintf("Dump output format: %s", outputTypeEnum.Join()),
  140. },
  141. },
  142. }
  143. func fatal(format string, args ...interface{}) {
  144. fmt.Fprintf(os.Stderr, format+"\n", args...)
  145. log.Fatal(format, args...)
  146. }
  147. func runDump(ctx *cli.Context) error {
  148. var file *os.File
  149. fileName := ctx.String("file")
  150. outType := ctx.String("type")
  151. if fileName == "-" {
  152. file = os.Stdout
  153. err := log.DelLogger("console")
  154. if err != nil {
  155. fatal("Deleting default logger failed. Can not write to stdout: %v", err)
  156. }
  157. } else {
  158. for _, suffix := range outputTypeEnum.Enum {
  159. if strings.HasSuffix(fileName, "."+suffix) {
  160. fileName = strings.TrimSuffix(fileName, "."+suffix)
  161. break
  162. }
  163. }
  164. fileName += "." + outType
  165. }
  166. setting.LoadFromExisting()
  167. // make sure we are logging to the console no matter what the configuration tells us do to
  168. if _, err := setting.Cfg.Section("log").NewKey("MODE", "console"); err != nil {
  169. fatal("Setting logging mode to console failed: %v", err)
  170. }
  171. if _, err := setting.Cfg.Section("log.console").NewKey("STDERR", "true"); err != nil {
  172. fatal("Setting console logger to stderr failed: %v", err)
  173. }
  174. if !setting.InstallLock {
  175. log.Error("Is '%s' really the right config path?\n", setting.CustomConf)
  176. return fmt.Errorf("gitea is not initialized")
  177. }
  178. setting.NewServices() // cannot access session settings otherwise
  179. stdCtx, cancel := installSignals()
  180. defer cancel()
  181. err := db.InitEngine(stdCtx)
  182. if err != nil {
  183. return err
  184. }
  185. if err := storage.Init(); err != nil {
  186. return err
  187. }
  188. if file == nil {
  189. file, err = os.Create(fileName)
  190. if err != nil {
  191. fatal("Unable to open %s: %v", fileName, err)
  192. }
  193. }
  194. defer file.Close()
  195. absFileName, err := filepath.Abs(fileName)
  196. if err != nil {
  197. return err
  198. }
  199. verbose := ctx.Bool("verbose")
  200. var iface interface{}
  201. if fileName == "-" {
  202. iface, err = archiver.ByExtension(fmt.Sprintf(".%s", outType))
  203. } else {
  204. iface, err = archiver.ByExtension(fileName)
  205. }
  206. if err != nil {
  207. fatal("Unable to get archiver for extension: %v", err)
  208. }
  209. w, _ := iface.(archiver.Writer)
  210. if err := w.Create(file); err != nil {
  211. fatal("Creating archiver.Writer failed: %v", err)
  212. }
  213. defer w.Close()
  214. if ctx.IsSet("skip-repository") && ctx.Bool("skip-repository") {
  215. log.Info("Skip dumping local repositories")
  216. } else {
  217. log.Info("Dumping local repositories... %s", setting.RepoRootPath)
  218. if err := addRecursiveExclude(w, "repos", setting.RepoRootPath, []string{absFileName}, verbose); err != nil {
  219. fatal("Failed to include repositories: %v", err)
  220. }
  221. if ctx.IsSet("skip-lfs-data") && ctx.Bool("skip-lfs-data") {
  222. log.Info("Skip dumping LFS data")
  223. } else if err := storage.LFS.IterateObjects(func(objPath string, object storage.Object) error {
  224. info, err := object.Stat()
  225. if err != nil {
  226. return err
  227. }
  228. return addReader(w, object, info, path.Join("data", "lfs", objPath), verbose)
  229. }); err != nil {
  230. fatal("Failed to dump LFS objects: %v", err)
  231. }
  232. }
  233. tmpDir := ctx.String("tempdir")
  234. if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
  235. fatal("Path does not exist: %s", tmpDir)
  236. }
  237. dbDump, err := os.CreateTemp(tmpDir, "gitea-db.sql")
  238. if err != nil {
  239. fatal("Failed to create tmp file: %v", err)
  240. }
  241. defer func() {
  242. if err := util.Remove(dbDump.Name()); err != nil {
  243. log.Warn("Unable to remove temporary file: %s: Error: %v", dbDump.Name(), err)
  244. }
  245. }()
  246. targetDBType := ctx.String("database")
  247. if len(targetDBType) > 0 && targetDBType != setting.Database.Type {
  248. log.Info("Dumping database %s => %s...", setting.Database.Type, targetDBType)
  249. } else {
  250. log.Info("Dumping database...")
  251. }
  252. if err := db.DumpDatabase(dbDump.Name(), targetDBType); err != nil {
  253. fatal("Failed to dump database: %v", err)
  254. }
  255. if err := addFile(w, "gitea-db.sql", dbDump.Name(), verbose); err != nil {
  256. fatal("Failed to include gitea-db.sql: %v", err)
  257. }
  258. if len(setting.CustomConf) > 0 {
  259. log.Info("Adding custom configuration file from %s", setting.CustomConf)
  260. if err := addFile(w, "app.ini", setting.CustomConf, verbose); err != nil {
  261. fatal("Failed to include specified app.ini: %v", err)
  262. }
  263. }
  264. if ctx.IsSet("skip-custom-dir") && ctx.Bool("skip-custom-dir") {
  265. log.Info("Skipping custom directory")
  266. } else {
  267. customDir, err := os.Stat(setting.CustomPath)
  268. if err == nil && customDir.IsDir() {
  269. if is, _ := isSubdir(setting.AppDataPath, setting.CustomPath); !is {
  270. if err := addRecursiveExclude(w, "custom", setting.CustomPath, []string{absFileName}, verbose); err != nil {
  271. fatal("Failed to include custom: %v", err)
  272. }
  273. } else {
  274. log.Info("Custom dir %s is inside data dir %s, skipped", setting.CustomPath, setting.AppDataPath)
  275. }
  276. } else {
  277. log.Info("Custom dir %s doesn't exist, skipped", setting.CustomPath)
  278. }
  279. }
  280. isExist, err := util.IsExist(setting.AppDataPath)
  281. if err != nil {
  282. log.Error("Unable to check if %s exists. Error: %v", setting.AppDataPath, err)
  283. }
  284. if isExist {
  285. log.Info("Packing data directory...%s", setting.AppDataPath)
  286. var excludes []string
  287. if setting.Cfg.Section("session").Key("PROVIDER").Value() == "file" {
  288. var opts session.Options
  289. if err = json.Unmarshal([]byte(setting.SessionConfig.ProviderConfig), &opts); err != nil {
  290. return err
  291. }
  292. excludes = append(excludes, opts.ProviderConfig)
  293. }
  294. if ctx.IsSet("skip-index") && ctx.Bool("skip-index") {
  295. excludes = append(excludes, setting.Indexer.RepoPath)
  296. excludes = append(excludes, setting.Indexer.IssuePath)
  297. }
  298. excludes = append(excludes, setting.RepoRootPath)
  299. excludes = append(excludes, setting.LFS.Path)
  300. excludes = append(excludes, setting.Attachment.Path)
  301. excludes = append(excludes, setting.Packages.Path)
  302. excludes = append(excludes, setting.LogRootPath)
  303. excludes = append(excludes, absFileName)
  304. if err := addRecursiveExclude(w, "data", setting.AppDataPath, excludes, verbose); err != nil {
  305. fatal("Failed to include data directory: %v", err)
  306. }
  307. }
  308. if ctx.IsSet("skip-attachment-data") && ctx.Bool("skip-attachment-data") {
  309. log.Info("Skip dumping attachment data")
  310. } else if err := storage.Attachments.IterateObjects(func(objPath string, object storage.Object) error {
  311. info, err := object.Stat()
  312. if err != nil {
  313. return err
  314. }
  315. return addReader(w, object, info, path.Join("data", "attachments", objPath), verbose)
  316. }); err != nil {
  317. fatal("Failed to dump attachments: %v", err)
  318. }
  319. if ctx.IsSet("skip-package-data") && ctx.Bool("skip-package-data") {
  320. log.Info("Skip dumping package data")
  321. } else if err := storage.Packages.IterateObjects(func(objPath string, object storage.Object) error {
  322. info, err := object.Stat()
  323. if err != nil {
  324. return err
  325. }
  326. return addReader(w, object, info, path.Join("data", "packages", objPath), verbose)
  327. }); err != nil {
  328. fatal("Failed to dump packages: %v", err)
  329. }
  330. // Doesn't check if LogRootPath exists before processing --skip-log intentionally,
  331. // ensuring that it's clear the dump is skipped whether the directory's initialized
  332. // yet or not.
  333. if ctx.IsSet("skip-log") && ctx.Bool("skip-log") {
  334. log.Info("Skip dumping log files")
  335. } else {
  336. isExist, err := util.IsExist(setting.LogRootPath)
  337. if err != nil {
  338. log.Error("Unable to check if %s exists. Error: %v", setting.LogRootPath, err)
  339. }
  340. if isExist {
  341. if err := addRecursiveExclude(w, "log", setting.LogRootPath, []string{absFileName}, verbose); err != nil {
  342. fatal("Failed to include log: %v", err)
  343. }
  344. }
  345. }
  346. if fileName != "-" {
  347. if err = w.Close(); err != nil {
  348. _ = util.Remove(fileName)
  349. fatal("Failed to save %s: %v", fileName, err)
  350. }
  351. if err := os.Chmod(fileName, 0o600); err != nil {
  352. log.Info("Can't change file access permissions mask to 0600: %v", err)
  353. }
  354. }
  355. if fileName != "-" {
  356. log.Info("Finish dumping in file %s", fileName)
  357. } else {
  358. log.Info("Finish dumping to stdout")
  359. }
  360. return nil
  361. }
  362. func contains(slice []string, s string) bool {
  363. for _, v := range slice {
  364. if v == s {
  365. return true
  366. }
  367. }
  368. return false
  369. }
  370. // addRecursiveExclude zips absPath to specified insidePath inside writer excluding excludeAbsPath
  371. func addRecursiveExclude(w archiver.Writer, insidePath, absPath string, excludeAbsPath []string, verbose bool) error {
  372. absPath, err := filepath.Abs(absPath)
  373. if err != nil {
  374. return err
  375. }
  376. dir, err := os.Open(absPath)
  377. if err != nil {
  378. return err
  379. }
  380. defer dir.Close()
  381. files, err := dir.Readdir(0)
  382. if err != nil {
  383. return err
  384. }
  385. for _, file := range files {
  386. currentAbsPath := path.Join(absPath, file.Name())
  387. currentInsidePath := path.Join(insidePath, file.Name())
  388. if file.IsDir() {
  389. if !contains(excludeAbsPath, currentAbsPath) {
  390. if err := addFile(w, currentInsidePath, currentAbsPath, false); err != nil {
  391. return err
  392. }
  393. if err = addRecursiveExclude(w, currentInsidePath, currentAbsPath, excludeAbsPath, verbose); err != nil {
  394. return err
  395. }
  396. }
  397. } else {
  398. // only copy regular files and symlink regular files, skip non-regular files like socket/pipe/...
  399. shouldAdd := file.Mode().IsRegular()
  400. if !shouldAdd && file.Mode()&os.ModeSymlink == os.ModeSymlink {
  401. target, err := filepath.EvalSymlinks(currentAbsPath)
  402. if err != nil {
  403. return err
  404. }
  405. targetStat, err := os.Stat(target)
  406. if err != nil {
  407. return err
  408. }
  409. shouldAdd = targetStat.Mode().IsRegular()
  410. }
  411. if shouldAdd {
  412. if err = addFile(w, currentInsidePath, currentAbsPath, verbose); err != nil {
  413. return err
  414. }
  415. }
  416. }
  417. }
  418. return nil
  419. }