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.

532 lines
14 KiB

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