remote_file.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package procutils
  15. import (
  16. "fmt"
  17. "io"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "time"
  22. "yunion.io/x/log"
  23. "yunion.io/x/pkg/errors"
  24. )
  25. var (
  26. remoteTmpDir = "/var/run/onecloud/files"
  27. )
  28. func GetRemoteTempDir() string {
  29. return remoteTmpDir
  30. }
  31. func SetRemoteTempDir(dir string) {
  32. remoteTmpDir = dir
  33. }
  34. func EnsureDir(dir string) error {
  35. if dir != "" && dir != "." {
  36. mkdirCmd := NewRemoteCommandAsFarAsPossible("mkdir", "-p", dir)
  37. if err := mkdirCmd.Run(); err != nil {
  38. return errors.Wrapf(err, "mkdir -p %s", dir)
  39. }
  40. }
  41. return nil
  42. }
  43. func FilePutContents(filename string, content string) error {
  44. // Generate temp filename: replace / with _ and add timestamp
  45. // Example: /etc/abc.txt -> etc_abc.txt.1234567890
  46. tempName := strings.TrimPrefix(filename, "/")
  47. tempName = strings.ReplaceAll(tempName, "/", "_")
  48. timestamp := time.Now().Unix()
  49. tempPath := fmt.Sprintf("%s/%s.%d", GetRemoteTempDir(), tempName, timestamp)
  50. // Ensure tempPath dir
  51. if err := EnsureDir(filepath.Dir(tempPath)); err != nil {
  52. return errors.Wrapf(err, "EnsureDir %s", filepath.Dir(tempPath))
  53. }
  54. // Write temp file using Go native function
  55. if err := os.WriteFile(tempPath, []byte(content), 0644); err != nil {
  56. return errors.Wrapf(err, "write file %s", tempPath)
  57. }
  58. // Ensure target directory exists
  59. targetDir := filepath.Dir(filename)
  60. if err := EnsureDir(targetDir); err != nil {
  61. // Clean up temp file
  62. os.Remove(tempPath)
  63. return errors.Wrapf(err, "EnsureDir targetDir %s", targetDir)
  64. }
  65. // Move temp file to target location
  66. mvCmd := NewRemoteCommandAsFarAsPossible("mv", tempPath, filename)
  67. if err := mvCmd.Run(); err != nil {
  68. // Clean up temp file
  69. os.Remove(tempPath)
  70. return errors.Wrapf(err, "mv %s %s", tempPath, filename)
  71. }
  72. return nil
  73. }
  74. func FileGetContents(filename string) ([]byte, error) {
  75. cmd := NewRemoteCommandAsFarAsPossible("cat", filename)
  76. stdout, err := cmd.StdoutPipe()
  77. if err != nil {
  78. return nil, errors.Wrap(err, "StdoutPipe")
  79. }
  80. err = cmd.Start()
  81. if err != nil {
  82. return nil, errors.Wrap(err, "Run")
  83. }
  84. contentChan := make(chan []byte)
  85. go func() {
  86. defer stdout.Close()
  87. content, err := io.ReadAll(stdout)
  88. if err != nil {
  89. log.Errorf("ReadAll: %v", err)
  90. }
  91. contentChan <- content
  92. }()
  93. content := <-contentChan
  94. return content, nil
  95. }
  96. // IsEmptyFile 使用 shell 命令判断文件是否为空
  97. // 返回 true 表示文件存在且为空(大小为 0),false 表示文件不存在或不为空
  98. func IsEmptyFile(filename string) bool {
  99. // 使用 test -f 检查文件是否存在且为普通文件
  100. // 使用 test ! -s 检查文件是否为空(大小为 0)
  101. // test -f file && test ! -s file 表示文件存在且为空
  102. checkCmd := fmt.Sprintf("test -f '%s' && test ! -s '%s'", filename, filename)
  103. cmd := NewRemoteCommandAsFarAsPossible("sh", "-c", checkCmd)
  104. err := cmd.Run()
  105. return err == nil
  106. }