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 11KB

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