You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

540 lines
15 KiB

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "math"
  7. "math/rand"
  8. "os"
  9. "runtime"
  10. "runtime/pprof"
  11. "sort"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/chrislusf/weed-fs/go/glog"
  16. "github.com/chrislusf/weed-fs/go/operation"
  17. "github.com/chrislusf/weed-fs/go/util"
  18. )
  19. type BenchmarkOptions struct {
  20. server *string
  21. concurrency *int
  22. numberOfFiles *int
  23. fileSize *int
  24. idListFile *string
  25. write *bool
  26. deletePercentage *int
  27. read *bool
  28. sequentialRead *bool
  29. collection *string
  30. cpuprofile *string
  31. maxCpu *int
  32. vid2server map[string]string //cache for vid locations
  33. }
  34. var (
  35. b BenchmarkOptions
  36. sharedBytes []byte
  37. )
  38. func init() {
  39. cmdBenchmark.Run = runbenchmark // break init cycle
  40. cmdBenchmark.IsDebug = cmdBenchmark.Flag.Bool("debug", false, "verbose debug information")
  41. b.server = cmdBenchmark.Flag.String("server", "localhost:9333", "weedfs master location")
  42. b.concurrency = cmdBenchmark.Flag.Int("c", 16, "number of concurrent write or read processes")
  43. b.fileSize = cmdBenchmark.Flag.Int("size", 1024, "simulated file size in bytes, with random(0~63) bytes padding")
  44. b.numberOfFiles = cmdBenchmark.Flag.Int("n", 1024*1024, "number of files to write for each thread")
  45. b.idListFile = cmdBenchmark.Flag.String("list", os.TempDir()+"/benchmark_list.txt", "list of uploaded file ids")
  46. b.write = cmdBenchmark.Flag.Bool("write", true, "enable write")
  47. b.deletePercentage = cmdBenchmark.Flag.Int("deletePercent", 0, "the percent of writes that are deletes")
  48. b.read = cmdBenchmark.Flag.Bool("read", true, "enable read")
  49. b.sequentialRead = cmdBenchmark.Flag.Bool("readSequentially", false, "randomly read by ids from \"-list\" specified file")
  50. b.collection = cmdBenchmark.Flag.String("collection", "benchmark", "write data to this collection")
  51. b.cpuprofile = cmdBenchmark.Flag.String("cpuprofile", "", "cpu profile output file")
  52. b.maxCpu = cmdBenchmark.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
  53. b.vid2server = make(map[string]string)
  54. sharedBytes = make([]byte, 1024)
  55. }
  56. var cmdBenchmark = &Command{
  57. UsageLine: "benchmark -server=localhost:9333 -c=10 -n=100000",
  58. Short: "benchmark on writing millions of files and read out",
  59. Long: `benchmark on an empty weed file system.
  60. Two tests during benchmark:
  61. 1) write lots of small files to the system
  62. 2) read the files out
  63. The file content is mostly zero, but no compression is done.
  64. You can choose to only benchmark read or write.
  65. During write, the list of uploaded file ids is stored in "-list" specified file.
  66. You can also use your own list of file ids to run read test.
  67. Write speed and read speed will be collected.
  68. The numbers are used to get a sense of the system.
  69. Usually your network or the hard drive is the real bottleneck.
  70. Another thing to watch is whether the volumes are evenly distributed
  71. to each volume server. Because the 7 more benchmark volumes are randomly distributed
  72. to servers with free slots, it's highly possible some servers have uneven amount of
  73. benchmark volumes. To remedy this, you can use this to grow the benchmark volumes
  74. before starting the benchmark command:
  75. http://localhost:9333/vol/grow?collection=benchmark&count=5
  76. After benchmarking, you can clean up the written data by deleting the benchmark collection
  77. http://localhost:9333/col/delete?collection=benchmark
  78. `,
  79. }
  80. var (
  81. wait sync.WaitGroup
  82. writeStats *stats
  83. readStats *stats
  84. )
  85. func runbenchmark(cmd *Command, args []string) bool {
  86. fmt.Printf("This is Seaweed File System version %s %s %s\n", util.VERSION, runtime.GOOS, runtime.GOARCH)
  87. if *b.maxCpu < 1 {
  88. *b.maxCpu = runtime.NumCPU()
  89. }
  90. runtime.GOMAXPROCS(*b.maxCpu)
  91. if *b.cpuprofile != "" {
  92. f, err := os.Create(*b.cpuprofile)
  93. if err != nil {
  94. glog.Fatal(err)
  95. }
  96. pprof.StartCPUProfile(f)
  97. defer pprof.StopCPUProfile()
  98. }
  99. if *b.write {
  100. bench_write()
  101. }
  102. if *b.read {
  103. bench_read()
  104. }
  105. return true
  106. }
  107. func bench_write() {
  108. fileIdLineChan := make(chan string)
  109. finishChan := make(chan bool)
  110. writeStats = newStats(*b.concurrency)
  111. idChan := make(chan int)
  112. go writeFileIds(*b.idListFile, fileIdLineChan, finishChan)
  113. for i := 0; i < *b.concurrency; i++ {
  114. wait.Add(1)
  115. go writeFiles(idChan, fileIdLineChan, &writeStats.localStats[i])
  116. }
  117. writeStats.start = time.Now()
  118. writeStats.total = *b.numberOfFiles
  119. go writeStats.checkProgress("Writing Benchmark", finishChan)
  120. for i := 0; i < *b.numberOfFiles; i++ {
  121. idChan <- i
  122. }
  123. close(idChan)
  124. wait.Wait()
  125. writeStats.end = time.Now()
  126. wait.Add(2)
  127. finishChan <- true
  128. finishChan <- true
  129. wait.Wait()
  130. close(finishChan)
  131. writeStats.printStats()
  132. }
  133. func bench_read() {
  134. fileIdLineChan := make(chan string)
  135. finishChan := make(chan bool)
  136. readStats = newStats(*b.concurrency)
  137. go readFileIds(*b.idListFile, fileIdLineChan)
  138. readStats.start = time.Now()
  139. readStats.total = *b.numberOfFiles
  140. go readStats.checkProgress("Randomly Reading Benchmark", finishChan)
  141. for i := 0; i < *b.concurrency; i++ {
  142. wait.Add(1)
  143. go readFiles(fileIdLineChan, &readStats.localStats[i])
  144. }
  145. wait.Wait()
  146. wait.Add(1)
  147. finishChan <- true
  148. wait.Wait()
  149. close(finishChan)
  150. readStats.end = time.Now()
  151. readStats.printStats()
  152. }
  153. type delayedFile struct {
  154. enterTime time.Time
  155. fp *operation.FilePart
  156. }
  157. func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
  158. defer wait.Done()
  159. delayedDeleteChan := make(chan *delayedFile, 100)
  160. var waitForDeletions sync.WaitGroup
  161. for i := 0; i < 7; i++ {
  162. waitForDeletions.Add(1)
  163. go func() {
  164. defer waitForDeletions.Done()
  165. for df := range delayedDeleteChan {
  166. if df.enterTime.After(time.Now()) {
  167. time.Sleep(df.enterTime.Sub(time.Now()))
  168. }
  169. if e := util.Delete("http://" + df.fp.Server + "/" + df.fp.Fid); e == nil {
  170. s.completed++
  171. } else {
  172. s.failed++
  173. }
  174. }
  175. }()
  176. }
  177. for id := range idChan {
  178. start := time.Now()
  179. fileSize := int64(*b.fileSize + rand.Intn(64))
  180. fp := &operation.FilePart{Reader: &FakeReader{id: uint64(id), size: fileSize}, FileSize: fileSize}
  181. if assignResult, err := operation.Assign(*b.server, 1, "", *b.collection, ""); err == nil {
  182. fp.Server, fp.Fid, fp.Collection = assignResult.PublicUrl, assignResult.Fid, *b.collection
  183. if _, err := fp.Upload(0, *b.server); err == nil {
  184. if rand.Intn(100) < *b.deletePercentage {
  185. s.total++
  186. delayedDeleteChan <- &delayedFile{time.Now().Add(time.Second), fp}
  187. } else {
  188. fileIdLineChan <- fp.Fid
  189. }
  190. s.completed++
  191. s.transferred += fileSize
  192. } else {
  193. s.failed++
  194. fmt.Printf("Failed to write with error:%v\n", err)
  195. }
  196. writeStats.addSample(time.Now().Sub(start))
  197. if *cmdBenchmark.IsDebug {
  198. fmt.Printf("writing %d file %s\n", id, fp.Fid)
  199. }
  200. } else {
  201. s.failed++
  202. println("writing file error:", err.Error())
  203. }
  204. }
  205. close(delayedDeleteChan)
  206. waitForDeletions.Wait()
  207. }
  208. func readFiles(fileIdLineChan chan string, s *stat) {
  209. defer wait.Done()
  210. masterLimitChan := make(chan bool, 1)
  211. for fid := range fileIdLineChan {
  212. if len(fid) == 0 {
  213. continue
  214. }
  215. if fid[0] == '#' {
  216. continue
  217. }
  218. if *cmdBenchmark.IsDebug {
  219. fmt.Printf("reading file %s\n", fid)
  220. }
  221. parts := strings.SplitN(fid, ",", 2)
  222. vid := parts[0]
  223. start := time.Now()
  224. if server, ok := b.vid2server[vid]; !ok {
  225. masterLimitChan <- true
  226. if _, now_ok := b.vid2server[vid]; !now_ok {
  227. if ret, err := operation.Lookup(*b.server, vid); err == nil {
  228. if len(ret.Locations) > 0 {
  229. server = ret.Locations[0].PublicUrl
  230. b.vid2server[vid] = server
  231. }
  232. }
  233. }
  234. <-masterLimitChan
  235. }
  236. if server, ok := b.vid2server[vid]; ok {
  237. url := "http://" + server + "/" + fid
  238. if bytesRead, err := util.Get(url); err == nil {
  239. s.completed++
  240. s.transferred += int64(len(bytesRead))
  241. readStats.addSample(time.Now().Sub(start))
  242. } else {
  243. s.failed++
  244. fmt.Printf("Failed to read %s error:%v\n", url, err)
  245. }
  246. } else {
  247. s.failed++
  248. println("!!!! volume id ", vid, " location not found!!!!!")
  249. }
  250. }
  251. }
  252. func writeFileIds(fileName string, fileIdLineChan chan string, finishChan chan bool) {
  253. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  254. if err != nil {
  255. glog.Fatalf("File to create file %s: %s\n", fileName, err)
  256. }
  257. defer file.Close()
  258. for {
  259. select {
  260. case <-finishChan:
  261. wait.Done()
  262. return
  263. case line := <-fileIdLineChan:
  264. file.Write([]byte(line))
  265. file.Write([]byte("\n"))
  266. }
  267. }
  268. }
  269. func readFileIds(fileName string, fileIdLineChan chan string) {
  270. file, err := os.Open(fileName) // For read access.
  271. if err != nil {
  272. glog.Fatalf("File to read file %s: %s\n", fileName, err)
  273. }
  274. defer file.Close()
  275. r := bufio.NewReader(file)
  276. if *b.sequentialRead {
  277. for {
  278. if line, err := Readln(r); err == nil {
  279. fileIdLineChan <- string(line)
  280. } else {
  281. break
  282. }
  283. }
  284. } else {
  285. lines := make([]string, 0, readStats.total)
  286. for {
  287. if line, err := Readln(r); err == nil {
  288. lines = append(lines, string(line))
  289. } else {
  290. break
  291. }
  292. }
  293. if len(lines) > 0 {
  294. for i := 0; i < readStats.total; i++ {
  295. fileIdLineChan <- lines[rand.Intn(len(lines))]
  296. }
  297. }
  298. }
  299. close(fileIdLineChan)
  300. }
  301. const (
  302. benchResolution = 10000 //0.1 microsecond
  303. benchBucket = 1000000000 / benchResolution
  304. )
  305. // An efficient statics collecting and rendering
  306. type stats struct {
  307. data []int
  308. overflow []int
  309. localStats []stat
  310. start time.Time
  311. end time.Time
  312. total int
  313. }
  314. type stat struct {
  315. completed int
  316. failed int
  317. total int
  318. transferred int64
  319. }
  320. var percentages = []int{50, 66, 75, 80, 90, 95, 98, 99, 100}
  321. func newStats(n int) *stats {
  322. return &stats{
  323. data: make([]int, benchResolution),
  324. overflow: make([]int, 0),
  325. localStats: make([]stat, n),
  326. }
  327. }
  328. func (s *stats) addSample(d time.Duration) {
  329. index := int(d / benchBucket)
  330. if index < 0 {
  331. fmt.Printf("This request takes %3.1f seconds, skipping!\n", float64(index)/10000)
  332. } else if index < len(s.data) {
  333. s.data[int(d/benchBucket)]++
  334. } else {
  335. s.overflow = append(s.overflow, index)
  336. }
  337. }
  338. func (s *stats) checkProgress(testName string, finishChan chan bool) {
  339. fmt.Printf("\n------------ %s ----------\n", testName)
  340. ticker := time.Tick(time.Second)
  341. lastCompleted, lastTransferred, lastTime := 0, int64(0), time.Now()
  342. for {
  343. select {
  344. case <-finishChan:
  345. wait.Done()
  346. return
  347. case t := <-ticker:
  348. completed, transferred, taken, total := 0, int64(0), t.Sub(lastTime), s.total
  349. for _, localStat := range s.localStats {
  350. completed += localStat.completed
  351. transferred += localStat.transferred
  352. total += localStat.total
  353. }
  354. fmt.Printf("Completed %d of %d requests, %3.1f%% %3.1f/s %3.1fMB/s\n",
  355. completed, total, float64(completed)*100/float64(total),
  356. float64(completed-lastCompleted)*float64(int64(time.Second))/float64(int64(taken)),
  357. float64(transferred-lastTransferred)*float64(int64(time.Second))/float64(int64(taken))/float64(1024*1024),
  358. )
  359. lastCompleted, lastTransferred, lastTime = completed, transferred, t
  360. }
  361. }
  362. }
  363. func (s *stats) printStats() {
  364. completed, failed, transferred, total := 0, 0, int64(0), s.total
  365. for _, localStat := range s.localStats {
  366. completed += localStat.completed
  367. failed += localStat.failed
  368. transferred += localStat.transferred
  369. total += localStat.total
  370. }
  371. timeTaken := float64(int64(s.end.Sub(s.start))) / 1000000000
  372. fmt.Printf("\nConcurrency Level: %d\n", *b.concurrency)
  373. fmt.Printf("Time taken for tests: %.3f seconds\n", timeTaken)
  374. fmt.Printf("Complete requests: %d\n", completed)
  375. fmt.Printf("Failed requests: %d\n", failed)
  376. fmt.Printf("Total transferred: %d bytes\n", transferred)
  377. fmt.Printf("Requests per second: %.2f [#/sec]\n", float64(completed)/timeTaken)
  378. fmt.Printf("Transfer rate: %.2f [Kbytes/sec]\n", float64(transferred)/1024/timeTaken)
  379. n, sum := 0, 0
  380. min, max := 10000000, 0
  381. for i := 0; i < len(s.data); i++ {
  382. n += s.data[i]
  383. sum += s.data[i] * i
  384. if s.data[i] > 0 {
  385. if min > i {
  386. min = i
  387. }
  388. if max < i {
  389. max = i
  390. }
  391. }
  392. }
  393. n += len(s.overflow)
  394. for i := 0; i < len(s.overflow); i++ {
  395. sum += s.overflow[i]
  396. if min > s.overflow[i] {
  397. min = s.overflow[i]
  398. }
  399. if max < s.overflow[i] {
  400. max = s.overflow[i]
  401. }
  402. }
  403. avg := float64(sum) / float64(n)
  404. varianceSum := 0.0
  405. for i := 0; i < len(s.data); i++ {
  406. if s.data[i] > 0 {
  407. d := float64(i) - avg
  408. varianceSum += d * d * float64(s.data[i])
  409. }
  410. }
  411. for i := 0; i < len(s.overflow); i++ {
  412. d := float64(s.overflow[i]) - avg
  413. varianceSum += d * d
  414. }
  415. std := math.Sqrt(varianceSum / float64(n))
  416. fmt.Printf("\nConnection Times (ms)\n")
  417. fmt.Printf(" min avg max std\n")
  418. fmt.Printf("Total: %2.1f %3.1f %3.1f %3.1f\n", float32(min)/10, float32(avg)/10, float32(max)/10, std/10)
  419. //printing percentiles
  420. fmt.Printf("\nPercentage of the requests served within a certain time (ms)\n")
  421. percentiles := make([]int, len(percentages))
  422. for i := 0; i < len(percentages); i++ {
  423. percentiles[i] = n * percentages[i] / 100
  424. }
  425. percentiles[len(percentiles)-1] = n
  426. percentileIndex := 0
  427. currentSum := 0
  428. for i := 0; i < len(s.data); i++ {
  429. currentSum += s.data[i]
  430. if s.data[i] > 0 && percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  431. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(i)/10.0)
  432. percentileIndex++
  433. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  434. percentileIndex++
  435. }
  436. }
  437. }
  438. sort.Ints(s.overflow)
  439. for i := 0; i < len(s.overflow); i++ {
  440. currentSum++
  441. if percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  442. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(s.overflow[i])/10.0)
  443. percentileIndex++
  444. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  445. percentileIndex++
  446. }
  447. }
  448. }
  449. }
  450. // a fake reader to generate content to upload
  451. type FakeReader struct {
  452. id uint64 // an id number
  453. size int64 // max bytes
  454. }
  455. func (l *FakeReader) Read(p []byte) (n int, err error) {
  456. if l.size <= 0 {
  457. return 0, io.EOF
  458. }
  459. if int64(len(p)) > l.size {
  460. n = int(l.size)
  461. } else {
  462. n = len(p)
  463. }
  464. if n >= 8 {
  465. for i := 0; i < 8; i++ {
  466. p[i] = byte(l.id >> uint(i*8))
  467. }
  468. }
  469. l.size -= int64(n)
  470. return
  471. }
  472. func (l *FakeReader) WriteTo(w io.Writer) (n int64, err error) {
  473. size := int(l.size)
  474. bufferSize := len(sharedBytes)
  475. for size > 0 {
  476. tempBuffer := sharedBytes
  477. if size < bufferSize {
  478. tempBuffer = sharedBytes[0:size]
  479. }
  480. count, e := w.Write(tempBuffer)
  481. if e != nil {
  482. return int64(size), e
  483. }
  484. size -= count
  485. }
  486. return l.size, nil
  487. }
  488. func Readln(r *bufio.Reader) ([]byte, error) {
  489. var (
  490. isPrefix bool = true
  491. err error = nil
  492. line, ln []byte
  493. )
  494. for isPrefix && err == nil {
  495. line, isPrefix, err = r.ReadLine()
  496. ln = append(ln, line...)
  497. }
  498. return ln, err
  499. }