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.

383 lines
10 KiB

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