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