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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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.InitProviderFromExistingFile()
  167. setting.LoadCommonSettings()
  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. if !setting.InstallLock {
  177. log.Error("Is '%s' really the right config path?\n", setting.CustomConf)
  178. return fmt.Errorf("gitea is not initialized")
  179. }
  180. setting.LoadSettings() // cannot access session settings otherwise
  181. stdCtx, cancel := installSignals()
  182. defer cancel()
  183. err := db.InitEngine(stdCtx)
  184. if err != nil {
  185. return err
  186. }
  187. if err := storage.Init(); err != nil {
  188. return err
  189. }
  190. if file == nil {
  191. file, err = os.Create(fileName)
  192. if err != nil {
  193. fatal("Unable to open %s: %v", fileName, err)
  194. }
  195. }
  196. defer file.Close()
  197. absFileName, err := filepath.Abs(fileName)
  198. if err != nil {
  199. return err
  200. }
  201. verbose := ctx.Bool("verbose")
  202. var iface interface{}
  203. if fileName == "-" {
  204. iface, err = archiver.ByExtension(fmt.Sprintf(".%s", outType))
  205. } else {
  206. iface, err = archiver.ByExtension(fileName)
  207. }
  208. if err != nil {
  209. fatal("Unable to get archiver for extension: %v", err)
  210. }
  211. w, _ := iface.(archiver.Writer)
  212. if err := w.Create(file); err != nil {
  213. fatal("Creating archiver.Writer failed: %v", err)
  214. }
  215. defer w.Close()
  216. if ctx.IsSet("skip-repository") && ctx.Bool("skip-repository") {
  217. log.Info("Skip dumping local repositories")
  218. } else {
  219. log.Info("Dumping local repositories... %s", setting.RepoRootPath)
  220. if err := addRecursiveExclude(w, "repos", setting.RepoRootPath, []string{absFileName}, verbose); err != nil {
  221. fatal("Failed to include repositories: %v", err)
  222. }
  223. if ctx.IsSet("skip-lfs-data") && ctx.Bool("skip-lfs-data") {
  224. log.Info("Skip dumping LFS data")
  225. } else if !setting.LFS.StartServer {
  226. log.Info("LFS isn't enabled. Skip dumping LFS data")
  227. } else if err := storage.LFS.IterateObjects(func(objPath string, object storage.Object) error {
  228. info, err := object.Stat()
  229. if err != nil {
  230. return err
  231. }
  232. return addReader(w, object, info, path.Join("data", "lfs", objPath), verbose)
  233. }); err != nil {
  234. fatal("Failed to dump LFS objects: %v", err)
  235. }
  236. }
  237. tmpDir := ctx.String("tempdir")
  238. if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
  239. fatal("Path does not exist: %s", tmpDir)
  240. }
  241. dbDump, err := os.CreateTemp(tmpDir, "gitea-db.sql")
  242. if err != nil {
  243. fatal("Failed to create tmp file: %v", err)
  244. }
  245. defer func() {
  246. _ = dbDump.Close()
  247. if err := util.Remove(dbDump.Name()); err != nil {
  248. log.Warn("Unable to remove temporary file: %s: Error: %v", dbDump.Name(), err)
  249. }
  250. }()
  251. targetDBType := ctx.String("database")
  252. if len(targetDBType) > 0 && targetDBType != setting.Database.Type.String() {
  253. log.Info("Dumping database %s => %s...", setting.Database.Type, targetDBType)
  254. } else {
  255. log.Info("Dumping database...")
  256. }
  257. if err := db.DumpDatabase(dbDump.Name(), targetDBType); err != nil {
  258. fatal("Failed to dump database: %v", err)
  259. }
  260. if err := addFile(w, "gitea-db.sql", dbDump.Name(), verbose); err != nil {
  261. fatal("Failed to include gitea-db.sql: %v", err)
  262. }
  263. if len(setting.CustomConf) > 0 {
  264. log.Info("Adding custom configuration file from %s", setting.CustomConf)
  265. if err := addFile(w, "app.ini", setting.CustomConf, verbose); err != nil {
  266. fatal("Failed to include specified app.ini: %v", err)
  267. }
  268. }
  269. if ctx.IsSet("skip-custom-dir") && ctx.Bool("skip-custom-dir") {
  270. log.Info("Skipping custom directory")
  271. } else {
  272. customDir, err := os.Stat(setting.CustomPath)
  273. if err == nil && customDir.IsDir() {
  274. if is, _ := isSubdir(setting.AppDataPath, setting.CustomPath); !is {
  275. if err := addRecursiveExclude(w, "custom", setting.CustomPath, []string{absFileName}, verbose); err != nil {
  276. fatal("Failed to include custom: %v", err)
  277. }
  278. } else {
  279. log.Info("Custom dir %s is inside data dir %s, skipped", setting.CustomPath, setting.AppDataPath)
  280. }
  281. } else {
  282. log.Info("Custom dir %s doesn't exist, skipped", setting.CustomPath)
  283. }
  284. }
  285. isExist, err := util.IsExist(setting.AppDataPath)
  286. if err != nil {
  287. log.Error("Unable to check if %s exists. Error: %v", setting.AppDataPath, err)
  288. }
  289. if isExist {
  290. log.Info("Packing data directory...%s", setting.AppDataPath)
  291. var excludes []string
  292. if setting.SessionConfig.OriginalProvider == "file" {
  293. var opts session.Options
  294. if err = json.Unmarshal([]byte(setting.SessionConfig.ProviderConfig), &opts); err != nil {
  295. return err
  296. }
  297. excludes = append(excludes, opts.ProviderConfig)
  298. }
  299. if ctx.IsSet("skip-index") && ctx.Bool("skip-index") {
  300. excludes = append(excludes, setting.Indexer.RepoPath)
  301. excludes = append(excludes, setting.Indexer.IssuePath)
  302. }
  303. excludes = append(excludes, setting.RepoRootPath)
  304. excludes = append(excludes, setting.LFS.Path)
  305. excludes = append(excludes, setting.Attachment.Path)
  306. excludes = append(excludes, setting.Packages.Path)
  307. excludes = append(excludes, setting.Log.RootPath)
  308. excludes = append(excludes, absFileName)
  309. if err := addRecursiveExclude(w, "data", setting.AppDataPath, excludes, verbose); err != nil {
  310. fatal("Failed to include data directory: %v", err)
  311. }
  312. }
  313. if ctx.IsSet("skip-attachment-data") && ctx.Bool("skip-attachment-data") {
  314. log.Info("Skip dumping attachment data")
  315. } else if err := storage.Attachments.IterateObjects(func(objPath string, object storage.Object) error {
  316. info, err := object.Stat()
  317. if err != nil {
  318. return err
  319. }
  320. return addReader(w, object, info, path.Join("data", "attachments", objPath), verbose)
  321. }); err != nil {
  322. fatal("Failed to dump attachments: %v", err)
  323. }
  324. if ctx.IsSet("skip-package-data") && ctx.Bool("skip-package-data") {
  325. log.Info("Skip dumping package data")
  326. } else if !setting.Packages.Enabled {
  327. log.Info("Packages isn't enabled. Skip dumping package data")
  328. } else if err := storage.Packages.IterateObjects(func(objPath string, object storage.Object) error {
  329. info, err := object.Stat()
  330. if err != nil {
  331. return err
  332. }
  333. return addReader(w, object, info, path.Join("data", "packages", objPath), verbose)
  334. }); err != nil {
  335. fatal("Failed to dump packages: %v", err)
  336. }
  337. // Doesn't check if LogRootPath exists before processing --skip-log intentionally,
  338. // ensuring that it's clear the dump is skipped whether the directory's initialized
  339. // yet or not.
  340. if ctx.IsSet("skip-log") && ctx.Bool("skip-log") {
  341. log.Info("Skip dumping log files")
  342. } else {
  343. isExist, err := util.IsExist(setting.Log.RootPath)
  344. if err != nil {
  345. log.Error("Unable to check if %s exists. Error: %v", setting.Log.RootPath, err)
  346. }
  347. if isExist {
  348. if err := addRecursiveExclude(w, "log", setting.Log.RootPath, []string{absFileName}, verbose); err != nil {
  349. fatal("Failed to include log: %v", err)
  350. }
  351. }
  352. }
  353. if fileName != "-" {
  354. if err = w.Close(); err != nil {
  355. _ = util.Remove(fileName)
  356. fatal("Failed to save %s: %v", fileName, err)
  357. }
  358. if err := os.Chmod(fileName, 0o600); err != nil {
  359. log.Info("Can't change file access permissions mask to 0600: %v", err)
  360. }
  361. }
  362. if fileName != "-" {
  363. log.Info("Finish dumping in file %s", fileName)
  364. } else {
  365. log.Info("Finish dumping to stdout")
  366. }
  367. return nil
  368. }
  369. // addRecursiveExclude zips absPath to specified insidePath inside writer excluding excludeAbsPath
  370. func addRecursiveExclude(w archiver.Writer, insidePath, absPath string, excludeAbsPath []string, verbose bool) error {
  371. absPath, err := filepath.Abs(absPath)
  372. if err != nil {
  373. return err
  374. }
  375. dir, err := os.Open(absPath)
  376. if err != nil {
  377. return err
  378. }
  379. defer dir.Close()
  380. files, err := dir.Readdir(0)
  381. if err != nil {
  382. return err
  383. }
  384. for _, file := range files {
  385. currentAbsPath := path.Join(absPath, file.Name())
  386. currentInsidePath := path.Join(insidePath, file.Name())
  387. if file.IsDir() {
  388. if !util.SliceContainsString(excludeAbsPath, currentAbsPath) {
  389. if err := addFile(w, currentInsidePath, currentAbsPath, false); err != nil {
  390. return err
  391. }
  392. if err = addRecursiveExclude(w, currentInsidePath, currentAbsPath, excludeAbsPath, verbose); err != nil {
  393. return err
  394. }
  395. }
  396. } else {
  397. // only copy regular files and symlink regular files, skip non-regular files like socket/pipe/...
  398. shouldAdd := file.Mode().IsRegular()
  399. if !shouldAdd && file.Mode()&os.ModeSymlink == os.ModeSymlink {
  400. target, err := filepath.EvalSymlinks(currentAbsPath)
  401. if err != nil {
  402. return err
  403. }
  404. targetStat, err := os.Stat(target)
  405. if err != nil {
  406. return err
  407. }
  408. shouldAdd = targetStat.Mode().IsRegular()
  409. }
  410. if shouldAdd {
  411. if err = addFile(w, currentInsidePath, currentAbsPath, verbose); err != nil {
  412. return err
  413. }
  414. }
  415. }
  416. }
  417. return nil
  418. }