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.

547 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. serverLimitChan map[string]chan bool
  85. )
  86. func init() {
  87. serverLimitChan = make(map[string]chan bool)
  88. }
  89. func runbenchmark(cmd *Command, args []string) bool {
  90. fmt.Printf("This is Seaweed File System version %s %s %s\n", util.VERSION, runtime.GOOS, runtime.GOARCH)
  91. if *b.maxCpu < 1 {
  92. *b.maxCpu = runtime.NumCPU()
  93. }
  94. runtime.GOMAXPROCS(*b.maxCpu)
  95. if *b.cpuprofile != "" {
  96. f, err := os.Create(*b.cpuprofile)
  97. if err != nil {
  98. glog.Fatal(err)
  99. }
  100. pprof.StartCPUProfile(f)
  101. defer pprof.StopCPUProfile()
  102. }
  103. if *b.write {
  104. bench_write()
  105. }
  106. if *b.read {
  107. bench_read()
  108. }
  109. return true
  110. }
  111. func bench_write() {
  112. fileIdLineChan := make(chan string)
  113. finishChan := make(chan bool)
  114. writeStats = newStats()
  115. idChan := make(chan int)
  116. wait.Add(*b.concurrency)
  117. go writeFileIds(*b.idListFile, fileIdLineChan, finishChan)
  118. for i := 0; i < *b.concurrency; i++ {
  119. go writeFiles(idChan, fileIdLineChan, writeStats)
  120. }
  121. writeStats.start = time.Now()
  122. writeStats.total = *b.numberOfFiles
  123. go writeStats.checkProgress("Writing Benchmark", finishChan)
  124. for i := 0; i < *b.numberOfFiles; i++ {
  125. idChan <- i
  126. }
  127. close(idChan)
  128. wait.Wait()
  129. writeStats.end = time.Now()
  130. wait.Add(1)
  131. finishChan <- true
  132. finishChan <- true
  133. close(finishChan)
  134. wait.Wait()
  135. writeStats.printStats()
  136. }
  137. func bench_read() {
  138. fileIdLineChan := make(chan string)
  139. finishChan := make(chan bool)
  140. readStats = newStats()
  141. wait.Add(*b.concurrency)
  142. go readFileIds(*b.idListFile, fileIdLineChan)
  143. readStats.start = time.Now()
  144. readStats.total = *b.numberOfFiles
  145. go readStats.checkProgress("Randomly Reading Benchmark", finishChan)
  146. for i := 0; i < *b.concurrency; i++ {
  147. go readFiles(fileIdLineChan, readStats)
  148. }
  149. wait.Wait()
  150. finishChan <- true
  151. close(finishChan)
  152. readStats.end = time.Now()
  153. readStats.printStats()
  154. }
  155. type delayedFile struct {
  156. enterTime time.Time
  157. fp *operation.FilePart
  158. }
  159. func writeFiles(idChan chan int, fileIdLineChan chan string, s *stats) {
  160. delayedDeleteChan := make(chan *delayedFile, 100)
  161. var waitForDeletions sync.WaitGroup
  162. for i := 0; i < 7; i++ {
  163. go func() {
  164. waitForDeletions.Add(1)
  165. for df := range delayedDeleteChan {
  166. if df == nil {
  167. break
  168. }
  169. if df.enterTime.After(time.Now()) {
  170. time.Sleep(df.enterTime.Sub(time.Now()))
  171. }
  172. fp := df.fp
  173. serverLimitChan[fp.Server] <- true
  174. if e := util.Delete("http://" + fp.Server + "/" + fp.Fid); e == nil {
  175. s.completed++
  176. } else {
  177. s.failed++
  178. }
  179. <-serverLimitChan[fp.Server]
  180. }
  181. waitForDeletions.Done()
  182. }()
  183. }
  184. for {
  185. if id, ok := <-idChan; ok {
  186. start := time.Now()
  187. fileSize := int64(*b.fileSize + rand.Intn(64))
  188. fp := &operation.FilePart{Reader: &FakeReader{id: uint64(id), size: fileSize}, FileSize: fileSize}
  189. if assignResult, err := operation.Assign(*b.server, 1, "", *b.collection, ""); err == nil {
  190. fp.Server, fp.Fid, fp.Collection = assignResult.PublicUrl, assignResult.Fid, *b.collection
  191. if _, ok := serverLimitChan[fp.Server]; !ok {
  192. serverLimitChan[fp.Server] = make(chan bool, 7)
  193. }
  194. serverLimitChan[fp.Server] <- true
  195. if _, err := fp.Upload(0, *b.server); err == nil {
  196. if rand.Intn(100) < *b.deletePercentage {
  197. s.total++
  198. delayedDeleteChan <- &delayedFile{time.Now().Add(time.Second), fp}
  199. } else {
  200. fileIdLineChan <- fp.Fid
  201. }
  202. s.completed++
  203. s.transferred += fileSize
  204. } else {
  205. s.failed++
  206. }
  207. writeStats.addSample(time.Now().Sub(start))
  208. <-serverLimitChan[fp.Server]
  209. if *cmdBenchmark.IsDebug {
  210. fmt.Printf("writing %d file %s\n", id, fp.Fid)
  211. }
  212. } else {
  213. s.failed++
  214. println("writing file error:", err.Error())
  215. }
  216. } else {
  217. break
  218. }
  219. }
  220. close(delayedDeleteChan)
  221. waitForDeletions.Wait()
  222. wait.Done()
  223. }
  224. func readFiles(fileIdLineChan chan string, s *stats) {
  225. serverLimitChan := make(map[string]chan bool)
  226. masterLimitChan := make(chan bool, 1)
  227. for {
  228. if fid, ok := <-fileIdLineChan; ok {
  229. if len(fid) == 0 {
  230. continue
  231. }
  232. if fid[0] == '#' {
  233. continue
  234. }
  235. if *cmdBenchmark.IsDebug {
  236. fmt.Printf("reading file %s\n", fid)
  237. }
  238. parts := strings.SplitN(fid, ",", 2)
  239. vid := parts[0]
  240. start := time.Now()
  241. if server, ok := b.vid2server[vid]; !ok {
  242. masterLimitChan <- true
  243. if _, now_ok := b.vid2server[vid]; !now_ok {
  244. if ret, err := operation.Lookup(*b.server, vid); err == nil {
  245. if len(ret.Locations) > 0 {
  246. server = ret.Locations[0].PublicUrl
  247. b.vid2server[vid] = server
  248. }
  249. }
  250. }
  251. <-masterLimitChan
  252. }
  253. if server, ok := b.vid2server[vid]; ok {
  254. if _, ok := serverLimitChan[server]; !ok {
  255. serverLimitChan[server] = make(chan bool, 7)
  256. }
  257. serverLimitChan[server] <- true
  258. url := "http://" + server + "/" + fid
  259. if bytesRead, err := util.Get(url); err == nil {
  260. s.completed++
  261. s.transferred += int64(len(bytesRead))
  262. readStats.addSample(time.Now().Sub(start))
  263. } else {
  264. s.failed++
  265. println("!!!! Failed to read from ", url, " !!!!!")
  266. }
  267. <-serverLimitChan[server]
  268. } else {
  269. s.failed++
  270. println("!!!! volume id ", vid, " location not found!!!!!")
  271. }
  272. } else {
  273. break
  274. }
  275. }
  276. wait.Done()
  277. }
  278. func writeFileIds(fileName string, fileIdLineChan chan string, finishChan chan bool) {
  279. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  280. if err != nil {
  281. glog.Fatalf("File to create file %s: %s\n", fileName, err)
  282. }
  283. defer file.Close()
  284. for {
  285. select {
  286. case <-finishChan:
  287. wait.Done()
  288. return
  289. case line := <-fileIdLineChan:
  290. file.Write([]byte(line))
  291. file.Write([]byte("\n"))
  292. }
  293. }
  294. }
  295. func readFileIds(fileName string, fileIdLineChan chan string) {
  296. file, err := os.Open(fileName) // For read access.
  297. if err != nil {
  298. glog.Fatalf("File to read file %s: %s\n", fileName, err)
  299. }
  300. defer file.Close()
  301. r := bufio.NewReader(file)
  302. if *b.sequentialRead {
  303. for {
  304. if line, err := Readln(r); err == nil {
  305. fileIdLineChan <- string(line)
  306. } else {
  307. break
  308. }
  309. }
  310. } else {
  311. lines := make([]string, 0, readStats.total)
  312. for {
  313. if line, err := Readln(r); err == nil {
  314. lines = append(lines, string(line))
  315. } else {
  316. break
  317. }
  318. }
  319. if len(lines) > 0 {
  320. for i := 0; i < readStats.total; i++ {
  321. fileIdLineChan <- lines[rand.Intn(len(lines))]
  322. }
  323. }
  324. }
  325. close(fileIdLineChan)
  326. }
  327. const (
  328. benchResolution = 10000 //0.1 microsecond
  329. benchBucket = 1000000000 / benchResolution
  330. )
  331. // An efficient statics collecting and rendering
  332. type stats struct {
  333. data []int
  334. overflow []int
  335. completed int
  336. failed int
  337. total int
  338. transferred int64
  339. start time.Time
  340. end time.Time
  341. }
  342. var percentages = []int{50, 66, 75, 80, 90, 95, 98, 99, 100}
  343. func newStats() *stats {
  344. return &stats{data: make([]int, benchResolution), overflow: make([]int, 0)}
  345. }
  346. func (s *stats) addSample(d time.Duration) {
  347. index := int(d / benchBucket)
  348. if index < 0 {
  349. fmt.Printf("This request takes %3.1f seconds, skipping!\n", float64(index)/10000)
  350. } else if index < len(s.data) {
  351. s.data[int(d/benchBucket)]++
  352. } else {
  353. s.overflow = append(s.overflow, index)
  354. }
  355. }
  356. func (s *stats) checkProgress(testName string, finishChan chan bool) {
  357. fmt.Printf("\n------------ %s ----------\n", testName)
  358. ticker := time.Tick(time.Second)
  359. lastCompleted, lastTransferred, lastTime := 0, int64(0), time.Now()
  360. for {
  361. select {
  362. case <-finishChan:
  363. return
  364. case t := <-ticker:
  365. completed, transferred, taken := s.completed-lastCompleted, s.transferred-lastTransferred, t.Sub(lastTime)
  366. fmt.Printf("Completed %d of %d requests, %3.1f%% %3.1f/s %3.1fMB/s\n",
  367. s.completed, s.total, float64(s.completed)*100/float64(s.total),
  368. float64(completed)*float64(int64(time.Second))/float64(int64(taken)),
  369. float64(transferred)*float64(int64(time.Second))/float64(int64(taken))/float64(1024*1024),
  370. )
  371. lastCompleted, lastTransferred, lastTime = s.completed, s.transferred, t
  372. }
  373. }
  374. }
  375. func (s *stats) printStats() {
  376. timeTaken := float64(int64(s.end.Sub(s.start))) / 1000000000
  377. fmt.Printf("\nConcurrency Level: %d\n", *b.concurrency)
  378. fmt.Printf("Time taken for tests: %.3f seconds\n", timeTaken)
  379. fmt.Printf("Complete requests: %d\n", s.completed)
  380. fmt.Printf("Failed requests: %d\n", s.failed)
  381. fmt.Printf("Total transferred: %d bytes\n", s.transferred)
  382. fmt.Printf("Requests per second: %.2f [#/sec]\n", float64(s.completed)/timeTaken)
  383. fmt.Printf("Transfer rate: %.2f [Kbytes/sec]\n", float64(s.transferred)/1024/timeTaken)
  384. n, sum := 0, 0
  385. min, max := 10000000, 0
  386. for i := 0; i < len(s.data); i++ {
  387. n += s.data[i]
  388. sum += s.data[i] * i
  389. if s.data[i] > 0 {
  390. if min > i {
  391. min = i
  392. }
  393. if max < i {
  394. max = i
  395. }
  396. }
  397. }
  398. n += len(s.overflow)
  399. for i := 0; i < len(s.overflow); i++ {
  400. sum += s.overflow[i]
  401. if min > s.overflow[i] {
  402. min = s.overflow[i]
  403. }
  404. if max < s.overflow[i] {
  405. max = s.overflow[i]
  406. }
  407. }
  408. avg := float64(sum) / float64(n)
  409. varianceSum := 0.0
  410. for i := 0; i < len(s.data); i++ {
  411. if s.data[i] > 0 {
  412. d := float64(i) - avg
  413. varianceSum += d * d * float64(s.data[i])
  414. }
  415. }
  416. for i := 0; i < len(s.overflow); i++ {
  417. d := float64(s.overflow[i]) - avg
  418. varianceSum += d * d
  419. }
  420. std := math.Sqrt(varianceSum / float64(n))
  421. fmt.Printf("\nConnection Times (ms)\n")
  422. fmt.Printf(" min avg max std\n")
  423. fmt.Printf("Total: %2.1f %3.1f %3.1f %3.1f\n", float32(min)/10, float32(avg)/10, float32(max)/10, std/10)
  424. //printing percentiles
  425. fmt.Printf("\nPercentage of the requests served within a certain time (ms)\n")
  426. percentiles := make([]int, len(percentages))
  427. for i := 0; i < len(percentages); i++ {
  428. percentiles[i] = n * percentages[i] / 100
  429. }
  430. percentiles[len(percentiles)-1] = n
  431. percentileIndex := 0
  432. currentSum := 0
  433. for i := 0; i < len(s.data); i++ {
  434. currentSum += s.data[i]
  435. if s.data[i] > 0 && percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  436. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(i)/10.0)
  437. percentileIndex++
  438. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  439. percentileIndex++
  440. }
  441. }
  442. }
  443. sort.Ints(s.overflow)
  444. for i := 0; i < len(s.overflow); i++ {
  445. currentSum++
  446. if percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  447. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(s.overflow[i])/10.0)
  448. percentileIndex++
  449. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  450. percentileIndex++
  451. }
  452. }
  453. }
  454. }
  455. // a fake reader to generate content to upload
  456. type FakeReader struct {
  457. id uint64 // an id number
  458. size int64 // max bytes
  459. }
  460. func (l *FakeReader) Read(p []byte) (n int, err error) {
  461. if l.size <= 0 {
  462. return 0, io.EOF
  463. }
  464. if int64(len(p)) > l.size {
  465. n = int(l.size)
  466. } else {
  467. n = len(p)
  468. }
  469. if n >= 8 {
  470. for i := 0; i < 8; i++ {
  471. p[i] = byte(l.id >> uint(i*8))
  472. }
  473. }
  474. l.size -= int64(n)
  475. return
  476. }
  477. func (l *FakeReader) WriteTo(w io.Writer) (n int64, err error) {
  478. size := int(l.size)
  479. bufferSize := len(sharedBytes)
  480. for size > 0 {
  481. tempBuffer := sharedBytes
  482. if size < bufferSize {
  483. tempBuffer = sharedBytes[0:size]
  484. }
  485. count, e := w.Write(tempBuffer)
  486. if e != nil {
  487. return int64(size), e
  488. }
  489. size -= count
  490. }
  491. return l.size, nil
  492. }
  493. func Readln(r *bufio.Reader) ([]byte, error) {
  494. var (
  495. isPrefix bool = true
  496. err error = nil
  497. line, ln []byte
  498. )
  499. for isPrefix && err == nil {
  500. line, isPrefix, err = r.ReadLine()
  501. ln = append(ln, line...)
  502. }
  503. return ln, err
  504. }