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.

387 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. if !setting.InstallLock {
  171. log.Error("Is '%s' really the right config path?\n", setting.CustomConf)
  172. return fmt.Errorf("gitea is not initialized")
  173. }
  174. setting.NewServices() // cannot access session settings otherwise
  175. err := models.SetEngine()
  176. if err != nil {
  177. return err
  178. }
  179. if file == nil {
  180. file, err = os.Create(fileName)
  181. if err != nil {
  182. fatal("Unable to open %s: %v", fileName, err)
  183. }
  184. }
  185. defer file.Close()
  186. verbose := ctx.Bool("verbose")
  187. outType := ctx.String("type")
  188. var iface interface{}
  189. if fileName == "-" {
  190. iface, err = archiver.ByExtension(fmt.Sprintf(".%s", outType))
  191. } else {
  192. iface, err = archiver.ByExtension(fileName)
  193. }
  194. if err != nil {
  195. fatal("Unable to get archiver for extension: %v", err)
  196. }
  197. w, _ := iface.(archiver.Writer)
  198. if err := w.Create(file); err != nil {
  199. fatal("Creating archiver.Writer failed: %v", err)
  200. }
  201. defer w.Close()
  202. if ctx.IsSet("skip-repository") && ctx.Bool("skip-repository") {
  203. log.Info("Skip dumping local repositories")
  204. } else {
  205. log.Info("Dumping local repositories... %s", setting.RepoRootPath)
  206. if err := addRecursive(w, "repos", setting.RepoRootPath, verbose); err != nil {
  207. fatal("Failed to include repositories: %v", err)
  208. }
  209. if _, err := os.Stat(setting.LFS.ContentPath); !os.IsNotExist(err) {
  210. log.Info("Dumping lfs... %s", setting.LFS.ContentPath)
  211. if err := addRecursive(w, "lfs", setting.LFS.ContentPath, verbose); err != nil {
  212. fatal("Failed to include lfs: %v", err)
  213. }
  214. }
  215. }
  216. tmpDir := ctx.String("tempdir")
  217. if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
  218. fatal("Path does not exist: %s", tmpDir)
  219. }
  220. dbDump, err := ioutil.TempFile(tmpDir, "gitea-db.sql")
  221. if err != nil {
  222. fatal("Failed to create tmp file: %v", err)
  223. }
  224. defer func() {
  225. if err := util.Remove(dbDump.Name()); err != nil {
  226. log.Warn("Unable to remove temporary file: %s: Error: %v", dbDump.Name(), err)
  227. }
  228. }()
  229. targetDBType := ctx.String("database")
  230. if len(targetDBType) > 0 && targetDBType != setting.Database.Type {
  231. log.Info("Dumping database %s => %s...", setting.Database.Type, targetDBType)
  232. } else {
  233. log.Info("Dumping database...")
  234. }
  235. if err := models.DumpDatabase(dbDump.Name(), targetDBType); err != nil {
  236. fatal("Failed to dump database: %v", err)
  237. }
  238. if err := addFile(w, "gitea-db.sql", dbDump.Name(), verbose); err != nil {
  239. fatal("Failed to include gitea-db.sql: %v", err)
  240. }
  241. if len(setting.CustomConf) > 0 {
  242. log.Info("Adding custom configuration file from %s", setting.CustomConf)
  243. if err := addFile(w, "app.ini", setting.CustomConf, verbose); err != nil {
  244. fatal("Failed to include specified app.ini: %v", err)
  245. }
  246. }
  247. customDir, err := os.Stat(setting.CustomPath)
  248. if err == nil && customDir.IsDir() {
  249. if is, _ := isSubdir(setting.AppDataPath, setting.CustomPath); !is {
  250. if err := addRecursive(w, "custom", setting.CustomPath, verbose); err != nil {
  251. fatal("Failed to include custom: %v", err)
  252. }
  253. } else {
  254. log.Info("Custom dir %s is inside data dir %s, skipped", setting.CustomPath, setting.AppDataPath)
  255. }
  256. } else {
  257. log.Info("Custom dir %s doesn't exist, skipped", setting.CustomPath)
  258. }
  259. if com.IsExist(setting.AppDataPath) {
  260. log.Info("Packing data directory...%s", setting.AppDataPath)
  261. var excludes []string
  262. if setting.Cfg.Section("session").Key("PROVIDER").Value() == "file" {
  263. var opts session.Options
  264. if err = json.Unmarshal([]byte(setting.SessionConfig.ProviderConfig), &opts); err != nil {
  265. return err
  266. }
  267. excludes = append(excludes, opts.ProviderConfig)
  268. }
  269. excludes = append(excludes, setting.RepoRootPath)
  270. excludes = append(excludes, setting.LFS.ContentPath)
  271. excludes = append(excludes, setting.LogRootPath)
  272. if err := addRecursiveExclude(w, "data", setting.AppDataPath, excludes, verbose); err != nil {
  273. fatal("Failed to include data directory: %v", err)
  274. }
  275. }
  276. // Doesn't check if LogRootPath exists before processing --skip-log intentionally,
  277. // ensuring that it's clear the dump is skipped whether the directory's initialized
  278. // yet or not.
  279. if ctx.IsSet("skip-log") && ctx.Bool("skip-log") {
  280. log.Info("Skip dumping log files")
  281. } else if com.IsExist(setting.LogRootPath) {
  282. if err := addRecursive(w, "log", setting.LogRootPath, verbose); err != nil {
  283. fatal("Failed to include log: %v", err)
  284. }
  285. }
  286. if fileName != "-" {
  287. if err = w.Close(); err != nil {
  288. _ = util.Remove(fileName)
  289. fatal("Failed to save %s: %v", fileName, err)
  290. }
  291. if err := os.Chmod(fileName, 0600); err != nil {
  292. log.Info("Can't change file access permissions mask to 0600: %v", err)
  293. }
  294. }
  295. if fileName != "-" {
  296. log.Info("Finish dumping in file %s", fileName)
  297. } else {
  298. log.Info("Finish dumping to stdout")
  299. }
  300. return nil
  301. }
  302. func contains(slice []string, s string) bool {
  303. for _, v := range slice {
  304. if v == s {
  305. return true
  306. }
  307. }
  308. return false
  309. }
  310. // addRecursiveExclude zips absPath to specified insidePath inside writer excluding excludeAbsPath
  311. func addRecursiveExclude(w archiver.Writer, insidePath, absPath string, excludeAbsPath []string, verbose bool) error {
  312. absPath, err := filepath.Abs(absPath)
  313. if err != nil {
  314. return err
  315. }
  316. dir, err := os.Open(absPath)
  317. if err != nil {
  318. return err
  319. }
  320. defer dir.Close()
  321. files, err := dir.Readdir(0)
  322. if err != nil {
  323. return err
  324. }
  325. for _, file := range files {
  326. currentAbsPath := path.Join(absPath, file.Name())
  327. currentInsidePath := path.Join(insidePath, file.Name())
  328. if file.IsDir() {
  329. if !contains(excludeAbsPath, currentAbsPath) {
  330. if err := addFile(w, currentInsidePath, currentAbsPath, false); err != nil {
  331. return err
  332. }
  333. if err = addRecursiveExclude(w, currentInsidePath, currentAbsPath, excludeAbsPath, verbose); err != nil {
  334. return err
  335. }
  336. }
  337. } else {
  338. if err = addFile(w, currentInsidePath, currentAbsPath, verbose); err != nil {
  339. return err
  340. }
  341. }
  342. }
  343. return nil
  344. }