restore.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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/pkg/errors"
  10. "github.com/unknwon/cae/zip"
  11. "github.com/urfave/cli"
  12. "gopkg.in/ini.v1"
  13. log "unknwon.dev/clog/v2"
  14. "gogs.io/gogs/internal/conf"
  15. "gogs.io/gogs/internal/db"
  16. "gogs.io/gogs/internal/osutil"
  17. "gogs.io/gogs/internal/semverutil"
  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 !osutil.IsDir(tmpDir) {
  44. log.Fatal("'--tempdir' does not exist: %s", tmpDir)
  45. }
  46. archivePath := path.Join(tmpDir, archiveRootDir)
  47. // Make sure there was no leftover and also clean up afterwards
  48. err := os.RemoveAll(archivePath)
  49. if err != nil {
  50. log.Fatal("Failed to clean up previous leftover in %q: %v", archivePath, err)
  51. }
  52. defer func() { _ = os.RemoveAll(archivePath) }()
  53. log.Info("Restoring backup from: %s", c.String("from"))
  54. err = zip.ExtractTo(c.String("from"), tmpDir)
  55. if err != nil {
  56. log.Fatal("Failed to extract backup archive: %v", err)
  57. }
  58. // Check backup version
  59. metaFile := filepath.Join(archivePath, "metadata.ini")
  60. if !osutil.IsFile(metaFile) {
  61. log.Fatal("File 'metadata.ini' is missing")
  62. }
  63. metadata, err := ini.Load(metaFile)
  64. if err != nil {
  65. log.Fatal("Failed to load metadata '%s': %v", metaFile, err)
  66. }
  67. backupVersion := metadata.Section("").Key("GOGS_VERSION").MustString("999.0")
  68. if semverutil.Compare(conf.App.Version, "<", backupVersion) {
  69. log.Fatal("Current Gogs version is lower than backup version: %s < %s", conf.App.Version, backupVersion)
  70. }
  71. formatVersion := metadata.Section("").Key("VERSION").MustInt()
  72. if formatVersion == 0 {
  73. log.Fatal("Failed to determine the backup format version from metadata '%s': %s", metaFile, "VERSION is not presented")
  74. }
  75. if formatVersion != currentBackupFormatVersion {
  76. 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",
  77. formatVersion, currentBackupFormatVersion, lastSupportedVersionOfFormat[formatVersion])
  78. }
  79. // If config file is not present in backup, user must set this file via flag.
  80. // Otherwise, it's optional to set config file flag.
  81. configFile := filepath.Join(archivePath, "custom", "conf", "app.ini")
  82. var customConf string
  83. if c.IsSet("config") {
  84. customConf = c.String("config")
  85. } else if !osutil.IsFile(configFile) {
  86. log.Fatal("'--config' is not specified and custom config file is not found in backup")
  87. } else {
  88. customConf = configFile
  89. }
  90. err = conf.Init(customConf)
  91. if err != nil {
  92. return errors.Wrap(err, "init configuration")
  93. }
  94. conf.InitLogging(true)
  95. conn, err := db.SetEngine()
  96. if err != nil {
  97. return errors.Wrap(err, "set engine")
  98. }
  99. // Database
  100. dbDir := path.Join(archivePath, "db")
  101. if err = db.ImportDatabase(conn, dbDir, c.Bool("verbose")); err != nil {
  102. log.Fatal("Failed to import database: %v", err)
  103. }
  104. // Custom files
  105. if !c.Bool("database-only") {
  106. if osutil.IsDir(conf.CustomDir()) {
  107. if err = os.Rename(conf.CustomDir(), conf.CustomDir()+".bak"); err != nil {
  108. log.Fatal("Failed to backup current 'custom': %v", err)
  109. }
  110. }
  111. if err = os.Rename(filepath.Join(archivePath, "custom"), conf.CustomDir()); err != nil {
  112. log.Fatal("Failed to import 'custom': %v", err)
  113. }
  114. }
  115. // Data files
  116. if !c.Bool("database-only") {
  117. _ = os.MkdirAll(conf.Server.AppDataPath, os.ModePerm)
  118. for _, dir := range []string{"attachments", "avatars", "repo-avatars"} {
  119. // Skip if backup archive does not have corresponding data
  120. srcPath := filepath.Join(archivePath, "data", dir)
  121. if !osutil.IsDir(srcPath) {
  122. continue
  123. }
  124. dirPath := filepath.Join(conf.Server.AppDataPath, dir)
  125. if osutil.IsDir(dirPath) {
  126. if err = os.Rename(dirPath, dirPath+".bak"); err != nil {
  127. log.Fatal("Failed to backup current 'data': %v", err)
  128. }
  129. }
  130. if err = os.Rename(srcPath, dirPath); err != nil {
  131. log.Fatal("Failed to import 'data': %v", err)
  132. }
  133. }
  134. }
  135. // Repositories
  136. reposPath := filepath.Join(archivePath, "repositories.zip")
  137. if !c.Bool("exclude-repos") && !c.Bool("database-only") && osutil.IsFile(reposPath) {
  138. if err := zip.ExtractTo(reposPath, filepath.Dir(conf.Repository.Root)); err != nil {
  139. log.Fatal("Failed to extract 'repositories.zip': %v", err)
  140. }
  141. }
  142. log.Info("Restore succeed!")
  143. log.Stop()
  144. return nil
  145. }