restore.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. // Copyright 2017 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "github.com/mcuadros/go-version"
  10. "github.com/pkg/errors"
  11. "github.com/unknwon/cae/zip"
  12. "github.com/unknwon/com"
  13. "github.com/urfave/cli"
  14. "gopkg.in/ini.v1"
  15. log "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/conf"
  17. "gogs.io/gogs/internal/db"
  18. )
  19. var Restore = cli.Command{
  20. Name: "restore",
  21. Usage: "Restore files and database from backup",
  22. Description: `Restore imports all related files and database from a backup archive.
  23. The backup version must lower or equal to current Gogs version. You can also import
  24. backup from other database engines, which is useful for database migrating.
  25. If corresponding files or database tables are not presented in the archive, they will
  26. be skipped and remain unchanged.`,
  27. Action: runRestore,
  28. Flags: []cli.Flag{
  29. stringFlag("config, c", "", "Custom configuration file path"),
  30. boolFlag("verbose, v", "Show process details"),
  31. stringFlag("tempdir, t", os.TempDir(), "Temporary directory path"),
  32. stringFlag("from", "", "Path to backup archive"),
  33. boolFlag("database-only", "Only import database"),
  34. boolFlag("exclude-repos", "Exclude repositories"),
  35. },
  36. }
  37. // lastSupportedVersionOfFormat returns the last supported version of the backup archive
  38. // format that is able to import.
  39. var lastSupportedVersionOfFormat = map[int]string{}
  40. func runRestore(c *cli.Context) error {
  41. zip.Verbose = c.Bool("verbose")
  42. tmpDir := c.String("tempdir")
  43. if !com.IsExist(tmpDir) {
  44. log.Fatal("'--tempdir' does not exist: %s", tmpDir)
  45. }
  46. log.Info("Restore backup from: %s", c.String("from"))
  47. if err := zip.ExtractTo(c.String("from"), tmpDir); err != nil {
  48. log.Fatal("Failed to extract backup archive: %v", err)
  49. }
  50. archivePath := path.Join(tmpDir, archiveRootDir)
  51. defer os.RemoveAll(archivePath)
  52. // Check backup version
  53. metaFile := filepath.Join(archivePath, "metadata.ini")
  54. if !com.IsExist(metaFile) {
  55. log.Fatal("File 'metadata.ini' is missing")
  56. }
  57. metadata, err := ini.Load(metaFile)
  58. if err != nil {
  59. log.Fatal("Failed to load metadata '%s': %v", metaFile, err)
  60. }
  61. backupVersion := metadata.Section("").Key("GOGS_VERSION").MustString("999.0")
  62. if version.Compare(conf.App.Version, backupVersion, "<") {
  63. log.Fatal("Current Gogs version is lower than backup version: %s < %s", conf.App.Version, backupVersion)
  64. }
  65. formatVersion := metadata.Section("").Key("VERSION").MustInt()
  66. if formatVersion == 0 {
  67. log.Fatal("Failed to determine the backup format version from metadata '%s': %s", metaFile, "VERSION is not presented")
  68. }
  69. if formatVersion != currentBackupFormatVersion {
  70. log.Fatal("Backup format version found is %d but this binary only supports %d\nThe last known version that is able to import your backup is %s",
  71. formatVersion, currentBackupFormatVersion, lastSupportedVersionOfFormat[formatVersion])
  72. }
  73. // If config file is not present in backup, user must set this file via flag.
  74. // Otherwise, it's optional to set config file flag.
  75. configFile := filepath.Join(archivePath, "custom", "conf", "app.ini")
  76. var customConf string
  77. if c.IsSet("config") {
  78. customConf = c.String("config")
  79. } else if !com.IsExist(configFile) {
  80. log.Fatal("'--config' is not specified and custom config file is not found in backup")
  81. } else {
  82. customConf = configFile
  83. }
  84. err = conf.Init(customConf)
  85. if err != nil {
  86. return errors.Wrap(err, "init configuration")
  87. }
  88. conf.InitLogging(true)
  89. conn, err := db.SetEngine()
  90. if err != nil {
  91. return errors.Wrap(err, "set engine")
  92. }
  93. // Database
  94. dbDir := path.Join(archivePath, "db")
  95. if err = db.ImportDatabase(conn, dbDir, c.Bool("verbose")); err != nil {
  96. log.Fatal("Failed to import database: %v", err)
  97. }
  98. // Custom files
  99. if !c.Bool("database-only") {
  100. if com.IsExist(conf.CustomDir()) {
  101. if err = os.Rename(conf.CustomDir(), conf.CustomDir()+".bak"); err != nil {
  102. log.Fatal("Failed to backup current 'custom': %v", err)
  103. }
  104. }
  105. if err = os.Rename(filepath.Join(archivePath, "custom"), conf.CustomDir()); err != nil {
  106. log.Fatal("Failed to import 'custom': %v", err)
  107. }
  108. }
  109. // Data files
  110. if !c.Bool("database-only") {
  111. _ = os.MkdirAll(conf.Server.AppDataPath, os.ModePerm)
  112. for _, dir := range []string{"attachments", "avatars", "repo-avatars"} {
  113. // Skip if backup archive does not have corresponding data
  114. srcPath := filepath.Join(archivePath, "data", dir)
  115. if !com.IsDir(srcPath) {
  116. continue
  117. }
  118. dirPath := filepath.Join(conf.Server.AppDataPath, dir)
  119. if com.IsExist(dirPath) {
  120. if err = os.Rename(dirPath, dirPath+".bak"); err != nil {
  121. log.Fatal("Failed to backup current 'data': %v", err)
  122. }
  123. }
  124. if err = os.Rename(srcPath, dirPath); err != nil {
  125. log.Fatal("Failed to import 'data': %v", err)
  126. }
  127. }
  128. }
  129. // Repositories
  130. reposPath := filepath.Join(archivePath, "repositories.zip")
  131. if !c.Bool("exclude-repos") && !c.Bool("database-only") && com.IsExist(reposPath) {
  132. if err := zip.ExtractTo(reposPath, filepath.Dir(conf.Repository.Root)); err != nil {
  133. log.Fatal("Failed to extract 'repositories.zip': %v", err)
  134. }
  135. }
  136. log.Info("Restore succeed!")
  137. log.Stop()
  138. return nil
  139. }