You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

dump.go 11 kB

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