migrate.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package paths
  5. import (
  6. "os"
  7. "path/filepath"
  8. "tailscale.com/types/logger"
  9. )
  10. // TryConfigFileMigration carefully copies the contents of oldFile to
  11. // newFile, returning the path which should be used to read the config.
  12. // - if newFile already exists, don't modify it just return its path
  13. // - if neither oldFile nor newFile exist, return newFile for a fresh
  14. // default config to be written to.
  15. // - if oldFile exists but copying to newFile fails, return oldFile so
  16. // there will at least be some config to work with.
  17. func TryConfigFileMigration(logf logger.Logf, oldFile, newFile string) string {
  18. _, err := os.Stat(newFile)
  19. if err == nil {
  20. // Common case for a system which has already been migrated.
  21. return newFile
  22. }
  23. if !os.IsNotExist(err) {
  24. logf("TryConfigFileMigration failed; new file: %v", err)
  25. return newFile
  26. }
  27. contents, err := os.ReadFile(oldFile)
  28. if err != nil {
  29. // Common case for a new user.
  30. return newFile
  31. }
  32. if err = MkStateDir(filepath.Dir(newFile)); err != nil {
  33. logf("TryConfigFileMigration failed; MkStateDir: %v", err)
  34. return oldFile
  35. }
  36. err = os.WriteFile(newFile, contents, 0600)
  37. if err != nil {
  38. removeErr := os.Remove(newFile)
  39. if removeErr != nil {
  40. logf("TryConfigFileMigration failed; write newFile no cleanup: %v, remove err: %v",
  41. err, removeErr)
  42. return oldFile
  43. }
  44. logf("TryConfigFileMigration failed; write newFile: %v", err)
  45. return oldFile
  46. }
  47. logf("TryConfigFileMigration: successfully migrated: from %v to %v",
  48. oldFile, newFile)
  49. return newFile
  50. }