s3_client.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package backup
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. "github.com/0xJacky/Nginx-UI/model"
  11. "github.com/minio/minio-go/v7"
  12. "github.com/minio/minio-go/v7/pkg/credentials"
  13. "github.com/uozi-tech/cosy"
  14. "github.com/uozi-tech/cosy/logger"
  15. )
  16. // S3Client wraps the MinIO client with backup-specific functionality
  17. type S3Client struct {
  18. client *minio.Client
  19. bucket string
  20. }
  21. // NewS3Client creates a new S3 client from auto backup configuration.
  22. // This function initializes the MinIO client with the provided credentials and configuration.
  23. //
  24. // Parameters:
  25. // - autoBackup: The auto backup configuration containing S3 settings
  26. //
  27. // Returns:
  28. // - *S3Client: Configured S3 client wrapper
  29. // - error: CosyError if client creation fails
  30. func NewS3Client(autoBackup *model.AutoBackup) (*S3Client, error) {
  31. // Determine endpoint and SSL settings
  32. endpoint := autoBackup.S3Endpoint
  33. if endpoint == "" {
  34. endpoint = "s3.amazonaws.com"
  35. }
  36. // Remove protocol prefix if present
  37. endpoint = strings.ReplaceAll(endpoint, "https://", "")
  38. endpoint = strings.ReplaceAll(endpoint, "http://", "")
  39. // Initialize MinIO client
  40. minioClient, err := minio.New(endpoint, &minio.Options{
  41. Creds: credentials.NewStaticV4(autoBackup.S3AccessKeyID, autoBackup.S3SecretAccessKey, ""),
  42. Secure: true, // Use SSL by default
  43. Region: getS3Region(autoBackup.S3Region),
  44. })
  45. if err != nil {
  46. return nil, cosy.WrapErrorWithParams(ErrAutoBackupS3Upload, fmt.Sprintf("failed to create MinIO client: %v", err))
  47. }
  48. return &S3Client{
  49. client: minioClient,
  50. bucket: autoBackup.S3Bucket,
  51. }, nil
  52. }
  53. // UploadFile uploads a file to S3 with the specified key.
  54. // This function handles the actual upload operation with proper error handling and logging.
  55. //
  56. // Parameters:
  57. // - ctx: Context for the upload operation
  58. // - key: S3 object key (path) for the uploaded file
  59. // - data: File content to upload
  60. // - contentType: MIME type of the file content
  61. //
  62. // Returns:
  63. // - error: CosyError if upload fails
  64. func (s3c *S3Client) UploadFile(ctx context.Context, key string, data []byte, contentType string) error {
  65. logger.Infof("Uploading file to S3: bucket=%s, key=%s, size=%d bytes", s3c.bucket, key, len(data))
  66. // Create upload options
  67. opts := minio.PutObjectOptions{
  68. ContentType: contentType,
  69. UserMetadata: map[string]string{
  70. "uploaded-by": "nginx-ui",
  71. "upload-time": time.Now().UTC().Format(time.RFC3339),
  72. "content-length": fmt.Sprintf("%d", len(data)),
  73. },
  74. }
  75. // Perform the upload
  76. _, err := s3c.client.PutObject(ctx, s3c.bucket, key, bytes.NewReader(data), int64(len(data)), opts)
  77. if err != nil {
  78. return cosy.WrapErrorWithParams(ErrAutoBackupS3Upload, fmt.Sprintf("failed to upload to S3: %v", err))
  79. }
  80. logger.Infof("Successfully uploaded file to S3: bucket=%s, key=%s", s3c.bucket, key)
  81. return nil
  82. }
  83. // UploadBackupFiles uploads backup files to S3 with proper naming and organization.
  84. // This function handles uploading both the backup file and optional key file.
  85. //
  86. // Parameters:
  87. // - ctx: Context for the upload operations
  88. // - result: Backup execution result containing file paths
  89. // - autoBackup: Auto backup configuration for S3 path construction
  90. //
  91. // Returns:
  92. // - error: CosyError if any upload fails
  93. func (s3c *S3Client) UploadBackupFiles(ctx context.Context, result *BackupExecutionResult, autoBackup *model.AutoBackup) error {
  94. // Read backup file content
  95. backupData, err := readFileContent(result.FilePath)
  96. if err != nil {
  97. return cosy.WrapErrorWithParams(ErrAutoBackupS3Upload, fmt.Sprintf("failed to read backup file: %v", err))
  98. }
  99. // Construct S3 key for backup file
  100. backupFileName := filepath.Base(result.FilePath)
  101. backupKey := constructS3Key(autoBackup.StoragePath, backupFileName)
  102. // Upload backup file
  103. if err := s3c.UploadFile(ctx, backupKey, backupData, "application/zip"); err != nil {
  104. return err
  105. }
  106. // Upload key file if it exists (for encrypted backups)
  107. if result.KeyPath != "" {
  108. keyData, err := readFileContent(result.KeyPath)
  109. if err != nil {
  110. return cosy.WrapErrorWithParams(ErrAutoBackupS3Upload, fmt.Sprintf("failed to read key file: %v", err))
  111. }
  112. keyFileName := filepath.Base(result.KeyPath)
  113. keyKey := constructS3Key(autoBackup.StoragePath, keyFileName)
  114. if err := s3c.UploadFile(ctx, keyKey, keyData, "text/plain"); err != nil {
  115. return err
  116. }
  117. }
  118. return nil
  119. }
  120. // TestS3Connection tests the S3 connection and permissions.
  121. // This function verifies that the S3 configuration is valid and accessible.
  122. //
  123. // Parameters:
  124. // - ctx: Context for the test operation
  125. //
  126. // Returns:
  127. // - error: CosyError if connection test fails
  128. func (s3c *S3Client) TestS3Connection(ctx context.Context) error {
  129. logger.Infof("Testing S3 connection: bucket=%s", s3c.bucket)
  130. // Try to check if the bucket exists and is accessible
  131. exists, err := s3c.client.BucketExists(ctx, s3c.bucket)
  132. if err != nil {
  133. return cosy.WrapErrorWithParams(ErrAutoBackupS3Upload, fmt.Sprintf("S3 connection test failed: %v", err))
  134. }
  135. if !exists {
  136. return cosy.WrapErrorWithParams(ErrAutoBackupS3Upload, fmt.Sprintf("S3 bucket does not exist: %s", s3c.bucket))
  137. }
  138. logger.Infof("S3 connection test successful: bucket=%s", s3c.bucket)
  139. return nil
  140. }
  141. // getS3Region returns the S3 region, defaulting to us-east-1 if not specified.
  142. // This function ensures a valid region is always provided to the MinIO client.
  143. //
  144. // Parameters:
  145. // - region: The configured S3 region
  146. //
  147. // Returns:
  148. // - string: Valid AWS region string
  149. func getS3Region(region string) string {
  150. if region == "" {
  151. return "us-east-1" // Default region
  152. }
  153. return region
  154. }
  155. // constructS3Key constructs a proper S3 object key from storage path and filename.
  156. // This function ensures consistent S3 key formatting across the application.
  157. //
  158. // Parameters:
  159. // - storagePath: Base storage path in S3
  160. // - filename: Name of the file
  161. //
  162. // Returns:
  163. // - string: Properly formatted S3 object key
  164. func constructS3Key(storagePath, filename string) string {
  165. // Ensure storage path doesn't start with slash and ends with slash
  166. if storagePath == "" {
  167. return filename
  168. }
  169. // Remove leading slash if present
  170. if storagePath[0] == '/' {
  171. storagePath = storagePath[1:]
  172. }
  173. // Add trailing slash if not present
  174. if storagePath[len(storagePath)-1] != '/' {
  175. storagePath += "/"
  176. }
  177. return storagePath + filename
  178. }
  179. // readFileContent reads the entire content of a file into memory.
  180. // This function provides a centralized way to read file content for S3 uploads.
  181. //
  182. // Parameters:
  183. // - filePath: Path to the file to read
  184. //
  185. // Returns:
  186. // - []byte: File content
  187. // - error: Standard error if file reading fails
  188. func readFileContent(filePath string) ([]byte, error) {
  189. return os.ReadFile(filePath)
  190. }
  191. // TestS3ConnectionForConfig tests S3 connection for a given auto backup configuration.
  192. // This function is used by the API to validate S3 settings before saving.
  193. //
  194. // Parameters:
  195. // - autoBackup: Auto backup configuration with S3 settings
  196. //
  197. // Returns:
  198. // - error: CosyError if connection test fails
  199. func TestS3ConnectionForConfig(autoBackup *model.AutoBackup) error {
  200. s3Client, err := NewS3Client(autoBackup)
  201. if err != nil {
  202. return err
  203. }
  204. return s3Client.TestS3Connection(context.Background())
  205. }