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.

536 lines
15 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package command
  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/weed/glog"
  16. "github.com/chrislusf/seaweedfs/weed/operation"
  17. "github.com/chrislusf/seaweedfs/weed/security"
  18. "github.com/chrislusf/seaweedfs/weed/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. ar := &operation.VolumeAssignRequest{
  185. Count: 1,
  186. Collection: *b.collection,
  187. }
  188. if assignResult, err := operation.Assign(*b.server, ar); err == nil {
  189. fp.Server, fp.Fid, fp.Collection = assignResult.Url, assignResult.Fid, *b.collection
  190. if _, err := fp.Upload(0, *b.server, secret); err == nil {
  191. if rand.Intn(100) < *b.deletePercentage {
  192. s.total++
  193. delayedDeleteChan <- &delayedFile{time.Now().Add(time.Second), fp}
  194. } else {
  195. fileIdLineChan <- fp.Fid
  196. }
  197. s.completed++
  198. s.transferred += fileSize
  199. } else {
  200. s.failed++
  201. fmt.Printf("Failed to write with error:%v\n", err)
  202. }
  203. writeStats.addSample(time.Now().Sub(start))
  204. if *cmdBenchmark.IsDebug {
  205. fmt.Printf("writing %d file %s\n", id, fp.Fid)
  206. }
  207. } else {
  208. s.failed++
  209. println("writing file error:", err.Error())
  210. }
  211. }
  212. close(delayedDeleteChan)
  213. waitForDeletions.Wait()
  214. }
  215. func readFiles(fileIdLineChan chan string, s *stat) {
  216. defer wait.Done()
  217. for fid := range fileIdLineChan {
  218. if len(fid) == 0 {
  219. continue
  220. }
  221. if fid[0] == '#' {
  222. continue
  223. }
  224. if *cmdBenchmark.IsDebug {
  225. fmt.Printf("reading file %s\n", fid)
  226. }
  227. parts := strings.SplitN(fid, ",", 2)
  228. vid := parts[0]
  229. start := time.Now()
  230. ret, err := operation.Lookup(*b.server, vid)
  231. if err != nil || len(ret.Locations) == 0 {
  232. s.failed++
  233. println("!!!! volume id ", vid, " location not found!!!!!")
  234. continue
  235. }
  236. server := ret.Locations[rand.Intn(len(ret.Locations))].Url
  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. }
  247. }
  248. func writeFileIds(fileName string, fileIdLineChan chan string, finishChan chan bool) {
  249. file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  250. if err != nil {
  251. glog.Fatalf("File to create file %s: %s\n", fileName, err)
  252. }
  253. defer file.Close()
  254. for {
  255. select {
  256. case <-finishChan:
  257. wait.Done()
  258. return
  259. case line := <-fileIdLineChan:
  260. file.Write([]byte(line))
  261. file.Write([]byte("\n"))
  262. }
  263. }
  264. }
  265. func readFileIds(fileName string, fileIdLineChan chan string) {
  266. file, err := os.Open(fileName) // For read access.
  267. if err != nil {
  268. glog.Fatalf("File to read file %s: %s\n", fileName, err)
  269. }
  270. defer file.Close()
  271. r := bufio.NewReader(file)
  272. if *b.sequentialRead {
  273. for {
  274. if line, err := Readln(r); err == nil {
  275. fileIdLineChan <- string(line)
  276. } else {
  277. break
  278. }
  279. }
  280. } else {
  281. lines := make([]string, 0, readStats.total)
  282. for {
  283. if line, err := Readln(r); err == nil {
  284. lines = append(lines, string(line))
  285. } else {
  286. break
  287. }
  288. }
  289. if len(lines) > 0 {
  290. for i := 0; i < readStats.total; i++ {
  291. fileIdLineChan <- lines[rand.Intn(len(lines))]
  292. }
  293. }
  294. }
  295. close(fileIdLineChan)
  296. }
  297. const (
  298. benchResolution = 10000 //0.1 microsecond
  299. benchBucket = 1000000000 / benchResolution
  300. )
  301. // An efficient statics collecting and rendering
  302. type stats struct {
  303. data []int
  304. overflow []int
  305. localStats []stat
  306. start time.Time
  307. end time.Time
  308. total int
  309. }
  310. type stat struct {
  311. completed int
  312. failed int
  313. total int
  314. transferred int64
  315. }
  316. var percentages = []int{50, 66, 75, 80, 90, 95, 98, 99, 100}
  317. func newStats(n int) *stats {
  318. return &stats{
  319. data: make([]int, benchResolution),
  320. overflow: make([]int, 0),
  321. localStats: make([]stat, n),
  322. }
  323. }
  324. func (s *stats) addSample(d time.Duration) {
  325. index := int(d / benchBucket)
  326. if index < 0 {
  327. fmt.Printf("This request takes %3.1f seconds, skipping!\n", float64(index)/10000)
  328. } else if index < len(s.data) {
  329. s.data[int(d/benchBucket)]++
  330. } else {
  331. s.overflow = append(s.overflow, index)
  332. }
  333. }
  334. func (s *stats) checkProgress(testName string, finishChan chan bool) {
  335. fmt.Printf("\n------------ %s ----------\n", testName)
  336. ticker := time.Tick(time.Second)
  337. lastCompleted, lastTransferred, lastTime := 0, int64(0), time.Now()
  338. for {
  339. select {
  340. case <-finishChan:
  341. wait.Done()
  342. return
  343. case t := <-ticker:
  344. completed, transferred, taken, total := 0, int64(0), t.Sub(lastTime), s.total
  345. for _, localStat := range s.localStats {
  346. completed += localStat.completed
  347. transferred += localStat.transferred
  348. total += localStat.total
  349. }
  350. fmt.Printf("Completed %d of %d requests, %3.1f%% %3.1f/s %3.1fMB/s\n",
  351. completed, total, float64(completed)*100/float64(total),
  352. float64(completed-lastCompleted)*float64(int64(time.Second))/float64(int64(taken)),
  353. float64(transferred-lastTransferred)*float64(int64(time.Second))/float64(int64(taken))/float64(1024*1024),
  354. )
  355. lastCompleted, lastTransferred, lastTime = completed, transferred, t
  356. }
  357. }
  358. }
  359. func (s *stats) printStats() {
  360. completed, failed, transferred, total := 0, 0, int64(0), s.total
  361. for _, localStat := range s.localStats {
  362. completed += localStat.completed
  363. failed += localStat.failed
  364. transferred += localStat.transferred
  365. total += localStat.total
  366. }
  367. timeTaken := float64(int64(s.end.Sub(s.start))) / 1000000000
  368. fmt.Printf("\nConcurrency Level: %d\n", *b.concurrency)
  369. fmt.Printf("Time taken for tests: %.3f seconds\n", timeTaken)
  370. fmt.Printf("Complete requests: %d\n", completed)
  371. fmt.Printf("Failed requests: %d\n", failed)
  372. fmt.Printf("Total transferred: %d bytes\n", transferred)
  373. fmt.Printf("Requests per second: %.2f [#/sec]\n", float64(completed)/timeTaken)
  374. fmt.Printf("Transfer rate: %.2f [Kbytes/sec]\n", float64(transferred)/1024/timeTaken)
  375. n, sum := 0, 0
  376. min, max := 10000000, 0
  377. for i := 0; i < len(s.data); i++ {
  378. n += s.data[i]
  379. sum += s.data[i] * i
  380. if s.data[i] > 0 {
  381. if min > i {
  382. min = i
  383. }
  384. if max < i {
  385. max = i
  386. }
  387. }
  388. }
  389. n += len(s.overflow)
  390. for i := 0; i < len(s.overflow); i++ {
  391. sum += s.overflow[i]
  392. if min > s.overflow[i] {
  393. min = s.overflow[i]
  394. }
  395. if max < s.overflow[i] {
  396. max = s.overflow[i]
  397. }
  398. }
  399. avg := float64(sum) / float64(n)
  400. varianceSum := 0.0
  401. for i := 0; i < len(s.data); i++ {
  402. if s.data[i] > 0 {
  403. d := float64(i) - avg
  404. varianceSum += d * d * float64(s.data[i])
  405. }
  406. }
  407. for i := 0; i < len(s.overflow); i++ {
  408. d := float64(s.overflow[i]) - avg
  409. varianceSum += d * d
  410. }
  411. std := math.Sqrt(varianceSum / float64(n))
  412. fmt.Printf("\nConnection Times (ms)\n")
  413. fmt.Printf(" min avg max std\n")
  414. fmt.Printf("Total: %2.1f %3.1f %3.1f %3.1f\n", float32(min)/10, float32(avg)/10, float32(max)/10, std/10)
  415. //printing percentiles
  416. fmt.Printf("\nPercentage of the requests served within a certain time (ms)\n")
  417. percentiles := make([]int, len(percentages))
  418. for i := 0; i < len(percentages); i++ {
  419. percentiles[i] = n * percentages[i] / 100
  420. }
  421. percentiles[len(percentiles)-1] = n
  422. percentileIndex := 0
  423. currentSum := 0
  424. for i := 0; i < len(s.data); i++ {
  425. currentSum += s.data[i]
  426. if s.data[i] > 0 && percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  427. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(i)/10.0)
  428. percentileIndex++
  429. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  430. percentileIndex++
  431. }
  432. }
  433. }
  434. sort.Ints(s.overflow)
  435. for i := 0; i < len(s.overflow); i++ {
  436. currentSum++
  437. if percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  438. fmt.Printf(" %3d%% %5.1f ms\n", percentages[percentileIndex], float32(s.overflow[i])/10.0)
  439. percentileIndex++
  440. for percentileIndex < len(percentiles) && currentSum >= percentiles[percentileIndex] {
  441. percentileIndex++
  442. }
  443. }
  444. }
  445. }
  446. // a fake reader to generate content to upload
  447. type FakeReader struct {
  448. id uint64 // an id number
  449. size int64 // max bytes
  450. }
  451. func (l *FakeReader) Read(p []byte) (n int, err error) {
  452. if l.size <= 0 {
  453. return 0, io.EOF
  454. }
  455. if int64(len(p)) > l.size {
  456. n = int(l.size)
  457. } else {
  458. n = len(p)
  459. }
  460. if n >= 8 {
  461. for i := 0; i < 8; i++ {
  462. p[i] = byte(l.id >> uint(i*8))
  463. }
  464. }
  465. l.size -= int64(n)
  466. return
  467. }
  468. func (l *FakeReader) WriteTo(w io.Writer) (n int64, err error) {
  469. size := int(l.size)
  470. bufferSize := len(sharedBytes)
  471. for size > 0 {
  472. tempBuffer := sharedBytes
  473. if size < bufferSize {
  474. tempBuffer = sharedBytes[0:size]
  475. }
  476. count, e := w.Write(tempBuffer)
  477. if e != nil {
  478. return int64(size), e
  479. }
  480. size -= count
  481. }
  482. return l.size, nil
  483. }
  484. func Readln(r *bufio.Reader) ([]byte, error) {
  485. var (
  486. isPrefix = true
  487. err error
  488. line, ln []byte
  489. )
  490. for isPrefix && err == nil {
  491. line, isPrefix, err = r.ReadLine()
  492. ln = append(ln, line...)
  493. }
  494. return ln, err
  495. }