create_vacuum_test_data.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "encoding/json"
  6. "flag"
  7. "fmt"
  8. "io"
  9. "log"
  10. "net/http"
  11. "time"
  12. )
  13. var (
  14. master = flag.String("master", "master:9333", "SeaweedFS master server address")
  15. fileCount = flag.Int("files", 20, "Number of files to create")
  16. deleteRatio = flag.Float64("delete", 0.4, "Ratio of files to delete (0.0-1.0)")
  17. fileSizeKB = flag.Int("size", 100, "Size of each file in KB")
  18. )
  19. type AssignResult struct {
  20. Fid string `json:"fid"`
  21. Url string `json:"url"`
  22. PublicUrl string `json:"publicUrl"`
  23. Count int `json:"count"`
  24. Error string `json:"error"`
  25. }
  26. func main() {
  27. flag.Parse()
  28. fmt.Println("🧪 Creating fake data for vacuum task testing...")
  29. fmt.Printf("Master: %s\n", *master)
  30. fmt.Printf("Files to create: %d\n", *fileCount)
  31. fmt.Printf("Delete ratio: %.1f%%\n", *deleteRatio*100)
  32. fmt.Printf("File size: %d KB\n", *fileSizeKB)
  33. fmt.Println()
  34. if *fileCount == 0 {
  35. // Just check volume status
  36. fmt.Println("📊 Checking volume status...")
  37. checkVolumeStatus()
  38. return
  39. }
  40. // Step 1: Create test files
  41. fmt.Println("📁 Step 1: Creating test files...")
  42. fids := createTestFiles()
  43. // Step 2: Delete some files to create garbage
  44. fmt.Println("🗑️ Step 2: Deleting files to create garbage...")
  45. deleteFiles(fids)
  46. // Step 3: Check volume status
  47. fmt.Println("📊 Step 3: Checking volume status...")
  48. checkVolumeStatus()
  49. // Step 4: Configure vacuum for testing
  50. fmt.Println("⚙️ Step 4: Instructions for testing...")
  51. printTestingInstructions()
  52. }
  53. func createTestFiles() []string {
  54. var fids []string
  55. for i := 0; i < *fileCount; i++ {
  56. // Generate random file content
  57. fileData := make([]byte, *fileSizeKB*1024)
  58. rand.Read(fileData)
  59. // Get file ID assignment
  60. assign, err := assignFileId()
  61. if err != nil {
  62. log.Printf("Failed to assign file ID for file %d: %v", i, err)
  63. continue
  64. }
  65. // Upload file
  66. err = uploadFile(assign, fileData, fmt.Sprintf("test_file_%d.dat", i))
  67. if err != nil {
  68. log.Printf("Failed to upload file %d: %v", i, err)
  69. continue
  70. }
  71. fids = append(fids, assign.Fid)
  72. if (i+1)%5 == 0 {
  73. fmt.Printf(" Created %d/%d files...\n", i+1, *fileCount)
  74. }
  75. }
  76. fmt.Printf("✅ Created %d files successfully\n\n", len(fids))
  77. return fids
  78. }
  79. func deleteFiles(fids []string) {
  80. deleteCount := int(float64(len(fids)) * *deleteRatio)
  81. for i := 0; i < deleteCount; i++ {
  82. err := deleteFile(fids[i])
  83. if err != nil {
  84. log.Printf("Failed to delete file %s: %v", fids[i], err)
  85. continue
  86. }
  87. if (i+1)%5 == 0 {
  88. fmt.Printf(" Deleted %d/%d files...\n", i+1, deleteCount)
  89. }
  90. }
  91. fmt.Printf("✅ Deleted %d files (%.1f%% of total)\n\n", deleteCount, *deleteRatio*100)
  92. }
  93. func assignFileId() (*AssignResult, error) {
  94. resp, err := http.Get(fmt.Sprintf("http://%s/dir/assign", *master))
  95. if err != nil {
  96. return nil, err
  97. }
  98. defer resp.Body.Close()
  99. var result AssignResult
  100. err = json.NewDecoder(resp.Body).Decode(&result)
  101. if err != nil {
  102. return nil, err
  103. }
  104. if result.Error != "" {
  105. return nil, fmt.Errorf("assignment error: %s", result.Error)
  106. }
  107. return &result, nil
  108. }
  109. func uploadFile(assign *AssignResult, data []byte, filename string) error {
  110. url := fmt.Sprintf("http://%s/%s", assign.Url, assign.Fid)
  111. body := &bytes.Buffer{}
  112. body.Write(data)
  113. req, err := http.NewRequest("POST", url, body)
  114. if err != nil {
  115. return err
  116. }
  117. req.Header.Set("Content-Type", "application/octet-stream")
  118. if filename != "" {
  119. req.Header.Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  120. }
  121. client := &http.Client{Timeout: 30 * time.Second}
  122. resp, err := client.Do(req)
  123. if err != nil {
  124. return err
  125. }
  126. defer resp.Body.Close()
  127. if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
  128. body, _ := io.ReadAll(resp.Body)
  129. return fmt.Errorf("upload failed with status %d: %s", resp.StatusCode, string(body))
  130. }
  131. return nil
  132. }
  133. func deleteFile(fid string) error {
  134. url := fmt.Sprintf("http://%s/%s", *master, fid)
  135. req, err := http.NewRequest("DELETE", url, nil)
  136. if err != nil {
  137. return err
  138. }
  139. client := &http.Client{Timeout: 10 * time.Second}
  140. resp, err := client.Do(req)
  141. if err != nil {
  142. return err
  143. }
  144. defer resp.Body.Close()
  145. return nil
  146. }
  147. func checkVolumeStatus() {
  148. // Get volume list from master
  149. resp, err := http.Get(fmt.Sprintf("http://%s/vol/status", *master))
  150. if err != nil {
  151. log.Printf("Failed to get volume status: %v", err)
  152. return
  153. }
  154. defer resp.Body.Close()
  155. var volumes map[string]interface{}
  156. err = json.NewDecoder(resp.Body).Decode(&volumes)
  157. if err != nil {
  158. log.Printf("Failed to decode volume status: %v", err)
  159. return
  160. }
  161. fmt.Println("📊 Volume Status Summary:")
  162. if vols, ok := volumes["Volumes"].([]interface{}); ok {
  163. for _, vol := range vols {
  164. if v, ok := vol.(map[string]interface{}); ok {
  165. id := int(v["Id"].(float64))
  166. size := uint64(v["Size"].(float64))
  167. fileCount := int(v["FileCount"].(float64))
  168. deleteCount := int(v["DeleteCount"].(float64))
  169. deletedBytes := uint64(v["DeletedByteCount"].(float64))
  170. garbageRatio := 0.0
  171. if size > 0 {
  172. garbageRatio = float64(deletedBytes) / float64(size) * 100
  173. }
  174. fmt.Printf(" Volume %d:\n", id)
  175. fmt.Printf(" Size: %s\n", formatBytes(size))
  176. fmt.Printf(" Files: %d (active), %d (deleted)\n", fileCount, deleteCount)
  177. fmt.Printf(" Garbage: %s (%.1f%%)\n", formatBytes(deletedBytes), garbageRatio)
  178. if garbageRatio > 30 {
  179. fmt.Printf(" 🎯 This volume should trigger vacuum (>30%% garbage)\n")
  180. }
  181. fmt.Println()
  182. }
  183. }
  184. }
  185. }
  186. func formatBytes(bytes uint64) string {
  187. if bytes < 1024 {
  188. return fmt.Sprintf("%d B", bytes)
  189. } else if bytes < 1024*1024 {
  190. return fmt.Sprintf("%.1f KB", float64(bytes)/1024)
  191. } else if bytes < 1024*1024*1024 {
  192. return fmt.Sprintf("%.1f MB", float64(bytes)/(1024*1024))
  193. } else {
  194. return fmt.Sprintf("%.1f GB", float64(bytes)/(1024*1024*1024))
  195. }
  196. }
  197. func printTestingInstructions() {
  198. fmt.Println("🧪 Testing Instructions:")
  199. fmt.Println()
  200. fmt.Println("1. Configure Vacuum for Testing:")
  201. fmt.Println(" Visit: http://localhost:23646/maintenance/config/vacuum")
  202. fmt.Println(" Set:")
  203. fmt.Printf(" - Garbage Percentage Threshold: 20 (20%% - lower than default 30)\n")
  204. fmt.Printf(" - Scan Interval: [30] [Seconds] (faster than default)\n")
  205. fmt.Printf(" - Min Volume Age: [0] [Minutes] (no age requirement)\n")
  206. fmt.Printf(" - Max Concurrent: 2\n")
  207. fmt.Printf(" - Min Interval: 1m (faster repeat)\n")
  208. fmt.Println()
  209. fmt.Println("2. Monitor Vacuum Tasks:")
  210. fmt.Println(" Visit: http://localhost:23646/maintenance")
  211. fmt.Println(" Watch for vacuum tasks to appear in the queue")
  212. fmt.Println()
  213. fmt.Println("3. Manual Vacuum (Optional):")
  214. fmt.Println(" curl -X POST 'http://localhost:9333/vol/vacuum?garbageThreshold=0.20'")
  215. fmt.Println(" (Note: Master API still uses 0.0-1.0 decimal format)")
  216. fmt.Println()
  217. fmt.Println("4. Check Logs:")
  218. fmt.Println(" Look for messages like:")
  219. fmt.Println(" - 'Vacuum detector found X volumes needing vacuum'")
  220. fmt.Println(" - 'Applied vacuum configuration'")
  221. fmt.Println(" - 'Worker executing task: vacuum'")
  222. fmt.Println()
  223. fmt.Println("5. Verify Results:")
  224. fmt.Println(" Re-run this script with -files=0 to check volume status")
  225. fmt.Println(" Garbage ratios should decrease after vacuum operations")
  226. fmt.Println()
  227. fmt.Printf("🚀 Quick test command:\n")
  228. fmt.Printf(" go run create_vacuum_test_data.go -files=0\n")
  229. fmt.Println()
  230. }